-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbuilder.rs
More file actions
774 lines (706 loc) · 29 KB
/
builder.rs
File metadata and controls
774 lines (706 loc) · 29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
//! Zone payload builder.
//!
//! Builds zone blocks by executing `advanceTempo` system transactions (one per L1 block)
//! followed by pool transactions and a withdrawal batch finalization.
use crate::{
abi::{self, ZONE_INBOX_ADDRESS, ZONE_OUTBOX_ADDRESS},
evm::ZoneEvmConfig,
ext::TempoStateExt,
l1::PreparedL1Block,
payload::ZonePayloadAttributes,
};
use alloy_consensus::{Signed, Transaction, TxLegacy, TxReceipt};
use alloy_eips::eip4895::Withdrawals;
use alloy_primitives::{B256, Bytes, U256};
use alloy_rlp::Encodable;
use alloy_sol_types::{SolCall, SolEvent};
use either::Either;
use reth_basic_payload_builder::{
BuildArguments, BuildOutcome, MissingPayloadBehaviour, PayloadBuilder, PayloadConfig,
};
use reth_chainspec::{ChainSpecProvider, EthereumHardforks};
use reth_errors::ProviderError;
use reth_evm::{
ConfigureEvm, Database, NextBlockEnvAttributes,
execute::{BlockBuilder, BlockBuilderOutcome, BlockExecutionOutput},
};
use reth_node_api::FullNodeTypes;
use reth_node_builder::{BuilderContext, components::PayloadBuilderBuilder};
use reth_payload_builder::{EthBuiltPayload, PayloadBuilderError};
use reth_payload_primitives::{BuiltPayloadExecutedBlock, PayloadAttributes};
use reth_primitives_traits::{AlloyBlockHeader as _, Recovered};
use reth_revm::{State, database::StateProviderDatabase};
use reth_storage_api::{StateProvider, StateProviderFactory};
use reth_transaction_pool::{
BestTransactions, BestTransactionsAttributes, TransactionPool,
error::InvalidPoolTransactionError,
};
use std::{sync::Arc, time::Instant};
use tempo_chainspec::spec::TempoChainSpec;
use tempo_evm::TempoNextBlockEnvAttributes;
use tempo_payload_types::TempoBuiltPayload;
use tempo_primitives::{
TempoHeader, TempoTxEnvelope,
transaction::envelope::{TEMPO_SYSTEM_TX_SENDER, TEMPO_SYSTEM_TX_SIGNATURE},
};
use tempo_transaction_pool::TempoTransactionPool;
use tracing::{error, info, warn};
use super::node::ZoneNode;
use alloy_evm::block::{BlockExecutor, TxResult};
#[derive(Clone)]
struct RequestedWithdrawalContext {
event: abi::ZoneOutbox::WithdrawalRequested,
tx_hash: B256,
}
/// Factory for constructing the zone payload builder.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct ZonePayloadFactory;
impl<Node> PayloadBuilderBuilder<Node, TempoTransactionPool<Node::Provider>, ZoneEvmConfig>
for ZonePayloadFactory
where
Node: FullNodeTypes<Types = ZoneNode>,
{
type PayloadBuilder = ZonePayloadBuilder<Node::Provider>;
async fn build_payload_builder(
self,
ctx: &BuilderContext<Node>,
pool: TempoTransactionPool<Node::Provider>,
evm_config: ZoneEvmConfig,
) -> eyre::Result<Self::PayloadBuilder> {
Ok(ZonePayloadBuilder {
pool,
provider: ctx.provider().clone(),
evm_config,
})
}
}
/// Zone payload builder that executes `advanceTempo` system txs + pool txs.
#[derive(Debug, Clone)]
pub struct ZonePayloadBuilder<Provider> {
/// Transaction pool for selecting pool txs to include in the block.
pool: TempoTransactionPool<Provider>,
/// State provider for reading chain state during block building.
provider: Provider,
/// Zone-specific EVM configuration (precompiles, hardfork spec, gas params).
evm_config: ZoneEvmConfig,
}
impl<Provider> PayloadBuilder for ZonePayloadBuilder<Provider>
where
Provider:
StateProviderFactory + ChainSpecProvider<ChainSpec = TempoChainSpec> + Clone + 'static,
{
type Attributes = ZonePayloadAttributes;
type BuiltPayload = TempoBuiltPayload;
fn try_build(
&self,
args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
) -> Result<BuildOutcome<Self::BuiltPayload>, PayloadBuilderError> {
let BuildArguments {
mut cached_reads,
config,
cancel,
best_payload: _,
..
} = args;
let PayloadConfig {
parent_header,
attributes,
payload_id: _,
} = config;
let start = Instant::now();
// Read the current tempoBlockHash and tempoBlockNumber from TempoState storage
// to validate the next L1 block we process is the expected successor.
let sp = self.provider.state_by_block_hash(parent_header.hash())?;
let stored_l1 = sp
.tempo_num_hash()
.map_err(|e| PayloadBuilderError::Internal(e.into()))?;
let stored_l1_block_hash = stored_l1.hash;
let expected_tempo_block_number = stored_l1.number + 1;
info!(
target: "zone::payload",
%stored_l1_block_hash,
expected_tempo_block_number,
"TempoState current state"
);
let prepared = attributes.l1_block();
// Validate chain continuity: the L1 block must be exactly tempoBlockNumber + 1
// and its parent hash must match the stored tempoBlockHash.
if prepared.header.inner.number != expected_tempo_block_number {
error!(
target: "zone::payload",
got = prepared.header.inner.number,
expected = expected_tempo_block_number,
"L1 block number mismatch — chain continuity broken"
);
return Err(PayloadBuilderError::Internal(reth_errors::RethError::msg(
format!(
"L1 block number mismatch: got {} expected {}",
prepared.header.inner.number, expected_tempo_block_number
),
)));
}
if prepared.header.inner.parent_hash != stored_l1_block_hash {
error!(
target: "zone::payload",
got = %prepared.header.inner.parent_hash,
expected = %stored_l1_block_hash,
l1_block = prepared.header.inner.number,
"L1 parent hash mismatch — chain continuity broken"
);
return Err(PayloadBuilderError::Internal(reth_errors::RethError::msg(
format!(
"L1 parent hash mismatch at block {}: got {} expected {}",
prepared.header.inner.number,
prepared.header.inner.parent_hash,
stored_l1_block_hash
),
)));
}
let total_deposits = prepared.queued_deposits.len();
info!(
target: "zone::payload",
zone_block = parent_header.number() + 1,
l1_block = prepared.header.inner.number,
deposits = total_deposits,
enabled_tokens = prepared.enabled_tokens.len(),
"Including advanceTempo system tx (chain continuity OK)"
);
let state_provider = self.provider.state_by_block_hash(parent_header.hash())?;
let state_provider: Box<dyn StateProvider> = state_provider;
let state = StateProviderDatabase::new(&state_provider);
let mut db = State::builder()
.with_database(
Box::new(cached_reads.as_db_mut(state)) as Box<dyn Database<Error = ProviderError>>
)
.with_bundle_update()
.build();
let chain_spec = self.provider.chain_spec();
let block_gas_limit = parent_header.gas_limit();
let mut cumulative_gas_used = 0u64;
let total_fees = U256::ZERO;
let mut requested_withdrawals = Vec::new();
let mut builder = self
.evm_config
.builder_for_next_block(
&mut db,
&parent_header,
TempoNextBlockEnvAttributes {
inner: NextBlockEnvAttributes {
timestamp: attributes.timestamp(),
suggested_fee_recipient: attributes.suggested_fee_recipient(),
prev_randao: attributes.prev_randao(),
gas_limit: block_gas_limit,
parent_beacon_block_root: attributes.parent_beacon_block_root(),
withdrawals: attributes.withdrawals().cloned().map(Withdrawals::new),
extra_data: attributes.extra_data(),
slot_number: attributes.slot_number(),
},
// Zones don't use L1 gas sections. These fields are required
// by TempoNextBlockEnvAttributes but ignored by the zone executor.
general_gas_limit: 0,
shared_gas_limit: block_gas_limit,
timestamp_millis_part: attributes.timestamp_millis_part(),
consensus_context: None,
subblock_fee_recipients: Default::default(),
},
)
.map_err(PayloadBuilderError::other)?;
builder.apply_pre_execution_changes().map_err(|err| {
warn!(%err, "failed to apply pre-execution changes");
PayloadBuilderError::Internal(err.into())
})?;
// Execute advanceTempo system transaction — exactly one per zone block.
{
let advance_tx = build_advance_tempo_tx(prepared);
let mut reverted = false;
match builder.execute_transaction_with_result_closure(advance_tx, |result| {
let evm_result = result.result();
if !evm_result.result.is_success() {
let revert_data = evm_result.result.output().cloned().unwrap_or_default();
error!(
target: "zone::payload",
l1_block = prepared.header.inner.number,
deposits = total_deposits,
is_halt = evm_result.result.is_halt(),
revert_data = %revert_data,
"advanceTempo system tx reverted on-chain"
);
reverted = true;
}
}) {
Ok(_) if reverted => {
return Err(PayloadBuilderError::Internal(reth_errors::RethError::msg(
format!(
"advanceTempo reverted at L1 block {}",
prepared.header.inner.number
),
)));
}
Ok(_) => {}
Err(err) => {
error!(
?err,
l1_block = prepared.header.inner.number,
deposits = total_deposits,
"advanceTempo system tx failed"
);
return Err(PayloadBuilderError::evm(err));
}
}
}
// Execute pool transactions
// TODO: Use gas accounting from TempoPayloadBuilder (payment vs non-payment limits, etc.)
let base_fee = builder.evm_mut().block.basefee;
let mut best_txs = self
.pool
.best_transactions_with_attributes(BestTransactionsAttributes::new(base_fee, None));
while let Some(pool_tx) = best_txs.next() {
// Contract creation (CREATE) transactions are not allowed on zones
if pool_tx.transaction.is_create() {
best_txs.mark_invalid(
&pool_tx,
&InvalidPoolTransactionError::Consensus(
reth_primitives_traits::transaction::error::InvalidTransactionError::TxTypeNotSupported,
),
);
continue;
}
let gas_limit_left = block_gas_limit;
if cumulative_gas_used + pool_tx.gas_limit() > gas_limit_left {
best_txs.mark_invalid(
&pool_tx,
&InvalidPoolTransactionError::ExceedsGasLimit(
pool_tx.gas_limit(),
gas_limit_left.saturating_sub(cumulative_gas_used),
),
);
continue;
}
if cancel.is_cancelled() {
return Ok(BuildOutcome::Cancelled);
}
let tx_with_env = pool_tx.transaction.clone().into_with_tx_env();
let tx_hash = *pool_tx.hash();
match builder.execute_transaction(tx_with_env) {
Ok(gas_used) => {
cumulative_gas_used += gas_used;
if let Some(receipt) = builder.executor().receipts().last() {
collect_requested_withdrawals(
receipt,
tx_hash,
&mut requested_withdrawals,
)?;
}
}
Err(reth_evm::block::BlockExecutionError::Validation(
reth_evm::block::BlockValidationError::InvalidTx { error, .. },
)) => {
if !error.is_nonce_too_low() {
best_txs.mark_invalid(
&pool_tx,
&InvalidPoolTransactionError::Consensus(
reth_primitives_traits::transaction::error::InvalidTransactionError::TxTypeNotSupported,
),
);
}
continue;
}
Err(reth_evm::block::BlockExecutionError::Internal(
reth_evm::block::InternalBlockExecutionError::EVM { ref error, .. },
)) if zone_precompiles::is_zone_rpc_error(&error.to_string()) => {
warn!(target: "zone::payload", %error, ?pool_tx, "skipping pool tx due to transient RPC error");
continue;
}
Err(err) => return Err(PayloadBuilderError::evm(err)),
}
}
// Finalize the withdrawal batch — must run after all user txs.
// Calls ZoneOutbox.finalizeWithdrawalBatch(MAX, blockNumber) to build the
// withdrawal hash chain and write batch state for proof generation.
let block_number: u64 = builder
.evm_mut()
.block
.number
.try_into()
.expect("block number fits u64");
let encrypted_senders = requested_withdrawals
.iter()
.map(|request| {
if request.event.revealTo.is_empty() {
Ok(Bytes::new())
} else {
zone_precompiles::ecies::encrypt_authenticated_withdrawal(
request.event.revealTo.as_ref(),
request.event.sender,
request.tx_hash,
)
.map(Bytes::from)
.ok_or_else(|| {
PayloadBuilderError::Internal(reth_errors::RethError::msg(format!(
"failed to encrypt authenticated sender reveal for tx {}",
request.tx_hash
)))
})
}
})
.collect::<Result<Vec<_>, _>>()?;
let finalize_tx = build_finalize_withdrawal_batch_tx(
U256::from(requested_withdrawals.len()),
block_number,
encrypted_senders,
);
let mut finalize_reverted = false;
match builder.execute_transaction_with_result_closure(finalize_tx, |result| {
let evm_result = result.result();
if !evm_result.result.is_success() {
let revert_data = evm_result.result.output().cloned().unwrap_or_default();
error!(
target: "zone::payload",
block_number,
is_halt = evm_result.result.is_halt(),
revert_data = %revert_data,
"finalizeWithdrawalBatch system tx reverted on-chain"
);
finalize_reverted = true;
}
}) {
Ok(_) if finalize_reverted => {
return Err(PayloadBuilderError::Internal(reth_errors::RethError::msg(
format!("finalizeWithdrawalBatch reverted at zone block {block_number}"),
)));
}
Ok(_) => {}
Err(err) => {
error!(?err, "finalizeWithdrawalBatch system tx failed");
return Err(PayloadBuilderError::evm(err));
}
}
let BlockBuilderOutcome {
execution_result,
hashed_state,
trie_updates,
block,
} = builder.finish(&*state_provider, None)?;
let requests = chain_spec
.is_prague_active_at_timestamp(attributes.timestamp())
.then_some(execution_result.requests.clone());
let sealed_block = Arc::new(block.sealed_block().clone());
let elapsed = start.elapsed();
info!(
number = sealed_block.number(),
l1_block = prepared.header.number(),
l1_hash = ?prepared.header.hash(),
hash = ?sealed_block.hash(),
gas_used = sealed_block.gas_used(),
deposits = total_deposits,
tx_count = sealed_block.body().transactions.len(),
?elapsed,
"Built zone payload"
);
let eth_payload = EthBuiltPayload::new(sealed_block, total_fees, requests, None);
let execution_output = BlockExecutionOutput {
result: execution_result,
state: db.take_bundle(),
};
let executed_block = BuiltPayloadExecutedBlock {
recovered_block: Arc::new(block),
execution_output: Arc::new(execution_output),
hashed_state: Either::Left(Arc::new(hashed_state)),
trie_updates: Either::Left(Arc::new(trie_updates)),
};
let payload = TempoBuiltPayload::new(eth_payload, Some(executed_block));
drop(db);
// Zone payloads are deterministic (one L1 block = one zone block), so freeze
// the payload to prevent reth from re-triggering try_build on the rebuild interval.
// Without this, the next rebuild attempt would find the deposit queue empty.
Ok(BuildOutcome::Freeze(payload))
}
fn on_missing_payload(
&self,
_args: BuildArguments<Self::Attributes, Self::BuiltPayload>,
) -> MissingPayloadBehaviour<Self::BuiltPayload> {
MissingPayloadBehaviour::AwaitInProgress
}
fn build_empty_payload(
&self,
config: PayloadConfig<Self::Attributes, TempoHeader>,
) -> Result<Self::BuiltPayload, PayloadBuilderError> {
self.try_build(BuildArguments::new(
Default::default(),
None,
None,
config,
Default::default(),
Default::default(),
))?
.into_payload()
.ok_or_else(|| PayloadBuilderError::MissingPayload)
}
}
/// Build the `finalizeWithdrawalBatch(count)` system transaction.
///
/// This must be the **last** transaction in every zone block. It calls
/// [`ZoneOutbox.finalizeWithdrawalBatch`](crate::abi::ZoneOutbox) which:
/// - Collects up to `count` pending withdrawals
/// - Builds the withdrawal hash chain (oldest outermost)
/// - Increments `withdrawalBatchIndex`
/// - Writes `_lastBatch` to state for proof access
/// - Emits `BatchFinalized`
///
/// Pass `u256::MAX` to batch all pending withdrawals. `block_number` must match the current zone
/// block number.
pub(crate) fn build_finalize_withdrawal_batch_tx(
count: U256,
block_number: u64,
encrypted_senders: Vec<Bytes>,
) -> Recovered<TempoTxEnvelope> {
let calldata = abi::ZoneOutbox::finalizeWithdrawalBatchCall {
count,
blockNumber: block_number,
encryptedSenders: encrypted_senders,
}
.abi_encode();
let tx = TxLegacy {
chain_id: None,
nonce: 0,
gas_price: 0,
gas_limit: 0,
to: ZONE_OUTBOX_ADDRESS.into(),
value: U256::ZERO,
input: calldata.into(),
};
Recovered::new_unchecked(
TempoTxEnvelope::Legacy(Signed::new_unhashed(tx, TEMPO_SYSTEM_TX_SIGNATURE)),
TEMPO_SYSTEM_TX_SENDER,
)
}
fn collect_requested_withdrawals(
receipt: &tempo_primitives::TempoReceipt,
tx_hash: B256,
requested_withdrawals: &mut Vec<RequestedWithdrawalContext>,
) -> Result<(), PayloadBuilderError> {
// Zone execution preserves reverted logs in receipts for observability, but
// reverted `requestWithdrawal` calls roll back the outbox's pending storage.
// Only successful receipts should contribute to end-of-block finalization.
if !receipt.status() {
return Ok(());
}
for log in receipt.logs() {
if log.address != ZONE_OUTBOX_ADDRESS {
continue;
}
if log
.topics()
.first()
.copied()
.is_some_and(|topic| topic == abi::ZoneOutbox::WithdrawalRequested::SIGNATURE_HASH)
{
let event = abi::ZoneOutbox::WithdrawalRequested::decode_log(log).map_err(|err| {
PayloadBuilderError::Internal(reth_errors::RethError::msg(format!(
"failed to decode WithdrawalRequested log: {err}"
)))
})?;
requested_withdrawals.push(RequestedWithdrawalContext {
event: event.data,
tx_hash,
});
}
}
Ok(())
}
/// Build the `advanceTempo(header, deposits, decryptions, enabledTokens)` system transaction.
///
/// This must be called **once per L1 block** at the start of a zone block (before user txs).
/// It calls [`ZoneInbox.advanceTempo`](crate::abi::ZoneInbox) which atomically:
/// - Advances the zone's view of Tempo by processing the L1 block header
/// - Enables newly-bridged TIP-20 tokens via the zone's TIP20Factory precompile
/// - Processes deposits from the queue (minting zone tokens to recipients)
/// - Validates the deposit hash chain against Tempo state
///
/// Takes a [`PreparedL1Block`] where all ECIES decryption, TIP-403 policy checks,
/// and ABI encoding have already been performed.
pub fn build_advance_tempo_tx(prepared: &PreparedL1Block) -> Recovered<TempoTxEnvelope> {
// RLP-encode the Tempo header
let mut header_rlp = Vec::new();
prepared.header.header().encode(&mut header_rlp);
let calldata = abi::ZoneInbox::advanceTempoCall {
header: Bytes::from(header_rlp),
deposits: prepared.queued_deposits.clone(),
decryptions: prepared.decryptions.clone(),
enabledTokens: prepared.enabled_tokens.clone(),
}
.abi_encode();
let tx = TxLegacy {
chain_id: None,
nonce: 0,
gas_price: 0,
gas_limit: 0,
to: ZONE_INBOX_ADDRESS.into(),
value: U256::ZERO,
input: calldata.into(),
};
Recovered::new_unchecked(
TempoTxEnvelope::Legacy(Signed::new_unhashed(tx, TEMPO_SYSTEM_TX_SIGNATURE)),
TEMPO_SYSTEM_TX_SENDER,
)
}
#[cfg(test)]
mod tests {
use alloy_consensus::Header;
use alloy_primitives::{Address, B256, Bytes, Log, U256, address};
use alloy_sol_types::{SolCall, SolEvent};
use reth_primitives_traits::SealedHeader;
use tempo_primitives::{TempoHeader, TempoReceipt, TempoTxType};
use crate::{
abi::{self, DepositType, ZoneInbox},
l1::PreparedL1Block,
};
fn make_withdrawal_requested_log(sender: alloy_primitives::Address) -> Log {
let event = abi::ZoneOutbox::WithdrawalRequested {
withdrawalIndex: 1,
sender,
token: address!("0x0000000000000000000000000000000000001000"),
to: address!("0x0000000000000000000000000000000000002000"),
amount: 500_000,
fee: 0,
memo: B256::ZERO,
gasLimit: 0,
fallbackRecipient: sender,
data: Bytes::new(),
revealTo: Bytes::new(),
};
Log {
address: super::ZONE_OUTBOX_ADDRESS,
data: event.encode_log_data(),
}
}
fn make_receipt(success: bool, logs: Vec<Log>) -> TempoReceipt {
TempoReceipt {
tx_type: TempoTxType::Legacy,
success,
cumulative_gas_used: 21_000,
logs,
}
}
/// Verify that `build_advance_tempo_tx` constructs valid calldata for mixed
/// deposit types. The calldata should include `QueuedDeposit` entries with the
/// correct `DepositType` discriminator and `DecryptionData` for encrypted deposits.
#[test]
fn test_build_advance_tempo_tx_with_encrypted_deposit() {
let token = address!("0x0000000000000000000000000000000000001000");
let sender = address!("0x0000000000000000000000000000000000001234");
let recipient = address!("0x0000000000000000000000000000000000005678");
let header = TempoHeader {
inner: Header {
number: 1,
..Default::default()
},
..Default::default()
};
// Build a PreparedL1Block directly — this test validates
// `build_advance_tempo_tx` calldata encoding, not `prepare`.
let prepared = PreparedL1Block {
header: SealedHeader::seal_slow(header),
queued_deposits: vec![
abi::QueuedDeposit {
depositType: DepositType::Regular,
depositData: alloy_primitives::Bytes::from(
alloy_sol_types::SolValue::abi_encode(&abi::Deposit {
token,
sender,
to: recipient,
amount: 500_000,
memo: B256::ZERO,
bouncebackRecipient: Address::ZERO,
}),
),
},
abi::QueuedDeposit {
depositType: DepositType::Encrypted,
depositData: alloy_primitives::Bytes::from(
alloy_sol_types::SolValue::abi_encode(&abi::EncryptedDeposit {
token,
sender,
amount: 300_000,
keyIndex: U256::ZERO,
encrypted: abi::EncryptedDepositPayload {
ephemeralPubkeyX: B256::with_last_byte(0xDD),
ephemeralPubkeyYParity: 0x02,
ciphertext: vec![0xAA; 64].into(),
nonce: [0x05; 12].into(),
tag: [0x06; 16].into(),
},
bouncebackRecipient: Address::ZERO,
}),
),
},
],
decryptions: vec![abi::DecryptionData {
sharedSecret: B256::ZERO,
sharedSecretYParity: 0x02,
to: sender,
memo: B256::ZERO,
cpProof: abi::ChaumPedersenProof {
s: B256::ZERO,
c: B256::ZERO,
},
}],
enabled_tokens: vec![],
};
let recovered_tx = super::build_advance_tempo_tx(&prepared);
// Decode the calldata to verify structure.
let envelope = recovered_tx.inner();
let input = match envelope {
tempo_primitives::TempoTxEnvelope::Legacy(signed) => &signed.tx().input,
_ => panic!("expected Legacy tx"),
};
let decoded = ZoneInbox::advanceTempoCall::abi_decode(input)
.expect("calldata should decode as advanceTempo");
// Should have 2 queued deposits
assert_eq!(decoded.deposits.len(), 2, "should have 2 queued deposits");
// First should be Regular
assert_eq!(
decoded.deposits[0].depositType,
DepositType::Regular,
"first deposit should be Regular"
);
// Second should be Encrypted
assert_eq!(
decoded.deposits[1].depositType,
DepositType::Encrypted,
"second deposit should be Encrypted"
);
// Should have exactly 1 DecryptionData (one per encrypted deposit)
assert_eq!(
decoded.decryptions.len(),
1,
"should have 1 DecryptionData for the encrypted deposit"
);
}
#[test]
fn collect_requested_withdrawals_ignores_reverted_receipts() {
let sender = address!("0x0000000000000000000000000000000000001234");
let tx_hash = B256::with_last_byte(0x42);
let mut requested = Vec::new();
super::collect_requested_withdrawals(
&make_receipt(false, vec![make_withdrawal_requested_log(sender)]),
tx_hash,
&mut requested,
)
.expect("reverted receipt should be ignored");
assert!(
requested.is_empty(),
"reverted receipts must not add phantom withdrawals"
);
super::collect_requested_withdrawals(
&make_receipt(true, vec![make_withdrawal_requested_log(sender)]),
tx_hash,
&mut requested,
)
.expect("successful receipt should decode");
assert_eq!(requested.len(), 1, "successful receipt should be collected");
assert_eq!(requested[0].tx_hash, tx_hash);
assert_eq!(requested[0].event.sender, sender);
}
}