r402-evm 0.21.0

EIP-155 (EVM) chain support for the x402 payment protocol.
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use alloy_network::{Ethereum as AlloyEthereum, EthereumWallet, NetworkWallet, TransactionBuilder};
use alloy_primitives::{Address, Bytes, TxHash, U256};
use alloy_provider::fillers::{
    BlobGasFiller, ChainIdFiller, FillProvider, GasFiller, JoinFill, NonceFiller, WalletFiller,
};
use alloy_provider::{
    Identity, PendingTransactionError, Provider, ProviderBuilder, RootProvider, WalletProvider,
};
use alloy_rpc_client::RpcClient;
use alloy_rpc_types_eth::{BlockId, TransactionReceipt, TransactionRequest};
use alloy_transport::TransportError;
use alloy_transport::layers::{FallbackLayer, ThrottleLayer};
use alloy_transport_http::{Client, Http};
use r402_protocol::network::{ChainId, ChainProvider};
use tower::ServiceBuilder;
#[cfg(feature = "telemetry")]
use tracing::Instrument;
use url::Url;

use crate::chain::account::Eip155ChainReference;
use crate::chain::nonce::PendingNonceManager;

/// Failure constructing an [`Eip155ChainProvider`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum Eip155ChainProviderError {
    /// Wallet contained no signers.
    #[error("at least one signer must be provided")]
    EmptyWallet,
    /// No HTTP(S) RPC URL remained after filtering non-HTTP endpoints.
    #[error("at least one HTTP RPC endpoint is required")]
    NoHttpEndpoint,
    /// `reqwest` client failed to build.
    #[error("failed to build HTTP RPC client")]
    HttpClient,
}

/// Combined filler type for gas, blob gas, nonce, and chain ID.
pub type InnerFiller = JoinFill<
    GasFiller,
    JoinFill<BlobGasFiller, JoinFill<NonceFiller<PendingNonceManager>, ChainIdFiller>>,
>;

/// The fully composed Ethereum provider type used in this project.
///
/// Combines multiple filler layers for gas, nonce, chain ID, blob gas, and wallet signing,
/// and wraps a [`RootProvider`] for actual JSON-RPC communication.
pub type InnerProvider = FillProvider<
    JoinFill<JoinFill<Identity, InnerFiller>, WalletFiller<EthereumWallet>>,
    RootProvider,
>;

/// Provider for interacting with EVM-compatible blockchains.
///
/// This provider handles:
/// - Transaction signing with multiple signers (round-robin selection)
/// - Nonce management with automatic reset on failures
/// - Gas estimation and pricing (EIP-1559 and legacy)
/// - Transaction receipt fetching with configurable timeouts
///
/// # Multiple Signers
///
/// The provider supports multiple signers for load distribution. When sending
/// transactions, signers are selected in round-robin fashion to distribute
/// the transaction load and avoid nonce conflicts.
///
/// # Nonce Management
///
/// Uses [`PendingNonceManager`] to track nonces locally and query pending
/// transactions on initialization. If a transaction fails, the nonce is
/// automatically reset to force a fresh query on the next transaction.
#[derive(Debug)]
pub struct Eip155ChainProvider {
    chain: Eip155ChainReference,
    eip1559: bool,
    flashblocks: bool,
    receipt_timeout_secs: u64,
    inner: InnerProvider,
    /// Available signer addresses for round-robin selection.
    signer_addresses: Arc<[Address]>,
    /// Current position in round-robin signer rotation.
    signer_cursor: Arc<AtomicUsize>,
    /// Nonce manager for resetting nonces on transaction failures.
    nonce_manager: PendingNonceManager,
}

impl Eip155ChainProvider {
    /// Creates a new EVM chain provider.
    ///
    /// # Parameters
    ///
    /// - `chain`: The numeric chain reference (e.g., 8453 for Base)
    /// - `wallet`: A pre-built Ethereum wallet containing one or more signers
    /// - `rpc_endpoints`: HTTP RPC endpoints as `(url, optional_rate_limit)` pairs
    /// - `eip1559`: Whether the chain supports EIP-1559 gas pricing
    /// - `flashblocks`: Whether the chain supports flashblocks
    /// - `receipt_timeout_secs`: How long to wait for a transaction receipt
    ///
    /// # Errors
    ///
    /// Returns [`Eip155ChainProviderError::EmptyWallet`] if the wallet has no
    /// signers, [`Eip155ChainProviderError::NoHttpEndpoint`] if no HTTP RPC
    /// URL remains after filtering, or [`Eip155ChainProviderError::HttpClient`]
    /// if the HTTP client cannot be built.
    pub fn new(
        chain: Eip155ChainReference,
        wallet: EthereumWallet,
        rpc_endpoints: &[(Url, Option<u32>)],
        eip1559: bool,
        flashblocks: bool,
        receipt_timeout_secs: u64,
    ) -> Result<Self, Eip155ChainProviderError> {
        let signer_addresses =
            NetworkWallet::<AlloyEthereum>::signer_addresses(&wallet).collect::<Vec<_>>();
        if signer_addresses.is_empty() {
            return Err(Eip155ChainProviderError::EmptyWallet);
        }
        let signer_addresses: Arc<[Address]> = signer_addresses.into();
        let signer_cursor = Arc::new(AtomicUsize::new(0));

        let chain_id: ChainId = chain.into();
        let client = Self::rpc_client(&chain_id, rpc_endpoints)?;

        let nonce_manager = PendingNonceManager::default();
        let filler = JoinFill::new(
            GasFiller::default(),
            JoinFill::new(
                BlobGasFiller::default(),
                JoinFill::new(
                    NonceFiller::new(nonce_manager.clone()),
                    ChainIdFiller::default(),
                ),
            ),
        );
        let inner: InnerProvider = ProviderBuilder::default()
            .filler(filler)
            .wallet(wallet)
            .connect_client(client);

        #[cfg(feature = "telemetry")]
        tracing::info!(chain=%chain_id, signers=?signer_addresses, "Using EVM provider");

        Ok(Self {
            chain,
            eip1559,
            flashblocks,
            receipt_timeout_secs,
            inner,
            signer_addresses,
            signer_cursor,
            nonce_manager,
        })
    }

    /// Creates an RPC client from HTTP endpoint URLs with optional per-endpoint rate limits.
    ///
    /// Each entry in `endpoints` is a `(url, optional_rate_limit)` pair.
    /// Non-HTTP(S) URLs are silently skipped.
    ///
    /// # Errors
    ///
    /// Returns [`Eip155ChainProviderError::NoHttpEndpoint`] if no HTTP(S)
    /// endpoint remains after filtering, or
    /// [`Eip155ChainProviderError::HttpClient`] if the HTTP client cannot be
    /// built.
    ///
    /// The client is HTTP/1.1-only and ignores env/system proxies.
    /// Workspace unification turns on `reqwest/{http2,system-proxy}` via
    /// other crates; HTTP/2 or a macOS system proxy against loopback
    /// JSON-RPC (wiremock) surfaces as `rpc_read_failed` / bad signatures.
    pub fn rpc_client(
        chain_id: &ChainId,
        endpoints: &[(Url, Option<u32>)],
    ) -> Result<RpcClient, Eip155ChainProviderError> {
        #[cfg(not(feature = "telemetry"))]
        let _ = chain_id;
        let http_client = Client::builder()
            .http1_only()
            .no_proxy()
            .build()
            .map_err(|_| Eip155ChainProviderError::HttpClient)?;
        let transports = endpoints
            .iter()
            .filter_map(|(url, rate_limit)| {
                let scheme = url.scheme();
                let is_http = scheme == "http" || scheme == "https";
                if !is_http {
                    return None;
                }
                #[cfg(feature = "telemetry")]
                tracing::info!(chain=%chain_id, rpc_url=%url, rate_limit=?rate_limit, "Using HTTP transport");
                let limit = rate_limit.unwrap_or(u32::MAX);
                let service = ServiceBuilder::new()
                    .layer(ThrottleLayer::new(limit))
                    .service(Http::with_client(http_client.clone(), url.clone()));
                Some(service)
            })
            .collect::<Vec<_>>();
        let count =
            NonZeroUsize::new(transports.len()).ok_or(Eip155ChainProviderError::NoHttpEndpoint)?;
        let fallback = ServiceBuilder::new()
            .layer(FallbackLayer::default().with_active_transport_count(count))
            .service(transports);
        Ok(RpcClient::new(fallback, false))
    }

    /// Round-robin selection of next signer from wallet.
    #[allow(
        clippy::indexing_slicing,
        reason = "bounds guaranteed by constructor requiring non-empty signers"
    )]
    fn next_signer_address(&self) -> Address {
        debug_assert!(
            !self.signer_addresses.is_empty(),
            "signer_addresses must not be empty"
        );
        if self.signer_addresses.len() == 1 {
            self.signer_addresses[0]
        } else {
            let next =
                self.signer_cursor.fetch_add(1, Ordering::Relaxed) % self.signer_addresses.len();
            self.signer_addresses[next]
        }
    }
}

/// Errors that can occur when sending a meta-transaction.
#[derive(Debug, thiserror::Error)]
pub enum MetaTransactionSendError {
    /// RPC transport error.
    #[error(transparent)]
    Transport(#[from] TransportError),
    /// Pending transaction error.
    #[error(transparent)]
    PendingTransaction(#[from] PendingTransactionError),
    /// Broadcast succeeded; waiting for the receipt failed.
    #[error("receipt wait failed for {hash}")]
    ReceiptWait {
        /// Broadcast transaction hash.
        hash: TxHash,
        /// Underlying receipt-wait error.
        #[source]
        source: PendingTransactionError,
    },
    /// Custom error message.
    #[error("{0}")]
    Custom(String),
}

/// Meta-transaction parameters: target address, calldata, required
/// confirmations, and native value.
#[derive(Debug, Clone)]
pub struct MetaTransaction {
    /// Target contract address.
    pub to: Address,
    /// Transaction calldata (encoded function call).
    pub calldata: Bytes,
    /// Number of block confirmations to wait for.
    pub confirmations: u64,
    /// Optional pinned signer address. When `None`, the provider picks a
    /// signer using its standard rotation strategy (round-robin in
    /// [`Eip155ChainProvider`]). When `Some`, the provider MUST submit the
    /// transaction from that exact address (used by the upto scheme to
    /// satisfy `msg.sender == witness.facilitator`).
    pub from: Option<Address>,
    /// Native token amount attached to the transaction.
    pub value: U256,
}

impl MetaTransaction {
    /// Builds a meta-transaction with no signer pinning and zero native value.
    #[must_use]
    pub const fn new(to: Address, calldata: Bytes, confirmations: u64) -> Self {
        Self {
            to,
            calldata,
            confirmations,
            from: None,
            value: U256::ZERO,
        }
    }

    /// Sets the pinned signer address; consuming and returning `self`.
    #[must_use]
    pub const fn with_from(mut self, from: Address) -> Self {
        self.from = Some(from);
        self
    }

    /// Appends a settlement calldata suffix (ERC-8021 builder-code `w`).
    #[must_use]
    pub fn with_data_suffix(mut self, suffix: &[u8]) -> Self {
        self.calldata = crate::chain::append_data_suffix(self.calldata, suffix);
        self
    }
}

impl ChainProvider for Eip155ChainProvider {
    fn signer_addresses(&self) -> Vec<String> {
        self.inner
            .signer_addresses()
            .map(|a| a.to_string())
            .collect()
    }

    fn chain_id(&self) -> ChainId {
        self.chain.into()
    }
}

/// Trait for sending meta-transactions with custom target and calldata.
pub trait Eip155MetaTransactionProvider {
    /// Error type for operations.
    type Error;
    /// Underlying provider type.
    type Inner: Provider;

    /// Returns reference to underlying provider.
    fn inner(&self) -> &Self::Inner;
    /// Returns reference to chain descriptor.
    fn chain(&self) -> &Eip155ChainReference;

    /// Sends a meta-transaction to the network.
    fn send_transaction(
        &self,
        tx: MetaTransaction,
    ) -> impl Future<Output = Result<TransactionReceipt, Self::Error>> + Send;

    /// `eth_sendRawTransaction` of a buyer-signed EIP-2718 envelope.
    ///
    /// Does not consume a facilitator nonce.
    ///
    /// # Errors
    ///
    /// Returns a transport error if broadcast fails, or a receipt-wait error if
    /// the transaction is not confirmed within the provider timeout.
    fn send_raw_transaction(
        &self,
        encoded: &[u8],
        confirmations: u64,
    ) -> impl Future<Output = Result<TransactionReceipt, Self::Error>> + Send;
}

impl<T: Eip155MetaTransactionProvider> Eip155MetaTransactionProvider for Arc<T> {
    type Error = T::Error;
    type Inner = T::Inner;

    fn inner(&self) -> &Self::Inner {
        (**self).inner()
    }

    fn chain(&self) -> &Eip155ChainReference {
        (**self).chain()
    }

    fn send_transaction(
        &self,
        tx: MetaTransaction,
    ) -> impl Future<Output = Result<TransactionReceipt, Self::Error>> + Send {
        (**self).send_transaction(tx)
    }

    fn send_raw_transaction(
        &self,
        encoded: &[u8],
        confirmations: u64,
    ) -> impl Future<Output = Result<TransactionReceipt, Self::Error>> + Send {
        (**self).send_raw_transaction(encoded, confirmations)
    }
}

impl Eip155MetaTransactionProvider for Eip155ChainProvider {
    type Error = MetaTransactionSendError;
    type Inner = InnerProvider;

    fn inner(&self) -> &Self::Inner {
        &self.inner
    }

    fn chain(&self) -> &Eip155ChainReference {
        &self.chain
    }

    /// Send a meta-transaction with provided `to`, `calldata`, and a signer.
    ///
    /// When [`MetaTransaction::from`] is set, the provider validates that
    /// the address is in its wallet and uses it as the EOA submitter (the
    /// upto scheme requires `msg.sender == witness.facilitator`). Otherwise
    /// it falls back to round-robin selection across configured signers.
    /// Gas pricing follows the network's EIP-1559 capability.
    ///
    /// If the transaction fails at any point (during submission or receipt fetching), the nonce
    /// for the sending address is reset to force a fresh query on the next transaction. This
    /// ensures correctness even when transactions partially succeed (e.g., submitted but receipt
    /// fetch times out).
    ///
    /// # Gas Pricing Strategy
    ///
    /// - **EIP-1559 networks**: Uses automatic gas pricing via the provider's fillers.
    /// - **Legacy networks**: Fetches the current gas price using `get_gas_price()` and sets it explicitly.
    ///
    /// # Timeout Configuration
    ///
    /// Receipt fetching is subject to a configurable timeout:
    /// - Default: 30 seconds
    /// - Override via `TX_RECEIPT_TIMEOUT_SECS` environment variable
    /// - If the timeout expires, the nonce is reset and an error is returned
    ///
    /// # Parameters
    ///
    /// - `tx`: A [`MetaTransaction`] containing the target address and calldata.
    ///
    /// # Returns
    ///
    /// A [`TransactionReceipt`] once the transaction has been mined and confirmed.
    ///
    /// # Errors
    ///
    /// Returns `FacilitatorLocalError::ContractCall` if:
    /// - Gas price fetching fails (on legacy networks)
    /// - Transaction sending fails
    /// - Receipt retrieval fails or times out
    async fn send_transaction(
        &self,
        tx: MetaTransaction,
    ) -> Result<TransactionReceipt, Self::Error> {
        let from_address = match tx.from {
            Some(pinned) => {
                if !self.signer_addresses.contains(&pinned) {
                    return Err(MetaTransactionSendError::Custom(format!(
                        "requested signer {pinned} is not in the configured wallet"
                    )));
                }
                pinned
            }
            None => self.next_signer_address(),
        };
        let mut txr = TransactionRequest::default()
            .with_to(tx.to)
            .with_from(from_address)
            .with_input(tx.calldata)
            .with_value(tx.value);

        if !self.eip1559 {
            let provider = &self.inner;
            let gas_fut = provider.get_gas_price();
            #[cfg(feature = "telemetry")]
            let gas: u128 = gas_fut
                .instrument(tracing::info_span!("get_gas_price"))
                .await?;
            #[cfg(not(feature = "telemetry"))]
            let gas: u128 = gas_fut.await?;
            txr.set_gas_price(gas);
        }

        // Estimate gas if not provided
        if txr.gas.is_none() {
            let block_id = if self.flashblocks {
                BlockId::latest()
            } else {
                BlockId::pending()
            };
            let gas_limit = self.inner.estimate_gas(txr.clone()).block(block_id).await?;
            txr.set_gas_limit(gas_limit);
        }

        // Send transaction with error handling for nonce reset
        let pending_tx = match self.inner.send_transaction(txr).await {
            Ok(pending) => pending,
            Err(e) => {
                // Transaction submission failed - reset nonce to force requery
                self.nonce_manager.reset_nonce(from_address).await;
                return Err(MetaTransactionSendError::Transport(e));
            }
        };

        // Get receipt with timeout and error handling for nonce reset
        // Default timeout of 30 seconds is reasonable for most EVM chains
        let timeout = std::time::Duration::from_secs(self.receipt_timeout_secs);

        let tx_hash = *pending_tx.tx_hash();
        let watcher = pending_tx
            .with_required_confirmations(tx.confirmations)
            .with_timeout(Some(timeout));

        match watcher.get_receipt().await {
            Ok(receipt) => Ok(receipt),
            Err(e) => {
                self.nonce_manager.reset_nonce(from_address).await;
                Err(MetaTransactionSendError::ReceiptWait {
                    hash: tx_hash,
                    source: e,
                })
            }
        }
    }

    async fn send_raw_transaction(
        &self,
        encoded: &[u8],
        confirmations: u64,
    ) -> Result<TransactionReceipt, Self::Error> {
        let pending_tx = self.inner.send_raw_transaction(encoded).await?;
        let timeout = std::time::Duration::from_secs(self.receipt_timeout_secs);
        let tx_hash = *pending_tx.tx_hash();
        let watcher = pending_tx
            .with_required_confirmations(confirmations)
            .with_timeout(Some(timeout));
        match watcher.get_receipt().await {
            Ok(receipt) => Ok(receipt),
            Err(e) => Err(MetaTransactionSendError::ReceiptWait {
                hash: tx_hash,
                source: e,
            }),
        }
    }
}

#[cfg(test)]
#[allow(
    clippy::expect_used,
    clippy::unwrap_used,
    reason = "test assertions on known-valid fixtures"
)]
mod tests {
    use std::str::FromStr;
    use std::sync::{Arc, Mutex};

    use super::*;

    const RAW_TX_HASH: TxHash = TxHash::repeat_byte(0x11);

    fn chain_id() -> ChainId {
        "eip155:8453".parse().expect("fixture chain id")
    }

    #[test]
    fn rpc_client_rejects_empty_endpoints() {
        let err = Eip155ChainProvider::rpc_client(&chain_id(), &[]).unwrap_err();
        assert_eq!(
            err,
            Eip155ChainProviderError::NoHttpEndpoint,
            "empty endpoint list must return NoHttpEndpoint, not panic"
        );
    }

    #[test]
    fn rpc_client_rejects_non_http_endpoints() {
        let ws = Url::parse("ws://127.0.0.1:8545").expect("fixture ws url");
        let err = Eip155ChainProvider::rpc_client(&chain_id(), &[(ws, None)]).unwrap_err();
        assert_eq!(
            err,
            Eip155ChainProviderError::NoHttpEndpoint,
            "non-HTTP endpoints must return NoHttpEndpoint after filtering"
        );
    }

    #[test]
    fn rpc_client_accepts_https_endpoint() {
        let url = Url::parse("https://mainnet.base.org").expect("fixture rpc url");
        Eip155ChainProvider::rpc_client(&chain_id(), &[(url, None)])
            .expect("HTTPS endpoint must construct");
    }

    #[test]
    fn meta_transaction_new_defaults_value_zero() {
        let tx = MetaTransaction::new(Address::ZERO, Bytes::new(), 1);
        assert_eq!(tx.value, U256::ZERO, "new() defaults value to zero");
        assert_eq!(tx.from, None, "new() does not pin a signer");
        let pinned = Address::repeat_byte(0x42);
        let tx = tx.with_from(pinned);
        assert_eq!(tx.from, Some(pinned), "with_from pins signer");
        assert_eq!(tx.value, U256::ZERO, "with_from leaves value unchanged");
    }

    #[test]
    fn with_data_suffix_preserves_value() {
        let mut tx = MetaTransaction::new(Address::ZERO, Bytes::from_static(&[0x01]), 2);
        tx.value = U256::from(9u64);
        let tx = tx.with_data_suffix(&[0xaa]);
        assert_eq!(tx.value, U256::from(9u64), "suffix must not clobber value");
        assert_eq!(
            tx.calldata.as_ref(),
            &[0x01, 0xaa],
            "suffix appends calldata"
        );
        assert_eq!(tx.confirmations, 2, "suffix must not clobber confirmations");
    }

    fn anvil_wallet() -> EthereumWallet {
        let signer = alloy_signer_local::PrivateKeySigner::from_str(
            "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80",
        )
        .expect("anvil key");
        EthereumWallet::from(signer)
    }

    fn provider_http(rpc: &str, receipt_timeout_secs: u64) -> Eip155ChainProvider {
        let url = Url::parse(rpc).expect("rpc url");
        Eip155ChainProvider::new(
            Eip155ChainReference::new(8453),
            anvil_wallet(),
            &[(url, None)],
            true,
            false,
            receipt_timeout_secs,
        )
        .expect("provider")
    }

    fn mined_receipt_json(hash: TxHash) -> serde_json::Value {
        serde_json::json!({
            "transactionHash": hash,
            "transactionIndex": "0x0",
            "blockHash": "0x2222222222222222222222222222222222222222222222222222222222222222",
            "blockNumber": "0x1",
            "from": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
            "to": "0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003",
            "cumulativeGasUsed": "0x1",
            "gasUsed": "0x1",
            "effectiveGasPrice": "0x1",
            "contractAddress": null,
            "logs": [],
            "logsBloom": format!("0x{}", "0".repeat(512)),
            "status": "0x1",
            "type": "0x2"
        })
    }

    fn rpc_result(
        id: &serde_json::Value,
        result: &serde_json::Value,
    ) -> wiremock::ResponseTemplate {
        wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": result
        }))
    }

    fn rpc_error(id: &serde_json::Value, message: &str) -> wiremock::ResponseTemplate {
        wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "jsonrpc": "2.0",
            "id": id,
            "error": { "code": -32000, "message": message }
        }))
    }

    fn raw_tx_hex(body: &serde_json::Value) -> Option<String> {
        body.get("params")
            .and_then(serde_json::Value::as_array)
            .and_then(|params| params.first())
            .and_then(serde_json::Value::as_str)
            .map(str::to_owned)
    }

    #[derive(Clone, Copy)]
    enum RawRpcMode {
        BroadcastFail,
        ReceiptRpcFail,
        ReceiptTimeout,
        Mined,
    }

    #[derive(Clone)]
    struct RawRpc {
        mode: RawRpcMode,
        captured: Arc<Mutex<Option<String>>>,
    }

    impl RawRpc {
        fn remember_raw(&self, body: &serde_json::Value) {
            let Some(hex) = raw_tx_hex(body) else {
                return;
            };
            *self.captured.lock().expect("captured") = Some(hex);
        }
    }

    impl wiremock::Respond for RawRpc {
        fn respond(&self, request: &wiremock::Request) -> wiremock::ResponseTemplate {
            let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default();
            let id = body
                .get("id")
                .cloned()
                .unwrap_or_else(|| serde_json::json!(1));
            let method = body
                .get("method")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("");
            if method == "eth_sendRawTransaction" {
                self.remember_raw(&body);
                return match self.mode {
                    RawRpcMode::BroadcastFail => rpc_error(&id, "broadcast failed"),
                    _ => rpc_result(&id, &serde_json::json!(RAW_TX_HASH)),
                };
            }
            if method == "eth_getTransactionReceipt" {
                return match self.mode {
                    RawRpcMode::Mined => rpc_result(&id, &mined_receipt_json(RAW_TX_HASH)),
                    RawRpcMode::ReceiptRpcFail => rpc_error(&id, "receipt failed"),
                    _ => rpc_result(&id, &serde_json::Value::Null),
                };
            }
            if method == "eth_blockNumber" {
                return rpc_result(&id, &serde_json::json!("0x1"));
            }
            rpc_result(&id, &serde_json::json!("0x"))
        }
    }

    async fn mount_raw_rpc(
        server: &wiremock::MockServer,
        mode: RawRpcMode,
    ) -> Arc<Mutex<Option<String>>> {
        let captured = Arc::new(Mutex::new(None));
        let script = RawRpc {
            mode,
            captured: Arc::clone(&captured),
        };
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(script)
            .mount(server)
            .await;
        captured
    }

    #[tokio::test]
    async fn send_raw_transaction_broadcast_error_is_transport() {
        let server = wiremock::MockServer::start().await;
        let captured = mount_raw_rpc(&server, RawRpcMode::BroadcastFail).await;
        let provider = provider_http(&server.uri(), 1);
        let encoded = [0x02, 0xaa, 0xbb];
        let err = provider
            .send_raw_transaction(&encoded, 1)
            .await
            .expect_err("broadcast failure must not succeed");
        assert!(
            matches!(err, MetaTransactionSendError::Transport(_)),
            "broadcast RPC error must be Transport, got {err}"
        );
        let hex = captured.lock().expect("captured").clone();
        assert_eq!(
            hex.as_deref(),
            Some("0x02aabb"),
            "raw envelope must be forwarded as hex"
        );
    }

    #[tokio::test]
    async fn send_raw_transaction_waits_for_receipt() {
        let server = wiremock::MockServer::start().await;
        mount_raw_rpc(&server, RawRpcMode::Mined).await;
        let provider = provider_http(&server.uri(), 5);
        let receipt = provider
            .send_raw_transaction(&[0x02], 1)
            .await
            .expect("mined raw tx");
        assert_eq!(
            receipt.transaction_hash, RAW_TX_HASH,
            "receipt hash must match eth_sendRawTransaction result"
        );
        assert!(receipt.status(), "fixture receipt is successful");
    }

    #[tokio::test]
    async fn send_raw_transaction_receipt_rpc_error_is_receipt_wait() {
        let server = wiremock::MockServer::start().await;
        mount_raw_rpc(&server, RawRpcMode::ReceiptRpcFail).await;
        let provider = provider_http(&server.uri(), 1);
        let err = provider
            .send_raw_transaction(&[0x02], 1)
            .await
            .expect_err("receipt RPC failure must not succeed");
        match err {
            MetaTransactionSendError::ReceiptWait { hash, .. } => {
                assert_eq!(
                    hash, RAW_TX_HASH,
                    "ReceiptWait must carry the broadcast hash"
                );
            }
            other => panic!("expected ReceiptWait, got {other}"),
        }
    }

    #[tokio::test]
    async fn send_raw_transaction_receipt_timeout_is_receipt_wait() {
        let server = wiremock::MockServer::start().await;
        mount_raw_rpc(&server, RawRpcMode::ReceiptTimeout).await;
        let provider = provider_http(&server.uri(), 1);
        let err = provider
            .send_raw_transaction(&[0x02], 1)
            .await
            .expect_err("missing receipt must time out");
        assert!(
            matches!(err, MetaTransactionSendError::ReceiptWait { .. }),
            "timeout must be ReceiptWait, got {err}"
        );
    }
}