Skip to main content

foundry_primitives/network/
receipt.rs

1use crate::FoundryReceiptEnvelope;
2use alloy_network::{AnyReceiptEnvelope, AnyTransactionReceipt, ReceiptResponse};
3use alloy_primitives::{Address, B256, BlockHash, TxHash};
4use alloy_rpc_types::{ConversionError, Log, TransactionReceipt};
5use alloy_serde::WithOtherFields;
6use derive_more::AsRef;
7use serde::{Deserialize, Serialize};
8use tempo_primitives::TEMPO_TX_TYPE_ID;
9
10#[cfg(any(feature = "base", feature = "optimism"))]
11use super::optimism::build_deposit_receipt_envelope;
12
13#[cfg(feature = "base")]
14use alloy_consensus::ReceiptWithBloom;
15#[cfg(feature = "base")]
16use alloy_primitives::U64;
17#[cfg(feature = "base")]
18use base_common_consensus::BASE_TX_TYPE_ID as EIP8130_TRANSACTION_TYPE;
19#[cfg(feature = "base")]
20use base_common_consensus::TxBaseReceipt;
21
22#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, AsRef)]
23pub struct FoundryTxReceipt(pub WithOtherFields<TransactionReceipt<FoundryReceiptEnvelope<Log>>>);
24
25impl FoundryTxReceipt {
26    pub fn new(inner: TransactionReceipt<FoundryReceiptEnvelope<Log>>) -> Self {
27        Self(WithOtherFields::new(inner))
28    }
29
30    /// Creates a new receipt with a timestamp in the other fields.
31    /// This avoids extra block lookups when timestamp is needed later.
32    pub fn with_timestamp(
33        inner: TransactionReceipt<FoundryReceiptEnvelope<Log>>,
34        timestamp: u64,
35    ) -> Self {
36        let mut receipt = WithOtherFields::new(inner);
37        receipt
38            .other
39            .insert("blockTimestamp".to_string(), serde_json::to_value(timestamp).unwrap());
40        Self(receipt)
41    }
42
43    /// Adds a `feePayer` field to the receipt.
44    pub fn with_fee_payer(mut self, fee_payer: Address) -> Self {
45        self.0.other.insert("feePayer".to_string(), serde_json::to_value(fee_payer).unwrap());
46        self
47    }
48
49    /// Adds a `feeToken` field to the receipt.
50    pub fn with_fee_token(mut self, fee_token: Address) -> Self {
51        self.0.other.insert("feeToken".to_string(), serde_json::to_value(fee_token).unwrap());
52        self
53    }
54
55    /// Get block timestamp from other fields if present.
56    pub fn block_timestamp(&self) -> Option<u64> {
57        self.0.other.get_deserialized::<u64>("blockTimestamp").transpose().ok().flatten()
58    }
59}
60
61impl ReceiptResponse for FoundryTxReceipt {
62    fn contract_address(&self) -> Option<Address> {
63        self.0.contract_address
64    }
65
66    fn status(&self) -> bool {
67        self.0.inner.status()
68    }
69
70    fn block_hash(&self) -> Option<BlockHash> {
71        self.0.block_hash
72    }
73
74    fn block_number(&self) -> Option<u64> {
75        self.0.block_number
76    }
77
78    fn transaction_hash(&self) -> TxHash {
79        self.0.transaction_hash
80    }
81
82    fn transaction_index(&self) -> Option<u64> {
83        self.0.transaction_index()
84    }
85
86    fn gas_used(&self) -> u64 {
87        self.0.gas_used()
88    }
89
90    fn effective_gas_price(&self) -> u128 {
91        self.0.effective_gas_price()
92    }
93
94    fn blob_gas_used(&self) -> Option<u64> {
95        self.0.blob_gas_used()
96    }
97
98    fn blob_gas_price(&self) -> Option<u128> {
99        self.0.blob_gas_price()
100    }
101
102    fn from(&self) -> Address {
103        self.0.from()
104    }
105
106    fn to(&self) -> Option<Address> {
107        self.0.to()
108    }
109
110    fn cumulative_gas_used(&self) -> u64 {
111        self.0.cumulative_gas_used()
112    }
113
114    fn state_root(&self) -> Option<B256> {
115        self.0.state_root()
116    }
117}
118
119impl TryFrom<AnyTransactionReceipt> for FoundryTxReceipt {
120    type Error = ConversionError;
121
122    fn try_from(receipt: AnyTransactionReceipt) -> Result<Self, Self::Error> {
123        let WithOtherFields {
124            inner:
125                TransactionReceipt {
126                    transaction_hash,
127                    transaction_index,
128                    block_hash,
129                    block_number,
130                    gas_used,
131                    contract_address,
132                    effective_gas_price,
133                    from,
134                    to,
135                    blob_gas_price,
136                    blob_gas_used,
137                    inner: AnyReceiptEnvelope { inner: receipt_with_bloom, r#type },
138                },
139            other,
140        } = receipt.0;
141
142        // The untyped envelope leaves the EIP-8130 `committedPhases` among the other fields; it
143        // moves into the typed receipt.
144        #[cfg(feature = "base")]
145        let mut other = other;
146        #[cfg(feature = "base")]
147        let committed_phases = if r#type == EIP8130_TRANSACTION_TYPE {
148            other
149                .remove_deserialized::<U64>("committedPhases")
150                .transpose()
151                .map_err(|err| ConversionError::Custom(err.to_string()))?
152                .unwrap_or_default()
153                .to::<u64>()
154        } else {
155            0
156        };
157
158        Ok(Self(WithOtherFields {
159            inner: TransactionReceipt {
160                transaction_hash,
161                transaction_index,
162                block_hash,
163                block_number,
164                gas_used,
165                contract_address,
166                effective_gas_price,
167                from,
168                to,
169                blob_gas_price,
170                blob_gas_used,
171                inner: match r#type {
172                    0x00 => FoundryReceiptEnvelope::Legacy(receipt_with_bloom),
173                    0x01 => FoundryReceiptEnvelope::Eip2930(receipt_with_bloom),
174                    0x02 => FoundryReceiptEnvelope::Eip1559(receipt_with_bloom),
175                    0x03 => FoundryReceiptEnvelope::Eip4844(receipt_with_bloom),
176                    0x04 => FoundryReceiptEnvelope::Eip7702(receipt_with_bloom),
177                    #[cfg(feature = "base")]
178                    EIP8130_TRANSACTION_TYPE => FoundryReceiptEnvelope::Eip8130(ReceiptWithBloom {
179                        receipt: TxBaseReceipt::new(receipt_with_bloom.receipt, committed_phases),
180                        logs_bloom: receipt_with_bloom.logs_bloom,
181                    }),
182                    TEMPO_TX_TYPE_ID => FoundryReceiptEnvelope::Tempo(receipt_with_bloom),
183                    #[cfg(any(feature = "base", feature = "optimism"))]
184                    0x7E => build_deposit_receipt_envelope(receipt_with_bloom, &other),
185                    // Chains anvil can fork but not execute, such as Arbitrum and its Orbit
186                    // rollups, mint their own transaction types. Keep those receipts verbatim
187                    // instead of failing the whole request.
188                    ty => FoundryReceiptEnvelope::Unknown(AnyReceiptEnvelope {
189                        inner: receipt_with_bloom,
190                        r#type: ty,
191                    }),
192                },
193            },
194            other,
195        }))
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[cfg(feature = "base")]
204    #[test]
205    fn eip8130_rpc_receipt_preserves_committed_phases() {
206        let receipt: AnyTransactionReceipt = serde_json::from_value(serde_json::json!({
207            "type": "0x79", "status": "0x0", "cumulativeGasUsed": "0x1", "gasUsed": "0x1",
208            "logs": [], "logsBloom": alloy_primitives::Bloom::ZERO,
209            "transactionHash": B256::ZERO, "from": Address::ZERO,
210            "phaseStatuses": ["0x1", "0x1", "0x0"]
211        }))
212        .unwrap();
213        for committed in [0u64, 2] {
214            let mut original = receipt.clone();
215            original.0.other.insert("committedPhases".into(), format!("{committed:#x}").into());
216            let converted = FoundryTxReceipt::try_from(original.clone()).unwrap();
217            assert_eq!(converted.0.inner.inner.eip8130_committed_phases(), Some(committed));
218            let json = serde_json::to_value(&converted).unwrap();
219            let typed: FoundryTxReceipt = serde_json::from_value(json.clone()).unwrap();
220            assert_eq!(typed, converted);
221            let roundtrip: AnyTransactionReceipt = serde_json::from_value(json).unwrap();
222            assert_eq!(roundtrip, original);
223        }
224        let mut invalid = receipt;
225        invalid.0.other.insert("committedPhases".into(), serde_json::json!("invalid"));
226        assert!(FoundryTxReceipt::try_from(invalid).is_err());
227    }
228
229    // <https://github.com/foundry-rs/foundry/issues/10852>
230    #[test]
231    fn test_receipt_convert() {
232        let s = r#"{"type":"0x4","status":"0x1","cumulativeGasUsed":"0x903fd1","logs":[{"address":"0x0000d9fcd47bf761e7287d8ee09917d7e2100000","topics":["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef","0x0000000000000000000000000000000000000000000000000000000000000000","0x000000000000000000000000234ce51365b9c417171b6dad280f49143e1b0547"],"data":"0x00000000000000000000000000000000000000000000032139b42c3431700000","blockHash":"0xd26b59c1d8b5bfa9362d19eb0da3819dfe0b367987a71f6d30908dd45e0d7a60","blockNumber":"0x159663e","blockTimestamp":"0x68411f7b","transactionHash":"0x17a6af73d1317e69cfc3cac9221bd98261d40f24815850a44dbfbf96652ae52a","transactionIndex":"0x22","logIndex":"0x158","removed":false}],"logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000008100000000000000000000000000000000000000000000000020000200000000000000800000000800000000000000010000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000","transactionHash":"0x17a6af73d1317e69cfc3cac9221bd98261d40f24815850a44dbfbf96652ae52a","transactionIndex":"0x22","blockHash":"0xd26b59c1d8b5bfa9362d19eb0da3819dfe0b367987a71f6d30908dd45e0d7a60","blockNumber":"0x159663e","gasUsed":"0x28ee7","effectiveGasPrice":"0x4bf02090","from":"0x234ce51365b9c417171b6dad280f49143e1b0547","to":"0x234ce51365b9c417171b6dad280f49143e1b0547","contractAddress":null}"#;
233        let receipt: AnyTransactionReceipt = serde_json::from_str(s).unwrap();
234        let _converted = FoundryTxReceipt::try_from(receipt).unwrap();
235    }
236
237    // Arbitrum and its Orbit rollups mint transaction types anvil cannot execute; forked receipts
238    // for them must still convert, keeping the original type byte.
239    #[test]
240    fn test_arbitrum_internal_receipt_convert() {
241        let s = r#"{"type":"0x6a","status":"0x1","cumulativeGasUsed":"0x0","logs":[],"logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","transactionHash":"0x7c9e0e2b0f2ffbd0a1ee3e2e2b6ff5a2ff8b6a0f1c0b4a5c1d5a8b6c9d0e1f22","transactionIndex":"0x0","blockHash":"0x3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f3a2b","blockNumber":"0x159663e","gasUsed":"0x0","effectiveGasPrice":"0x0","from":"0x00000000000000000000000000000000000a4b05","to":"0x00000000000000000000000000000000000a4b05","contractAddress":null,"gasUsedForL1":"0x0","l1BlockNumber":"0x1499e2c"}"#;
242        let receipt: AnyTransactionReceipt = serde_json::from_str(s).unwrap();
243        let converted = FoundryTxReceipt::try_from(receipt).unwrap();
244
245        assert!(converted.0.inner.inner.is_unknown());
246        assert_eq!(converted.0.inner.inner.ty(), 0x6a);
247        assert_eq!(serde_json::to_value(&converted).unwrap()["type"], "0x6a");
248    }
249}