Skip to main content

forge_script/
receipts.rs

1use alloy_chains::{Chain, NamedChain};
2use alloy_network::{Network, ReceiptResponse};
3use alloy_primitives::{TxHash, U256, utils::format_units};
4use alloy_provider::{
5    PendingTransactionBuilder, PendingTransactionError, Provider, RootProvider, WatchTxError,
6};
7use eyre::{Result, eyre};
8use forge_script_sequence::ScriptSequence;
9use foundry_common::{retry, retry::RetryError, shell};
10use indicatif::MultiProgress;
11use std::{
12    sync::atomic::{AtomicBool, Ordering},
13    time::Duration,
14};
15
16/// Marker error type for pending receipts
17#[derive(Debug, thiserror::Error)]
18#[error(
19    "Received a pending receipt for {tx_hash}, but transaction is still known to the node, retrying"
20)]
21pub struct PendingReceiptError {
22    pub tx_hash: TxHash,
23}
24
25/// Convenience enum for internal signalling of transaction status
26pub enum TxStatus<R: ReceiptResponse> {
27    Dropped,
28    Success(R),
29    Revert(R),
30}
31
32impl<R: ReceiptResponse> From<R> for TxStatus<R> {
33    fn from(receipt: R) -> Self {
34        if receipt.status() { Self::Success(receipt) } else { Self::Revert(receipt) }
35    }
36}
37
38/// Checks the status of a txhash by first polling for a receipt, then for
39/// mempool inclusion. Returns the tx hash, and a status
40///
41/// While the transaction stays pending past `timeout`, warns once above `progress` that it is still
42/// being waited on.
43pub async fn check_tx_status<N: Network>(
44    provider: &RootProvider<N>,
45    hash: TxHash,
46    timeout: u64,
47    confirmations: u64,
48    progress: &MultiProgress,
49) -> (TxHash, Result<TxStatus<N::ReceiptResponse>, eyre::Report>) {
50    let warned = AtomicBool::new(false);
51    let result = retry::Retry::new_no_delay(3)
52        .run_async_until_break(|| async {
53            match PendingTransactionBuilder::new(provider.clone(), hash)
54                .with_timeout(Some(Duration::from_secs(timeout)))
55                .with_required_confirmations(confirmations)
56                .get_receipt()
57                .await
58            {
59                Ok(receipt) => {
60                    if is_mined_receipt_for(&receipt, hash) {
61                        return Ok(receipt.into());
62                    }
63
64                    // Receipt is pending or foreign, try to sleep and retry a few times
65                    match provider.get_transaction_by_hash(hash).await {
66                        Ok(Some(_)) => {
67                            // Sleep for a short time to allow the transaction to be mined
68                            tokio::time::sleep(Duration::from_millis(500)).await;
69                            // Transaction is still known to the node, retry
70                            Err(RetryError::Retry(PendingReceiptError { tx_hash: hash }.into()))
71                        }
72                        Ok(None) => {
73                            // Transaction is not known to the node, mark it as dropped
74                            Ok(TxStatus::Dropped)
75                        }
76                        Err(err) => Err(RetryError::Retry(eyre!(
77                            "failed to check if transaction {hash} is still known to the node: {err}"
78                        ))),
79                    }
80                }
81                Err(e) => match provider.get_transaction_by_hash(hash).await {
82                    Ok(Some(_)) => match e {
83                        PendingTransactionError::TxWatcher(WatchTxError::Timeout) => {
84                            // Waiting is unbounded, so name the transaction once; progress bars
85                            // are hidden outside a terminal and redrawn over plain output in one.
86                            if !warned.swap(true, Ordering::Relaxed) {
87                                progress.suspend(|| {
88                                    let _ = sh_warn!(
89                                        "Transaction {hash} has not been mined after {timeout}s; still waiting for its receipt."
90                                    );
91                                });
92                            }
93                            Err(RetryError::Continue(eyre!(
94                                "tx is still known to the node, waiting for receipt"
95                            )))
96                        }
97                        _ => Err(RetryError::Retry(e.into())),
98                    },
99                    Ok(None) => Ok(TxStatus::Dropped),
100                    Err(err) => Err(RetryError::Retry(eyre!(
101                        "failed to check if transaction {hash} is still known to the node after receipt error: {err}; receipt error: {e}"
102                    ))),
103                },
104            }
105        })
106        .await;
107
108    (hash, result)
109}
110
111/// Checks the status of a txhash once without waiting. Returns `None` while the transaction is
112/// still known to the node but has no receipt with the requested confirmations.
113pub async fn check_tx_status_once<N: Network>(
114    provider: &RootProvider<N>,
115    hash: TxHash,
116    confirmations: u64,
117) -> Option<TxStatus<N::ReceiptResponse>> {
118    let receipt = provider
119        .get_transaction_receipt(hash)
120        .await
121        .ok()
122        .flatten()
123        .filter(|receipt| is_mined_receipt_for(receipt, hash));
124    if let Some(receipt) = receipt {
125        let confirmed = confirmations <= 1
126            || provider.get_block_number().await.is_ok_and(|latest| {
127                receipt.block_number().is_some_and(|block| {
128                    block.checked_add(confirmations - 1).is_some_and(|required| latest >= required)
129                })
130            });
131        return confirmed.then(|| receipt.into());
132    }
133    matches!(provider.get_transaction_by_hash(hash).await, Ok(None)).then_some(TxStatus::Dropped)
134}
135
136/// Returns true if `receipt` is a mined receipt for `hash`.
137pub(crate) fn is_mined_receipt_for<R: ReceiptResponse>(receipt: &R, hash: TxHash) -> bool {
138    receipt.transaction_hash() == hash
139        && receipt.block_number().is_some()
140        && receipt.block_hash().is_some()
141        && receipt.transaction_index().is_some()
142}
143
144/// Prints parts of the receipt to stdout
145pub fn format_receipt<N: Network>(
146    chain: Chain,
147    receipt: &N::ReceiptResponse,
148    sequence: Option<&ScriptSequence<N>>,
149) -> String {
150    let gas_used = receipt.gas_used();
151    let gas_price = receipt.effective_gas_price();
152    let block_number = receipt.block_number().unwrap_or_default();
153    let success = receipt.status();
154
155    let (contract_name, function) = sequence
156        .and_then(|seq| {
157            seq.transactions
158                .iter()
159                .find(|tx| tx.hash == Some(receipt.transaction_hash()))
160                .map(|tx| (tx.contract_name.clone(), tx.function.clone()))
161        })
162        .unwrap_or((None, None));
163
164    if shell::is_json() {
165        let mut json = serde_json::json!({
166            "chain": chain,
167            "status": if success {
168                "success"
169            } else {
170                "failed"
171            },
172            "tx_hash": receipt.transaction_hash(),
173            "contract_address": receipt.contract_address().map(|addr| addr.to_string()),
174            "block_number": block_number,
175            "gas_used": gas_used,
176            "gas_price": gas_price,
177        });
178
179        if let Some(name) = &contract_name
180            && !name.is_empty()
181        {
182            json["contract_name"] = serde_json::Value::String(name.clone());
183        }
184        if let Some(func) = &function
185            && !func.is_empty()
186        {
187            json["function"] = serde_json::Value::String(func.clone());
188        }
189
190        let _ = sh_println!("{}", json);
191
192        String::new()
193    } else {
194        let contract_info = match &contract_name {
195            Some(name) if !name.is_empty() => format!("\nContract: {name}"),
196            _ => String::new(),
197        };
198
199        let function_info = match &function {
200            Some(func) if !func.is_empty() => format!("\nFunction: {func}"),
201            _ => String::new(),
202        };
203
204        format!(
205            "\n##### {chain}\n{status} Hash: {tx_hash:?}{contract_info}{function_info}{contract_address}\nBlock: {block_number}\n{gas}\n\n",
206            status = if success { "✅  [Success]" } else { "❌  [Failed]" },
207            tx_hash = receipt.transaction_hash(),
208            contract_address = if let Some(addr) = receipt.contract_address() {
209                format!("\nContract Address: {}", addr.to_checksum(None))
210            } else {
211                String::new()
212            },
213            gas = if gas_price == 0 {
214                format!("Gas Used: {gas_used}")
215            } else {
216                let paid = format_units((gas_used as u128).saturating_mul(gas_price), 18)
217                    .unwrap_or_else(|_| "N/A".into());
218                let gas_price =
219                    format_units(U256::from(gas_price), 9).unwrap_or_else(|_| "N/A".into());
220                let token_symbol = NamedChain::try_from(chain)
221                    .unwrap_or_default()
222                    .native_currency_symbol()
223                    .unwrap_or("ETH");
224                format!(
225                    "Paid: {} {} ({gas_used} gas * {} gwei)",
226                    paid.trim_end_matches('0'),
227                    token_symbol,
228                    gas_price.trim_end_matches('0').trim_end_matches('.')
229                )
230            },
231        )
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238    use alloy_network::{Ethereum, TransactionBuilder};
239    use alloy_primitives::{B256, Bloom};
240    use alloy_provider::{ProviderBuilder, mock::Asserter};
241    use alloy_rpc_types::{TransactionReceipt, TransactionRequest};
242    use std::collections::VecDeque;
243
244    fn mock_receipt(tx_hash: B256, success: bool) -> TransactionReceipt {
245        serde_json::from_value(serde_json::json!({
246            "type": "0x02", "status": if success { "0x1" } else { "0x0" },
247            "cumulativeGasUsed": "0x5208", "logs": [], "transactionHash": tx_hash,
248            "logsBloom": format!("{:#x}", Bloom::ZERO),
249            "transactionIndex": "0x0", "blockHash": B256::ZERO, "blockNumber": "0x3039",
250            "gasUsed": "0x5208", "effectiveGasPrice": "0x4a817c800",
251            "from": "0x0000000000000000000000000000000000000000",
252            "to": "0x0000000000000000000000000000000000000000", "contractAddress": null
253        }))
254        .unwrap()
255    }
256
257    fn mock_sequence(
258        tx_hash: B256,
259        contract: Option<&str>,
260        func: Option<&str>,
261    ) -> ScriptSequence<Ethereum> {
262        let tx = serde_json::from_value(serde_json::json!({
263            "hash": tx_hash, "transactionType": "CALL",
264            "contractName": contract, "contractAddress": null, "function": func,
265            "arguments": null, "additionalContracts": [], "isFixedGasLimit": false,
266            "transaction": {
267                "type": "0x02", "chainId": "0x1", "nonce": "0x0", "gas": "0x5208",
268                "maxFeePerGas": "0x4a817c800", "maxPriorityFeePerGas": "0x3b9aca00",
269                "to": "0x0000000000000000000000000000000000000000",
270                "value": "0x0", "input": "0x", "accessList": []
271            },
272        }))
273        .unwrap();
274        ScriptSequence { transactions: VecDeque::from([tx]), chain: 1, ..Default::default() }
275    }
276
277    #[test]
278    fn format_receipt_displays_contract_and_function() {
279        let hash = B256::repeat_byte(0x42);
280        let seq = mock_sequence(hash, Some("MyContract"), Some("init(address)"));
281        let out = format_receipt(Chain::mainnet(), &mock_receipt(hash, true), Some(&seq));
282
283        assert!(out.contains("Contract: MyContract"));
284        assert!(out.contains("Function: init(address)"));
285        assert!(out.contains("✅  [Success]"));
286    }
287
288    #[test]
289    fn format_receipt_without_sequence_omits_metadata() {
290        let hash = B256::repeat_byte(0x42);
291        let out = format_receipt::<Ethereum>(Chain::mainnet(), &mock_receipt(hash, true), None);
292
293        assert!(!out.contains("Contract:"));
294        assert!(!out.contains("Function:"));
295    }
296
297    #[test]
298    fn format_receipt_skips_empty_contract_name() {
299        let hash = B256::repeat_byte(0x42);
300        let seq = mock_sequence(hash, Some(""), Some("transfer(address)"));
301        let out = format_receipt(Chain::mainnet(), &mock_receipt(hash, true), Some(&seq));
302
303        assert!(!out.contains("Contract:"));
304        assert!(out.contains("Function: transfer(address)"));
305    }
306
307    #[test]
308    fn format_receipt_handles_missing_tx_in_sequence() {
309        let seq = mock_sequence(B256::repeat_byte(0x99), Some("Other"), Some("other()"));
310        let out = format_receipt(
311            Chain::mainnet(),
312            &mock_receipt(B256::repeat_byte(0x42), true),
313            Some(&seq),
314        );
315
316        assert!(!out.contains("Contract:"));
317        assert!(!out.contains("Function:"));
318    }
319
320    #[test]
321    fn format_receipt_shows_contract_on_failure() {
322        let hash = B256::repeat_byte(0x42);
323        let seq = mock_sequence(hash, Some("FailContract"), Some("fail()"));
324        let out = format_receipt(Chain::mainnet(), &mock_receipt(hash, false), Some(&seq));
325
326        assert!(out.contains("❌  [Failed]"));
327        assert!(out.contains("Contract: FailContract"));
328    }
329
330    #[tokio::test]
331    async fn check_tx_status_marks_null_transaction_lookup_as_dropped() {
332        let hash = B256::repeat_byte(0x42);
333        let asserter = Asserter::new();
334        let provider: RootProvider<Ethereum> =
335            ProviderBuilder::default().connect_mocked_client(asserter.clone());
336        let not_found: Option<serde_json::Value> = None;
337
338        for _ in 0..50_000 {
339            asserter.push_success(&not_found);
340        }
341
342        let null_responder = tokio::spawn({
343            let asserter = asserter.clone();
344            async move {
345                let not_found: Option<serde_json::Value> = None;
346                loop {
347                    for _ in 0..1_000 {
348                        asserter.push_success(&not_found);
349                    }
350                    tokio::task::yield_now().await;
351                }
352            }
353        });
354
355        let result = tokio::time::timeout(
356            Duration::from_secs(2),
357            check_tx_status(&provider, hash, 0, 1, &Default::default()),
358        )
359        .await;
360        null_responder.abort();
361
362        let (returned_hash, status) = result.expect(
363            "check_tx_status should not keep waiting when eth_getTransactionByHash returns null",
364        );
365
366        assert_eq!(returned_hash, hash);
367        assert!(matches!(status.unwrap(), TxStatus::Dropped));
368    }
369
370    #[tokio::test]
371    async fn check_tx_status_once_requires_confirmations() {
372        let hash = B256::repeat_byte(0x42);
373        // The receipt is mined in block 0x3039.
374        for (latest, confirmations, confirmed) in [
375            (0x3039u64, 1, true),
376            (0x303a, 3, false),
377            (0x303b, 3, true),
378            (u64::MAX, u64::MAX, false),
379        ] {
380            let asserter = Asserter::new();
381            let provider: RootProvider<Ethereum> =
382                ProviderBuilder::default().connect_mocked_client(asserter.clone());
383            asserter.push_success(&mock_receipt(hash, true));
384            asserter.push_success(&U256::from(latest));
385
386            let status = check_tx_status_once(&provider, hash, confirmations).await;
387            assert_eq!(status.is_some(), confirmed, "{latest} {confirmations}");
388        }
389    }
390
391    #[tokio::test]
392    async fn check_tx_status_does_not_mark_lookup_errors_as_dropped() {
393        let hash = B256::repeat_byte(0x42);
394        let asserter = Asserter::new();
395        let provider: RootProvider<Ethereum> =
396            ProviderBuilder::default().connect_mocked_client(asserter.clone());
397        let not_found: Option<serde_json::Value> = None;
398
399        // Initial receipt lookup while registering the pending transaction.
400        asserter.push_success(&not_found);
401        for _ in 0..50 {
402            asserter.push_failure_msg("lookup unavailable");
403        }
404
405        let (_, status) = check_tx_status(&provider, hash, 0, 1, &Default::default()).await;
406        let err = match status {
407            Ok(_) => panic!("transaction lookup errors should not be marked as dropped"),
408            Err(err) => err.to_string(),
409        };
410
411        assert!(err.contains("failed to check if transaction"));
412        assert!(err.contains("lookup unavailable"));
413    }
414
415    #[tokio::test]
416    async fn check_tx_status_rejects_foreign_receipt() {
417        let hash = B256::repeat_byte(0x42);
418        let foreign = mock_receipt(B256::repeat_byte(0x99), true);
419        let asserter = Asserter::new();
420        let provider: RootProvider<Ethereum> =
421            ProviderBuilder::default().connect_mocked_client(asserter.clone());
422
423        // Receipt lookups while registering and polling, then the transaction lookup.
424        asserter.push_success(&foreign);
425        asserter.push_success(&foreign);
426        asserter.push_success(&None::<()>);
427
428        let (_, status) = check_tx_status(&provider, hash, 0, 1, &Default::default()).await;
429
430        assert!(matches!(status.unwrap(), TxStatus::Dropped));
431    }
432
433    /// Upper bound for the anvil-based `check_tx_status` tests, so a hang fails fast
434    /// instead of stalling the suite.
435    const CHECK_TX_TIMEOUT: Duration = Duration::from_secs(15);
436
437    /// A tx hash the node doesn't know about (rejected at submission or dropped from
438    /// the mempool) must resolve to `TxStatus::Dropped` rather than polling forever.
439    #[tokio::test(flavor = "multi_thread")]
440    async fn check_tx_status_unknown_tx_is_dropped() {
441        let (_api, handle) = anvil::spawn(anvil::NodeConfig::test()).await;
442        let provider = ProviderBuilder::new()
443            .connect_http(handle.http_endpoint().parse().unwrap())
444            .root()
445            .clone();
446
447        // Random hash the node has never seen.
448        let unknown_hash = B256::repeat_byte(0xab);
449
450        // Inner `timeout=1` bounds the pending-tx watcher; the outer `tokio::time::timeout`
451        // guarantees the test fails fast if the watcher ever hangs again.
452        let (returned_hash, status) = tokio::time::timeout(
453            CHECK_TX_TIMEOUT,
454            check_tx_status::<Ethereum>(&provider, unknown_hash, 1, 1, &Default::default()),
455        )
456        .await
457        .expect("check_tx_status hung on an unknown tx hash");
458
459        assert_eq!(returned_hash, unknown_hash);
460        let status = status.expect("unknown tx should resolve to Ok(TxStatus::Dropped)");
461        assert!(
462            matches!(status, TxStatus::Dropped),
463            "expected TxStatus::Dropped for an unknown tx",
464        );
465    }
466
467    /// A tx that is initially in the mempool (so `eth_getTransactionByHash` returns
468    /// `Some`) and is later dropped from it must:
469    ///   1. keep retrying while the node still knows the tx (the `Ok(Some(_))` branch), and
470    ///   2. resolve to `TxStatus::Dropped` once the node forgets it (the `Ok(None)` branch).
471    #[tokio::test(flavor = "multi_thread")]
472    async fn check_tx_status_known_then_dropped_resolves_to_dropped() {
473        // `no_mining` keeps the tx pending so `get_receipt` always times out and the
474        // watcher exercises the `WatchTxError::Timeout` + `get_transaction_by_hash`
475        // branch on every retry.
476        let (api, handle) = anvil::spawn(anvil::NodeConfig::test().with_no_mining(true)).await;
477        let signer_provider =
478            ProviderBuilder::new().connect_http(handle.http_endpoint().parse().unwrap());
479
480        let mut wallets = handle.dev_wallets();
481        let from = wallets.next().unwrap().address();
482        let to = wallets.next().unwrap().address();
483        let tx = TransactionRequest::default().with_from(from).with_to(to).with_value(U256::ONE);
484
485        let pending = signer_provider.send_transaction(tx).await.unwrap();
486        let tx_hash = *pending.tx_hash();
487
488        // Run `check_tx_status` concurrently; while it loops on `Ok(Some(_))`, drop the
489        // tx from the mempool so the next iteration sees `Ok(None)` and exits.
490        let provider = signer_provider.root().clone();
491        let watcher = tokio::spawn(async move {
492            tokio::time::timeout(
493                CHECK_TX_TIMEOUT,
494                check_tx_status::<Ethereum>(&provider, tx_hash, 1, 1, &Default::default()),
495            )
496            .await
497        });
498
499        // Give the watcher at least one Continue iteration before evicting the tx.
500        tokio::time::sleep(Duration::from_millis(1500)).await;
501        api.anvil_drop_transaction(tx_hash).await.unwrap();
502
503        let (returned_hash, status) = watcher
504            .await
505            .unwrap()
506            .expect("check_tx_status hung after the tx was dropped from the mempool");
507        assert_eq!(returned_hash, tx_hash);
508        let status = status.expect("dropped tx should resolve to Ok(TxStatus::Dropped)");
509        assert!(
510            matches!(status, TxStatus::Dropped),
511            "expected TxStatus::Dropped after the tx was evicted from the mempool",
512        );
513    }
514
515    /// A real, mined transaction must resolve to `TxStatus::Success` and not be
516    /// misclassified as dropped.
517    #[tokio::test(flavor = "multi_thread")]
518    async fn check_tx_status_mined_tx_is_success() {
519        let (_api, handle) = anvil::spawn(anvil::NodeConfig::test()).await;
520        let signer_provider =
521            ProviderBuilder::new().connect_http(handle.http_endpoint().parse().unwrap());
522
523        let mut wallets = handle.dev_wallets();
524        let from = wallets.next().unwrap().address();
525        let to = wallets.next().unwrap().address();
526        let tx = TransactionRequest::default().with_from(from).with_to(to).with_value(U256::ONE);
527
528        // Send and mine the tx so a receipt is immediately available.
529        let pending = signer_provider.send_transaction(tx).await.unwrap();
530        let tx_hash = *pending.tx_hash();
531        let _ = pending.get_receipt().await.unwrap();
532
533        let provider = signer_provider.root().clone();
534        let (returned_hash, status) = tokio::time::timeout(
535            CHECK_TX_TIMEOUT,
536            check_tx_status::<Ethereum>(&provider, tx_hash, 5, 1, &Default::default()),
537        )
538        .await
539        .expect("check_tx_status hung on a mined tx");
540
541        assert_eq!(returned_hash, tx_hash);
542        let status = status.expect("mined tx should resolve to Ok(TxStatus::Success)");
543        assert!(
544            matches!(status, TxStatus::Success(_)),
545            "expected TxStatus::Success for a mined ETH transfer",
546        );
547    }
548
549    #[tokio::test(flavor = "multi_thread")]
550    async fn check_tx_status_waits_for_confirmations() {
551        let (api, handle) = anvil::spawn(anvil::NodeConfig::test().with_no_mining(true)).await;
552        let signer_provider =
553            ProviderBuilder::new().connect_http(handle.http_endpoint().parse().unwrap());
554
555        let mut wallets = handle.dev_wallets();
556        let from = wallets.next().unwrap().address();
557        let to = wallets.next().unwrap().address();
558        let tx = TransactionRequest::default().with_from(from).with_to(to).with_value(U256::ONE);
559
560        let pending = signer_provider.send_transaction(tx).await.unwrap();
561        let tx_hash = *pending.tx_hash();
562        api.mine_one().await.unwrap();
563
564        let provider = signer_provider.root().clone();
565        let mut watcher = tokio::spawn(async move {
566            check_tx_status::<Ethereum>(&provider, tx_hash, 5, 3, &Default::default()).await
567        });
568
569        assert!(tokio::time::timeout(Duration::from_millis(500), &mut watcher).await.is_err());
570
571        api.anvil_mine(Some(U256::from(2)), None).await.unwrap();
572        let (returned_hash, status) =
573            tokio::time::timeout(CHECK_TX_TIMEOUT, watcher).await.unwrap().unwrap();
574
575        assert_eq!(returned_hash, tx_hash);
576        assert!(matches!(status.unwrap(), TxStatus::Success(_)));
577    }
578}