evmlib 0.10.0

Safe Network EVM
Documentation
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
// Copyright 2026 MaidSafe.net limited.
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Sign before broadcasting so callers can durably journal and recover payments.

use super::{ProviderWithWallet, Wallet};
use crate::common::{Amount, Calldata, QuotePayment, TxHash, U256};
use crate::contract::payment_vault::{MAX_TRANSFERS_PER_TRANSACTION, handler::PaymentVaultHandler};
use crate::merkle_batch_payment::{PoolCommitment, PoolHash};
use crate::retry::{Eip1559Fees, TransactionError, apply_fee_policy, needs_fee_estimate};
use crate::transaction_config::TransactionConfig;
use alloy::consensus::{Transaction, TxEnvelope, transaction::SignerRecoverable};
use alloy::eips::eip2718::{Decodable2718, Encodable2718};
use alloy::eips::{BlockId, BlockNumberOrTag};
use alloy::network::TransactionBuilder;
use alloy::providers::Provider;
use alloy::rpc::types::{Block, Header, TransactionReceipt};
use alloy::transports::{RpcError, TransportErrorKind};
use serde::{Deserialize, Serialize};

/// Retry base for reads made while a caller is polling for an outcome. The
/// native client observes inside a 30s window, so the default 4s base (4/16/36s)
/// would turn one throttled read into a timed-out payment.
const OBSERVE_RETRY_INTERVAL_MS: u64 = 500;

/// Run a read-only RPC call with the crate's standard backoff.
///
/// Every read in the journal path used to be single-shot, so one `429` from a
/// public endpoint failed the upload — the legacy `send_transaction_with_retries`
/// path wrapped the same reads in three retries.
async fn rpc<T, E, F, Fut>(
    operation: &str,
    interval_ms: Option<u64>,
    action: F,
) -> Result<T, String>
where
    F: FnMut() -> Fut + Send,
    Fut: std::future::Future<Output = Result<T, E>>,
    E: std::fmt::Debug + std::fmt::Display,
{
    crate::retry::retry(action, operation, interval_ms)
        .await
        .map_err(|e| e.to_string())
}

/// A failure the endpoint may not give again: HTTP-level errors (429, 5xx),
/// connection loss, timeouts, and the backend-timeout error responses public
/// load balancers emit. Definitive RPC rejections (bad nonce, underpriced,
/// insufficient funds) are never transient.
fn is_transient(err: &RpcError<TransportErrorKind>) -> bool {
    match err {
        RpcError::Transport(_) => true,
        RpcError::ErrorResp(payload) => {
            let message = payload.message.to_ascii_lowercase();
            [
                "deadline exceeded",
                "timeout",
                "timed out",
                "too many requests",
                "rate limit",
            ]
            .iter()
            .any(|needle| message.contains(needle))
        }
        _ => false,
    }
}

/// The endpoint already holds these exact bytes: a retried broadcast after an
/// ambiguous failure, or a replica that saw the first send.
fn is_already_known(err: &RpcError<TransportErrorKind>) -> bool {
    match err {
        RpcError::ErrorResp(payload) => {
            let message = payload.message.to_ascii_lowercase();
            [
                "already known",
                "already imported",
                "already exists",
                "alreadyexists",
            ]
            .iter()
            .any(|needle| message.contains(needle))
        }
        _ => false,
    }
}

/// Read the EIP-1559 fee estimate with the standard backoff, then apply the
/// configured fee policy. Only the RPC read is retried: a definitive
/// `GasPriceAboveLimit` returns at once.
async fn journal_fee_read<P: Provider>(
    provider: &P,
    config: &TransactionConfig,
) -> Result<Option<Eip1559Fees>, String> {
    let estimate = if needs_fee_estimate(config) {
        Some(
            rpc("gas price", None, || async {
                provider.estimate_eip1559_fees().await
            })
            .await
            .map_err(|e| TransactionError::CouldNotGetGasPrice(e).to_string())?,
        )
    } else {
        None
    };
    apply_fee_policy(estimate, config).map_err(|e| e.to_string())
}

/// An ordinary single transaction payment, using the existing vault encoders.
pub enum PaymentRequest {
    /// At most one vault transaction of nonzero quote payments.
    Quotes(Vec<QuotePayment>),
    /// One Merkle sub-batch.
    Merkle {
        depth: u8,
        pools: Vec<PoolCommitment>,
        timestamp: u64,
    },
}

/// Signed transaction bytes, safe to persist before the first broadcast.
/// Contains no private key. Re-sending these bytes cannot create another payment.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SignedPayment {
    raw: Vec<u8>,
}

/// A payment included in the canonical chain. Inclusion is not finality.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PaymentReceipt {
    /// Settlement transaction hash, including a same-intent fee replacement.
    pub transaction_hash: TxHash,
    /// Storage tokens charged.
    pub amount: Amount,
    /// Merkle winner, absent for quote payments.
    pub winner_pool: Option<PoolHash>,
    /// Actual gas spend.
    pub gas_cost_wei: u128,
}

/// Observation never assumes a missing receipt means the transaction failed.
#[derive(Debug)]
pub enum PaymentStatus {
    /// No mined payment found; retain the journal.
    Pending,
    /// A mined failure is not finalized yet. Retain the journal without
    /// broadcasting or preparing another payment. (A consumed nonce with no
    /// receipt reports `Pending`, not this: see `observe_payment`.)
    Finalizing,
    /// The payment reverted in a finalized block. The original transaction
    /// cannot subsequently charge storage tokens, including after a fee replacement.
    Reverted,
    /// A different transaction consumed the nonce in a finalized block.
    /// Its calldata differs from this payment; the original cannot execute.
    Replaced { transaction_hash: TxHash },
    /// Successful canonical inclusion, suitable for optimistic proof construction.
    /// This retains the existing wallet's inclusion-level success semantics;
    /// callers requiring irreversible settlement must also wait for finality.
    Confirmed(PaymentReceipt),
}

impl PaymentRequest {
    fn calldata(&self, wallet: &Wallet) -> Result<(Calldata, Amount), String> {
        let handler = PaymentVaultHandler::new(
            *wallet.network.payment_vault_address(),
            wallet.to_provider(),
        );
        match self {
            Self::Quotes(quotes) => {
                let quotes = quotes
                    .iter()
                    .filter(|(_, _, amount)| *amount != Amount::ZERO)
                    .copied()
                    .collect::<Vec<_>>();
                if quotes.is_empty() || quotes.len() > MAX_TRANSFERS_PER_TRANSACTION {
                    return Err(
                        "journaled quote payment must fit one nonempty vault transaction".into(),
                    );
                }
                let amount = quotes.iter().try_fold(Amount::ZERO, |sum, (_, _, value)| {
                    sum.checked_add(*value).ok_or("payment total overflow")
                })?;
                Ok((
                    handler
                        .pay_for_quotes_calldata(quotes)
                        .map_err(|e| e.to_string())?
                        .0,
                    amount,
                ))
            }
            Self::Merkle {
                depth,
                pools,
                timestamp,
            } => Ok((
                handler
                    .pay_for_merkle_tree_calldata(*depth, pools.clone(), *timestamp)
                    .map_err(|e| e.to_string())?
                    .0,
                wallet.network.estimate_merkle_payment_cost(*depth, pools),
            )),
        }
    }
}

impl Wallet {
    /// Prepare and sign without broadcasting the storage payment. Persist the
    /// result before calling `broadcast_payment`. Hold `Wallet::lock` across
    /// preparation and submission when sharing a wallet between operations.
    pub async fn prepare_payment(&self, request: &PaymentRequest) -> Result<SignedPayment, String> {
        let (calldata, amount) = request.calldata(self)?;
        let balance = self.balance_of_tokens().await.map_err(|e| e.to_string())?;
        if balance < amount {
            return Err(super::Error::InsufficientTokensForQuotes(balance, amount).to_string());
        }
        let vault = *self.network.payment_vault_address();
        if self
            .token_allowance(vault)
            .await
            .map_err(|e| e.to_string())?
            < amount
        {
            self.approve_to_spend_tokens(vault, U256::MAX)
                .await
                .map_err(|e| e.to_string())?;
        }
        let provider = self.to_provider();
        let address = self.address();
        // Set the chain id here so `fill` below needs no RPC call of its own.
        let chain = rpc("chain id", None, || async { provider.get_chain_id().await }).await?;
        let mut tx = provider
            .transaction_request()
            .with_from(address)
            .with_to(vault)
            .with_input(calldata)
            .with_chain_id(chain);
        if let Some(fees) = journal_fee_read(&provider, &self.transaction_config).await? {
            tx.set_max_fee_per_gas(fees.max_fee_per_gas);
            tx.set_max_priority_fee_per_gas(fees.max_priority_fee_per_gas);
        }
        let gas = rpc("gas estimate", None, || {
            let (provider, tx) = (&provider, tx.clone());
            async move { provider.estimate_gas(tx).await }
        })
        .await?;
        tx.set_gas_limit(gas.saturating_mul(120) / 100);
        // Two independent reads, highest wins. A public endpoint is a pool of
        // replicas that can lag each other by a block or more; a single stale
        // `pending` read signs a nonce the chain has already consumed, and those
        // bytes can then never be mined. Measured on sepolia-rollup.arbitrum.io
        // (2026-09-16): `pending=98` followed by `latest=99`, 1 pair in 150.
        let pending_nonce = rpc("pending nonce", None, || async {
            provider.get_transaction_count(address).pending().await
        })
        .await?;
        let latest_nonce = rpc("latest nonce", None, || async {
            provider.get_transaction_count(address).await
        })
        .await?;
        tx.set_nonce(pending_nonce.max(latest_nonce));
        let envelope = provider
            .fill(tx)
            .await
            .map_err(|e| e.to_string())?
            .try_into_envelope()
            .map_err(|_| "wallet did not sign transaction")?;
        Ok(SignedPayment {
            raw: envelope.encoded_2718(),
        })
    }

    async fn validate_payment(
        &self,
        signed: &SignedPayment,
        request: &PaymentRequest,
    ) -> Result<TxEnvelope, String> {
        let mut bytes = signed.raw.as_slice();
        let tx = TxEnvelope::decode_2718(&mut bytes).map_err(|e| e.to_string())?;
        let (calldata, _) = request.calldata(self)?;
        let provider = self.to_provider();
        let chain = rpc("chain id", Some(OBSERVE_RETRY_INTERVAL_MS), || async {
            provider.get_chain_id().await
        })
        .await?;
        if !bytes.is_empty()
            || tx.to() != Some(*self.network.payment_vault_address())
            || tx.input() != &calldata
            || tx.value() != U256::ZERO
            || tx.chain_id() != Some(chain)
            || tx.recover_signer().map_err(|e| e.to_string())? != self.address()
        {
            return Err(
                "journaled transaction does not match this wallet, chain, or payment intent".into(),
            );
        }
        Ok(tx)
    }

    /// Broadcast exactly the journaled bytes. No re-signing, nonce change, or
    /// fee replacement occurs, including after an ambiguous RPC failure.
    ///
    /// Transport-level failures (HTTP 429/5xx, timeouts, backend deadline
    /// responses) are retried with the same bytes: re-sending a signed
    /// transaction cannot create a second payment, and an endpoint that already
    /// holds it answers "already known", which is treated as success. A
    /// definitive rejection (bad nonce, underpriced, insufficient funds) is
    /// returned at once.
    pub async fn broadcast_payment(
        &self,
        signed: &SignedPayment,
        request: &PaymentRequest,
    ) -> Result<TxHash, String> {
        let tx = self.validate_payment(signed, request).await?;
        let provider = self.to_provider();
        let mut retries: u8 = 0;
        loop {
            match provider.send_raw_transaction(&signed.raw).await {
                Ok(pending) => {
                    if pending.tx_hash() != tx.tx_hash() {
                        return Err("RPC returned a different transaction hash".into());
                    }
                    return Ok(*tx.tx_hash());
                }
                Err(err) if is_already_known(&err) => return Ok(*tx.tx_hash()),
                Err(err) if is_transient(&err) && retries < crate::retry::MAX_RETRIES => {
                    retries += 1;
                    let delay = std::time::Duration::from_millis(
                        OBSERVE_RETRY_INTERVAL_MS * u64::from(retries).pow(2),
                    );
                    tracing::warn!(
                        "Error broadcasting payment: {err}. Retry #{retries} in {delay:?} with the same bytes."
                    );
                    crate::runtime::sleep(delay).await;
                }
                Err(err) => return Err(err.to_string()),
            }
        }
    }

    /// Observe the journaled payment without broadcasting. Reverted and replaced
    /// outcomes require finalized, canonical evidence before another payment is safe.
    /// A successful fee replacement with identical calldata recovers its own receipt.
    pub async fn observe_payment(
        &self,
        signed: &SignedPayment,
        request: &PaymentRequest,
    ) -> Result<PaymentStatus, String> {
        let tx = self.validate_payment(signed, request).await?;
        let provider = self.to_provider();
        let tx_hash = *tx.tx_hash();
        if let Some(receipt) = rpc(
            "payment receipt",
            Some(OBSERVE_RETRY_INTERVAL_MS),
            || async { provider.get_transaction_receipt(tx_hash).await },
        )
        .await?
        {
            if receipt.transaction_hash != *tx.tx_hash() {
                return Err("RPC returned a different receipt transaction hash".into());
            }
            if receipt.status() {
                if !receipt_is_canonical(&provider, &receipt).await? {
                    return Ok(PaymentStatus::Pending);
                }
                return self
                    .payment_receipt(request, receipt)
                    .map(PaymentStatus::Confirmed);
            }
            let finalized = finalized_header(&provider).await?;
            // Read finality before checking canonicality: a reorg between the
            // two queries must not bless a receipt from the discarded fork.
            if !receipt_is_canonical(&provider, &receipt).await? {
                return Ok(PaymentStatus::Pending);
            }
            return Ok(
                if receipt.block_number.is_some_and(|n| n <= finalized.number) {
                    PaymentStatus::Reverted
                } else {
                    PaymentStatus::Finalizing
                },
            );
        }

        // A missing receipt alone is never evidence of failure. Check whether
        // this nonce has been mined before asking for historical/finality data.
        let address = self.address();
        let latest_nonce = rpc("latest nonce", Some(OBSERVE_RETRY_INTERVAL_MS), || async {
            provider.get_transaction_count(address).await
        })
        .await?;
        if latest_nonce <= tx.nonce() {
            return Ok(PaymentStatus::Pending);
        }
        let finalized = finalized_header(&provider).await?;
        let finalized_nonce = nonce_at(&provider, address, &finalized).await?;
        if finalized_nonce <= tx.nonce() {
            // The nonce looks consumed but nothing is final. That is either an
            // unfinalised transaction on this nonce (this payment with its receipt
            // not yet visible, a fee replacement, or something else) or simply a
            // `latest` read served by a replica ahead of the one that served the
            // caller's earlier reads — the two are indistinguishable from here, and
            // a public endpoint produces the second routinely. Neither warrants
            // giving up: the journaled bytes can be re-sent safely (a consumed
            // nonce is rejected, never paid twice), and finality resolves a real
            // replacement into `Replaced` below. Reporting `Finalizing` here made
            // every stale read a failed upload (DEV-03 run 589, 2026-09-16).
            return Ok(PaymentStatus::Pending);
        }

        // Find what actually consumed the nonce. It could be the original
        // transaction with a temporarily unavailable receipt, or a fee bump
        // that already paid. Neither permits assuming the payment failed.
        let (replacement_hash, block) =
            find_nonce_transaction(&provider, self.address(), tx.nonce(), &finalized).await?;
        let replacement = rpc(
            "nonce transaction",
            Some(OBSERVE_RETRY_INTERVAL_MS),
            || async { provider.get_transaction_by_hash(replacement_hash).await },
        )
        .await?
        .ok_or("finalized nonce transaction unavailable; retain the journal")?;
        let receipt = rpc("nonce receipt", Some(OBSERVE_RETRY_INTERVAL_MS), || async {
            provider.get_transaction_receipt(replacement_hash).await
        })
        .await?
        .ok_or("finalized nonce receipt unavailable; retain the journal")?;
        if replacement.inner.tx_hash() != &replacement_hash
            || replacement.block_hash != Some(block.hash)
            || receipt.transaction_hash != replacement_hash
            || receipt.block_hash != Some(block.hash)
            || receipt.block_number != Some(block.number)
            || !receipt_is_canonical(&provider, &receipt).await?
        {
            return Err("inconsistent finalized transaction evidence; retain the journal".into());
        }
        if replacement.to() != tx.to()
            || replacement.value() != tx.value()
            || replacement.input() != tx.input()
        {
            return Ok(PaymentStatus::Replaced {
                transaction_hash: replacement_hash,
            });
        }
        if !receipt.status() {
            return Ok(PaymentStatus::Reverted);
        }
        self.payment_receipt(request, receipt)
            .map(PaymentStatus::Confirmed)
    }

    fn payment_receipt(
        &self,
        request: &PaymentRequest,
        receipt: TransactionReceipt,
    ) -> Result<PaymentReceipt, String> {
        let (amount, winner_pool) = match request {
            PaymentRequest::Quotes(_) => (request.calldata(self)?.1, None),
            PaymentRequest::Merkle { .. } => {
                // Decode the logs from this receipt so block-number queries
                // cannot mix a settlement event from another fork into it.
                use crate::contract::payment_vault::interface::IPaymentVault;
                let event = receipt
                    .inner
                    .logs()
                    .iter()
                    .filter(|log| log.address() == *self.network.payment_vault_address())
                    .find_map(|log| log.log_decode::<IPaymentVault::MerklePaymentMade>().ok())
                    .ok_or("MerklePaymentMade event missing from payment receipt")?;
                (
                    event.inner.data.totalAmount,
                    Some(event.inner.data.winnerPoolHash.0),
                )
            }
        };
        Ok(PaymentReceipt {
            transaction_hash: receipt.transaction_hash,
            amount,
            winner_pool,
            gas_cost_wei: (receipt.gas_used as u128).saturating_mul(receipt.effective_gas_price),
        })
    }
}

async fn finalized_header(provider: &ProviderWithWallet) -> Result<Header, String> {
    rpc(
        "finalized block",
        Some(OBSERVE_RETRY_INTERVAL_MS),
        || async {
            provider
                .get_block_by_number(BlockNumberOrTag::Finalized)
                .await
        },
    )
    .await?
    .map(|block| block.header)
    .ok_or_else(|| "finalized block unavailable; retain the journal".into())
}

async fn block_by_number(
    provider: &ProviderWithWallet,
    number: u64,
) -> Result<Option<Block>, String> {
    rpc(
        "block by number",
        Some(OBSERVE_RETRY_INTERVAL_MS),
        || async { provider.get_block_by_number(number.into()).await },
    )
    .await
}

async fn receipt_is_canonical(
    provider: &ProviderWithWallet,
    receipt: &TransactionReceipt,
) -> Result<bool, String> {
    let (Some(number), Some(hash)) = (receipt.block_number, receipt.block_hash) else {
        return Ok(false);
    };
    Ok(block_by_number(provider, number)
        .await?
        .is_some_and(|block| block.header.number == number && block.header.hash == hash))
}

async fn nonce_at(
    provider: &ProviderWithWallet,
    address: crate::common::Address,
    block: &Header,
) -> Result<u64, String> {
    let hash = block.hash;
    rpc(
        "nonce at block",
        Some(OBSERVE_RETRY_INTERVAL_MS),
        || async {
            provider
                .get_transaction_count(address)
                .block_id(BlockId::hash_canonical(hash))
                .await
        },
    )
    .await
}

// Decode only transaction identity when scanning a block. Arbitrum blocks also
// contain system transaction types that Ethereum's TxEnvelope cannot decode.
#[derive(Debug, Deserialize)]
struct NonceTransaction {
    hash: TxHash,
    from: Option<crate::common::Address>,
    #[serde(default, with = "alloy::serde::quantity::opt")]
    nonce: Option<u64>,
}

async fn find_nonce_transaction(
    provider: &ProviderWithWallet,
    address: crate::common::Address,
    nonce: u64,
    finalized: &Header,
) -> Result<(TxHash, Header), String> {
    // Search backwards from finality first: recent replacements should not
    // require state from halfway back to genesis on a pruned RPC endpoint.
    // Exponential bracketing then binary search takes O(log age) queries and
    // supports existing journals without adding preparation-block metadata.
    let (mut low, mut high) = (finalized.number, finalized.number);
    let mut step = 1u64;
    while low > 0 {
        let probe = low.saturating_sub(step);
        let block = block_by_number(provider, probe)
            .await?
            .ok_or("nonce history unavailable; retain the journal")?;
        low = probe;
        if nonce_at(provider, address, &block.header).await? <= nonce {
            break;
        }
        high = probe;
        step = step.saturating_mul(2);
    }
    while low < high {
        let mid = low + (high - low) / 2;
        let block = block_by_number(provider, mid)
            .await?
            .ok_or("nonce history unavailable; retain the journal")?;
        if nonce_at(provider, address, &block.header).await? > nonce {
            high = mid;
        } else {
            low = mid + 1;
        }
    }
    let header = block_by_number(provider, low)
        .await?
        .ok_or("nonce block unavailable; retain the journal")?
        .header;
    let block_hash = header.hash;
    let block: Option<Block<NonceTransaction>> = rpc(
        "nonce block transactions",
        Some(OBSERVE_RETRY_INTERVAL_MS),
        || async {
            provider
                .client()
                .request("eth_getBlockByHash", (block_hash, true))
                .await
        },
    )
    .await?;
    let block = block.ok_or("nonce transactions unavailable; retain the journal")?;
    if block.header.hash != header.hash || block.header.number != header.number {
        return Err("inconsistent nonce block; retain the journal".into());
    }
    for candidate in block.transactions.txns() {
        if candidate.from == Some(address) && candidate.nonce == Some(nonce) {
            return Ok((candidate.hash, header));
        }
    }
    // EIP-7702 authorizations can also advance a nonce. Do not classify an
    // unexplained nonce advance or incomplete RPC history as a safe retry.
    Err("finalized nonce consumer not found; retain the journal for reconciliation".into())
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy::rpc::json_rpc::ErrorPayload;

    fn error_resp(code: i64, message: &str) -> RpcError<TransportErrorKind> {
        RpcError::ErrorResp(ErrorPayload {
            code,
            message: message.to_string().into(),
            data: None,
        })
    }

    /// One throttled fee read must not fail the payment. The first
    /// `eth_feeHistory` gets the -32000 a public load balancer returns under
    /// load; the retry gets a valid history.
    #[cfg(feature = "native")]
    #[tokio::test]
    async fn journal_fee_read_retries_a_transient_failure() {
        use crate::transaction_config::MaxFeePerGas;
        use alloy::providers::{ProviderBuilder, mock::Asserter};
        use alloy::rpc::types::FeeHistory;

        let asserter = Asserter::new();
        let provider = ProviderBuilder::new()
            .disable_recommended_fillers()
            .connect_mocked_client(asserter.clone());
        asserter.push_failure(ErrorPayload {
            code: -32000,
            message: "Post \"http://10.17.52.14:8547/rpc\": context deadline exceeded".into(),
            data: None,
        });
        asserter.push_success(&FeeHistory {
            base_fee_per_gas: vec![100_000_000; 11],
            gas_used_ratio: vec![0.5; 10],
            oldest_block: 1,
            reward: Some(vec![vec![1_000]; 10]),
            ..Default::default()
        });

        let config = TransactionConfig {
            max_fee_per_gas: MaxFeePerGas::Auto,
        };
        let fees = journal_fee_read(&provider, &config)
            .await
            .expect("the retried fee read should succeed")
            .expect("Auto mode sets fees");
        assert!(fees.max_fee_per_gas > 0);
        assert!(asserter.read_q().is_empty());
    }

    #[cfg(feature = "native")]
    #[tokio::test]
    async fn journal_fee_read_does_not_retry_a_fee_over_the_limit() {
        use crate::transaction_config::MaxFeePerGas;
        use alloy::providers::{ProviderBuilder, mock::Asserter};
        use alloy::rpc::types::FeeHistory;

        let asserter = Asserter::new();
        let provider = ProviderBuilder::new()
            .disable_recommended_fillers()
            .connect_mocked_client(asserter.clone());
        asserter.push_success(&FeeHistory {
            base_fee_per_gas: vec![100_000_000; 11],
            gas_used_ratio: vec![0.5; 10],
            oldest_block: 1,
            reward: Some(vec![vec![1_000]; 10]),
            ..Default::default()
        });

        let config = TransactionConfig {
            max_fee_per_gas: MaxFeePerGas::LimitedAuto(1),
        };
        let started = std::time::Instant::now();
        let err = journal_fee_read(&provider, &config)
            .await
            .expect_err("a fee over the limit is rejected");
        assert_eq!(err, TransactionError::GasPriceAboveLimit(1).to_string());
        assert!(started.elapsed() < std::time::Duration::from_secs(1));
    }

    #[test]
    fn transport_failures_are_transient() {
        // What sepolia-rollup.arbitrum.io returned on DEV-03 run 589.
        assert!(is_transient(&RpcError::Transport(
            TransportErrorKind::HttpError(alloy::transports::HttpError {
                status: 429,
                body: "Too Many Requests".into(),
            })
        )));
        assert!(is_transient(&error_resp(
            -32000,
            "Post \"http://10.17.52.14:8547/rpc\": context deadline exceeded"
        )));
        assert!(is_transient(&RpcError::Transport(
            TransportErrorKind::BackendGone
        )));
    }

    #[test]
    fn definitive_rejections_are_not_transient() {
        for message in [
            "nonce too low: address 0x00, tx: 5 state: 6",
            "replacement transaction underpriced",
            "insufficient funds for gas * price + value",
            "execution reverted",
        ] {
            let err = error_resp(-32000, message);
            assert!(!is_transient(&err), "{message}");
            assert!(!is_already_known(&err), "{message}");
        }
    }

    #[test]
    fn already_known_is_success_not_failure() {
        assert!(is_already_known(&error_resp(-32000, "already known")));
        assert!(is_already_known(&error_resp(
            -32000,
            "ALREADY_EXISTS: already known"
        )));
        assert!(!is_transient(&error_resp(-32000, "already known")));
    }

    #[test]
    fn nonce_scan_accepts_arbitrum_system_transactions() {
        // Scanning an entire Arbitrum block must not require decoding every
        // transaction as an Ethereum envelope. Unknown system types are skipped.
        let system: NonceTransaction = serde_json::from_value(serde_json::json!({
            "type": "0x6a",
            "hash": TxHash::ZERO,
            "from": crate::common::Address::ZERO,
            "nonce": "0x0",
            "input": "0x1234"
        }))
        .unwrap();
        assert_eq!(system.nonce, Some(0));
        let without_nonce: NonceTransaction = serde_json::from_value(serde_json::json!({
            "type": "0x7e",
            "hash": TxHash::ZERO
        }))
        .unwrap();
        assert_eq!(without_nonce.nonce, None);
    }
}