signet_bundle/send/
bundle.rs

1//! Signet bundle types.
2use crate::send::SignetEthBundleError;
3use alloy::{
4    consensus::TxEnvelope,
5    eips::Decodable2718,
6    network::Network,
7    primitives::{Bytes, B256},
8    providers::Provider,
9    rlp::Buf,
10    rpc::types::mev::EthSendBundle,
11};
12use serde::{Deserialize, Serialize};
13use signet_types::{SignedFill, SignedPermitError};
14use signet_zenith::HostOrders::HostOrdersInstance;
15use trevm::{revm::Database, BundleError};
16
17/// Bundle of transactions for `signet_sendBundle`.
18///
19/// The Signet bundle contains the following:
20///
21/// - A standard [`EthSendBundle`] with the transactions to simulate.
22/// - A signed permit2 fill to be applied on the Host chain with the bundle.
23///
24/// This is based on the flashbots `eth_sendBundle` bundle. See [their docs].
25///
26/// [their docs]: https://docs.flashbots.net/flashbots-auction/advanced/rpc-endpoint
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "camelCase")]
29pub struct SignetEthBundle {
30    /// The bundle of transactions to simulate. Same structure as a Flashbots [`EthSendBundle`] bundle.
31    #[serde(flatten)]
32    pub bundle: EthSendBundle,
33    /// Host fills to be applied with the bundle, represented as a signed
34    /// permit2 fill.
35    #[serde(default)]
36    pub host_fills: Option<SignedFill>,
37}
38
39impl SignetEthBundle {
40    /// Returns the transactions in this bundle.
41    #[allow(clippy::missing_const_for_fn)] // false positive
42    pub fn txs(&self) -> &[Bytes] {
43        &self.bundle.txs
44    }
45
46    /// Returns the block number for this bundle.
47    pub const fn block_number(&self) -> u64 {
48        self.bundle.block_number
49    }
50
51    /// Returns the minimum timestamp for this bundle.
52    pub const fn min_timestamp(&self) -> Option<u64> {
53        self.bundle.min_timestamp
54    }
55
56    /// Returns the maximum timestamp for this bundle.
57    pub const fn max_timestamp(&self) -> Option<u64> {
58        self.bundle.max_timestamp
59    }
60
61    /// Returns the reverting tx hashes for this bundle.
62    pub fn reverting_tx_hashes(&self) -> &[B256] {
63        self.bundle.reverting_tx_hashes.as_slice()
64    }
65
66    /// Returns the replacement uuid for this bundle.
67    pub fn replacement_uuid(&self) -> Option<&str> {
68        self.bundle.replacement_uuid.as_deref()
69    }
70
71    /// Decode and validate the transactions in the bundle.
72    pub fn decode_and_validate_txs<Db: Database>(
73        &self,
74    ) -> Result<Vec<TxEnvelope>, BundleError<Db>> {
75        // Decode and validate the transactions in the bundle
76        let txs = self
77            .txs()
78            .iter()
79            .map(|tx| TxEnvelope::decode_2718(&mut tx.chunk()))
80            .collect::<Result<Vec<_>, _>>()
81            .map_err(|err| BundleError::TransactionDecodingError(err))?;
82
83        if txs.iter().any(|tx| tx.is_eip4844()) {
84            return Err(BundleError::UnsupportedTransactionType);
85        }
86
87        Ok(txs)
88    }
89
90    /// Check that this can be syntactically used as a fill.
91    pub fn validate_fills_offchain(&self, timestamp: u64) -> Result<(), SignedPermitError> {
92        if let Some(host_fills) = &self.host_fills {
93            host_fills.validate(timestamp)
94        } else {
95            Ok(())
96        }
97    }
98
99    /// Check that this fill is valid on-chain as of the current block. This
100    /// checks that the tokens can actually be transferred.
101    pub async fn alloy_validate_fills_onchain<Db, P, N>(
102        &self,
103        orders: HostOrdersInstance<P, N>,
104    ) -> Result<(), SignetEthBundleError<Db>>
105    where
106        Db: Database,
107        P: Provider<N>,
108        N: Network,
109    {
110        if let Some(host_fills) = self.host_fills.clone() {
111            orders.try_fill(host_fills.outputs, host_fills.permit).await.map_err(Into::into)
112        } else {
113            Ok(())
114        }
115    }
116}
117
118/// Response for `signet_sendBundle`.
119///
120/// This is based on the flashbots `eth_sendBundle` response. See [their docs].
121///
122/// [their docs]: https://docs.flashbots.net/flashbots-auction/advanced/rpc-endpoint
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
124#[serde(rename_all = "camelCase")]
125pub struct SignetEthBundleResponse {
126    /// The bundle hash of the sent bundle.
127    ///
128    /// This is calculated as keccak256(tx_hashes) where tx_hashes are the
129    /// concatenated transaction hashes.
130    pub bundle_hash: B256,
131}
132
133#[cfg(test)]
134mod test {
135    use super::*;
136    use alloy::primitives::{Address, U256};
137    use signet_zenith::HostOrders::{
138        Output, Permit2Batch, PermitBatchTransferFrom, TokenPermissions,
139    };
140
141    #[test]
142    fn send_bundle_ser_roundtrip() {
143        let bundle = SignetEthBundle {
144            bundle: EthSendBundle {
145                txs: vec![b"tx1".into(), b"tx2".into()],
146                block_number: 1,
147                min_timestamp: Some(2),
148                max_timestamp: Some(3),
149                reverting_tx_hashes: vec![B256::repeat_byte(4), B256::repeat_byte(5)],
150                replacement_uuid: Some("uuid".to_owned()),
151                ..Default::default()
152            },
153            host_fills: Some(SignedFill {
154                permit: Permit2Batch {
155                    permit: PermitBatchTransferFrom {
156                        permitted: vec![TokenPermissions {
157                            token: Address::repeat_byte(66),
158                            amount: U256::from(17),
159                        }],
160                        nonce: U256::from(18),
161                        deadline: U256::from(19),
162                    },
163                    owner: Address::repeat_byte(77),
164                    signature: Bytes::from(b"abcd"),
165                },
166                outputs: vec![Output {
167                    token: Address::repeat_byte(88),
168                    amount: U256::from(20),
169                    recipient: Address::repeat_byte(99),
170                    chainId: 100,
171                }],
172            }),
173        };
174
175        let serialized = serde_json::to_string(&bundle).unwrap();
176        let deserialized: SignetEthBundle = serde_json::from_str(&serialized).unwrap();
177
178        assert_eq!(bundle, deserialized);
179    }
180
181    #[test]
182    fn send_bundle_resp_ser_roundtrip() {
183        let resp = SignetEthBundleResponse { bundle_hash: B256::repeat_byte(1) };
184
185        let serialized = serde_json::to_string(&resp).unwrap();
186        let deserialized: SignetEthBundleResponse = serde_json::from_str(&serialized).unwrap();
187
188        assert_eq!(resp, deserialized);
189    }
190}