alloy_network/transaction/
builder.rs

1use super::signer::NetworkWallet;
2use crate::Network;
3use alloy_primitives::{Address, Bytes, ChainId, TxKind, U256};
4use alloy_rpc_types_eth::AccessList;
5use alloy_sol_types::SolCall;
6use futures_utils_wasm::impl_future;
7
8pub use alloy_network_primitives::{TransactionBuilder4844, TransactionBuilder7702};
9
10/// Result type for transaction builders
11pub type BuildResult<T, N> = Result<T, UnbuiltTransactionError<N>>;
12
13/// An unbuilt transaction, along with some error.
14#[derive(Debug, thiserror::Error)]
15#[error("Failed to build transaction: {error}")]
16pub struct UnbuiltTransactionError<N: Network> {
17    /// The original request that failed to build.
18    pub request: N::TransactionRequest,
19    /// The error that occurred.
20    #[source]
21    pub error: TransactionBuilderError<N>,
22}
23
24/// Error type for transaction builders.
25#[derive(Debug, thiserror::Error)]
26pub enum TransactionBuilderError<N: Network> {
27    /// Invalid transaction request
28    #[error("{0} transaction can't be built due to missing keys: {1:?}")]
29    InvalidTransactionRequest(N::TxType, Vec<&'static str>),
30
31    /// Signer cannot produce signature type required for transaction.
32    #[error("Signer cannot produce signature type required for transaction")]
33    UnsupportedSignatureType,
34
35    /// Signer error.
36    #[error(transparent)]
37    Signer(#[from] alloy_signer::Error),
38
39    /// A custom error.
40    #[error("{0}")]
41    Custom(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
42}
43
44impl<N: Network> TransactionBuilderError<N> {
45    /// Instantiate a custom error.
46    pub fn custom<E>(e: E) -> Self
47    where
48        E: std::error::Error + Send + Sync + 'static,
49    {
50        Self::Custom(Box::new(e))
51    }
52
53    /// Convert the error into an unbuilt transaction error.
54    pub const fn into_unbuilt(self, request: N::TransactionRequest) -> UnbuiltTransactionError<N> {
55        UnbuiltTransactionError { request, error: self }
56    }
57}
58
59/// A Transaction builder for a network.
60///
61/// Transaction builders are primarily used to construct typed transactions that can be signed with
62/// [`TransactionBuilder::build`], or unsigned typed transactions with
63/// [`TransactionBuilder::build_unsigned`].
64///
65/// Transaction builders should be able to construct all available transaction types on a given
66/// network.
67#[doc(alias = "TxBuilder")]
68pub trait TransactionBuilder<N: Network>: Default + Sized + Send + Sync + 'static {
69    /// Get the chain ID for the transaction.
70    fn chain_id(&self) -> Option<ChainId>;
71
72    /// Set the chain ID for the transaction.
73    fn set_chain_id(&mut self, chain_id: ChainId);
74
75    /// Builder-pattern method for setting the chain ID.
76    fn with_chain_id(mut self, chain_id: ChainId) -> Self {
77        self.set_chain_id(chain_id);
78        self
79    }
80
81    /// Get the nonce for the transaction.
82    fn nonce(&self) -> Option<u64>;
83
84    /// Set the nonce for the transaction.
85    fn set_nonce(&mut self, nonce: u64);
86
87    /// Builder-pattern method for setting the nonce.
88    fn with_nonce(mut self, nonce: u64) -> Self {
89        self.set_nonce(nonce);
90        self
91    }
92
93    /// Get the input data for the transaction.
94    fn input(&self) -> Option<&Bytes>;
95
96    /// Set the input data for the transaction.
97    fn set_input<T: Into<Bytes>>(&mut self, input: T);
98
99    /// Builder-pattern method for setting the input data.
100    fn with_input<T: Into<Bytes>>(mut self, input: T) -> Self {
101        self.set_input(input);
102        self
103    }
104
105    /// Get the sender for the transaction.
106    fn from(&self) -> Option<Address>;
107
108    /// Set the sender for the transaction.
109    fn set_from(&mut self, from: Address);
110
111    /// Builder-pattern method for setting the sender.
112    fn with_from(mut self, from: Address) -> Self {
113        self.set_from(from);
114        self
115    }
116
117    /// Get the kind of transaction.
118    fn kind(&self) -> Option<TxKind>;
119
120    /// Clear the kind of transaction.
121    fn clear_kind(&mut self);
122
123    /// Set the kind of transaction.
124    fn set_kind(&mut self, kind: TxKind);
125
126    /// Builder-pattern method for setting the kind of transaction.
127    fn with_kind(mut self, kind: TxKind) -> Self {
128        self.set_kind(kind);
129        self
130    }
131
132    /// Get the recipient for the transaction.
133    fn to(&self) -> Option<Address> {
134        if let Some(TxKind::Call(addr)) = self.kind() {
135            return Some(addr);
136        }
137        None
138    }
139
140    /// Set the recipient for the transaction.
141    fn set_to(&mut self, to: Address) {
142        self.set_kind(to.into());
143    }
144
145    /// Builder-pattern method for setting the recipient.
146    fn with_to(mut self, to: Address) -> Self {
147        self.set_to(to);
148        self
149    }
150
151    /// Set the `to` field to a create call.
152    fn set_create(&mut self) {
153        self.set_kind(TxKind::Create);
154    }
155
156    /// Set the `to` field to a create call.
157    fn into_create(mut self) -> Self {
158        self.set_create();
159        self
160    }
161
162    /// Deploy the code by making a create call with data. This will set the
163    /// `to` field to [`TxKind::Create`].
164    fn set_deploy_code<T: Into<Bytes>>(&mut self, code: T) {
165        self.set_input(code.into());
166        self.set_create()
167    }
168
169    /// Deploy the code by making a create call with data. This will set the
170    /// `to` field to [`TxKind::Create`].
171    fn with_deploy_code<T: Into<Bytes>>(mut self, code: T) -> Self {
172        self.set_deploy_code(code);
173        self
174    }
175
176    /// Set the data field to a contract call. This will clear the `to` field
177    /// if it is set to [`TxKind::Create`].
178    fn set_call<T: SolCall>(&mut self, t: &T) {
179        self.set_input(t.abi_encode());
180        if matches!(self.kind(), Some(TxKind::Create)) {
181            self.clear_kind();
182        }
183    }
184
185    /// Make a contract call with data.
186    fn with_call<T: SolCall>(mut self, t: &T) -> Self {
187        self.set_call(t);
188        self
189    }
190
191    /// Calculates the address that will be created by the transaction, if any.
192    ///
193    /// Returns `None` if the transaction is not a contract creation (the `to` field is set), or if
194    /// the `from` or `nonce` fields are not set.
195    fn calculate_create_address(&self) -> Option<Address> {
196        if !self.kind().is_some_and(|to| to.is_create()) {
197            return None;
198        }
199        let from = self.from()?;
200        let nonce = self.nonce()?;
201        Some(from.create(nonce))
202    }
203
204    /// Get the value for the transaction.
205    fn value(&self) -> Option<U256>;
206
207    /// Set the value for the transaction.
208    fn set_value(&mut self, value: U256);
209
210    /// Builder-pattern method for setting the value.
211    fn with_value(mut self, value: U256) -> Self {
212        self.set_value(value);
213        self
214    }
215
216    /// Get the legacy gas price for the transaction.
217    fn gas_price(&self) -> Option<u128>;
218
219    /// Set the legacy gas price for the transaction.
220    fn set_gas_price(&mut self, gas_price: u128);
221
222    /// Builder-pattern method for setting the legacy gas price.
223    fn with_gas_price(mut self, gas_price: u128) -> Self {
224        self.set_gas_price(gas_price);
225        self
226    }
227
228    /// Get the max fee per gas for the transaction.
229    fn max_fee_per_gas(&self) -> Option<u128>;
230
231    /// Set the max fee per gas  for the transaction.
232    fn set_max_fee_per_gas(&mut self, max_fee_per_gas: u128);
233
234    /// Builder-pattern method for setting max fee per gas .
235    fn with_max_fee_per_gas(mut self, max_fee_per_gas: u128) -> Self {
236        self.set_max_fee_per_gas(max_fee_per_gas);
237        self
238    }
239
240    /// Get the max priority fee per gas for the transaction.
241    fn max_priority_fee_per_gas(&self) -> Option<u128>;
242
243    /// Set the max priority fee per gas for the transaction.
244    fn set_max_priority_fee_per_gas(&mut self, max_priority_fee_per_gas: u128);
245
246    /// Builder-pattern method for setting max priority fee per gas.
247    fn with_max_priority_fee_per_gas(mut self, max_priority_fee_per_gas: u128) -> Self {
248        self.set_max_priority_fee_per_gas(max_priority_fee_per_gas);
249        self
250    }
251    /// Get the gas limit for the transaction.
252    fn gas_limit(&self) -> Option<u64>;
253
254    /// Set the gas limit for the transaction.
255    fn set_gas_limit(&mut self, gas_limit: u64);
256
257    /// Builder-pattern method for setting the gas limit.
258    fn with_gas_limit(mut self, gas_limit: u64) -> Self {
259        self.set_gas_limit(gas_limit);
260        self
261    }
262
263    /// Get the EIP-2930 access list for the transaction.
264    fn access_list(&self) -> Option<&AccessList>;
265
266    /// Sets the EIP-2930 access list.
267    fn set_access_list(&mut self, access_list: AccessList);
268
269    /// Builder-pattern method for setting the access list.
270    fn with_access_list(mut self, access_list: AccessList) -> Self {
271        self.set_access_list(access_list);
272        self
273    }
274
275    /// Check if all necessary keys are present to build the specified type,
276    /// returning a list of missing keys.
277    fn complete_type(&self, ty: N::TxType) -> Result<(), Vec<&'static str>>;
278
279    /// Check if all necessary keys are present to build the currently-preferred
280    /// transaction type, returning a list of missing keys.
281    fn complete_preferred(&self) -> Result<(), Vec<&'static str>> {
282        self.complete_type(self.output_tx_type())
283    }
284
285    /// Assert that the builder prefers a certain transaction type. This does
286    /// not indicate that the builder is ready to build. This function uses a
287    /// `dbg_assert_eq!` to check the builder status, and will have no affect
288    /// in release builds.
289    fn assert_preferred(&self, ty: N::TxType) {
290        debug_assert_eq!(self.output_tx_type(), ty);
291    }
292
293    /// Assert that the builder prefers a certain transaction type. This does
294    /// not indicate that the builder is ready to build. This function uses a
295    /// `dbg_assert_eq!` to check the builder status, and will have no affect
296    /// in release builds.
297    fn assert_preferred_chained(self, ty: N::TxType) -> Self {
298        self.assert_preferred(ty);
299        self
300    }
301
302    /// Apply a function to the builder, returning the modified builder.
303    fn apply<F>(self, f: F) -> Self
304    where
305        F: FnOnce(Self) -> Self,
306    {
307        f(self)
308    }
309
310    /// Apply a fallible function to the builder, returning the modified builder or an error.
311    fn try_apply<F, E>(self, f: F) -> Result<Self, E>
312    where
313        F: FnOnce(Self) -> Result<Self, E>,
314    {
315        f(self)
316    }
317
318    /// True if the builder contains all necessary information to be submitted
319    /// to the `eth_sendTransaction` endpoint.
320    fn can_submit(&self) -> bool;
321
322    /// True if the builder contains all necessary information to be built into
323    /// a valid transaction.
324    fn can_build(&self) -> bool;
325
326    /// Returns the transaction type that this builder will attempt to build.
327    /// This does not imply that the builder is ready to build.
328    #[doc(alias = "output_transaction_type")]
329    fn output_tx_type(&self) -> N::TxType;
330
331    /// Returns the transaction type that this builder will build. `None` if
332    /// the builder is not ready to build.
333    #[doc(alias = "output_transaction_type_checked")]
334    fn output_tx_type_checked(&self) -> Option<N::TxType>;
335
336    /// Trim any conflicting keys and populate any computed fields (like blob
337    /// hashes).
338    ///
339    /// This is useful for transaction requests that have multiple conflicting
340    /// fields. While these may be buildable, they may not be submitted to the
341    /// RPC. This method should be called before RPC submission, but is not
342    /// necessary before building.
343    fn prep_for_submission(&mut self);
344
345    /// Build an unsigned, but typed, transaction.
346    fn build_unsigned(self) -> BuildResult<N::UnsignedTx, N>;
347
348    /// Build a signed transaction.
349    fn build<W: NetworkWallet<N>>(
350        self,
351        wallet: &W,
352    ) -> impl_future!(<Output = Result<N::TxEnvelope, TransactionBuilderError<N>>>);
353}