Skip to main content

cast/
tempo.rs

1//! Tempo transaction helpers used by Cast-facing commands.
2
3use crate::tx::fill_transaction_gas_fees;
4use alloy_network::{Ethereum, Network, TransactionBuilder};
5use alloy_primitives::{Address, B256};
6use alloy_provider::Provider;
7use alloy_rpc_client::BuiltInConnectionString;
8use alloy_rpc_types::BlockId;
9use alloy_transport::{BoxTransport, TransportConnect, TransportError};
10use eyre::Result;
11use foundry_cli::{
12    json::print_json_success,
13    opts::{EthereumOpts, TempoOpts},
14    utils::{LoadConfig, get_chain},
15};
16use foundry_common::{
17    FoundryTransactionBuilder,
18    provider::{ProviderBuilder, RetryProvider},
19    shell,
20    tempo::{
21        configurable_account::{ConfigurableAccountSigner, simulation_spec},
22        is_tempo_hardfork_active, maybe_print_fee_token, resolve_and_set_fee_token,
23    },
24};
25use foundry_config::{Chain, Config, Eip1559FeeEstimatePreset};
26use foundry_evm_networks::NetworkVariant;
27use foundry_wallets::{WalletOpts, WalletSigner};
28use serde_json::Value;
29use std::{str::FromStr, sync::Arc};
30use tempo_alloy::{
31    TempoNetwork,
32    accounts::TempoAccountsWallet,
33    chainspec::hardfork::TempoHardfork,
34    rpc::{ConfigurableAccountSimulationSpec, TempoTransactionRequest},
35    transport::{RelayConnector, SponsorshipMode},
36};
37
38pub use foundry_common::tempo::TempoSponsor;
39
40/// Loads the config for `opts` and builds a Tempo provider from it.
41pub(crate) fn tempo_provider(
42    opts: &impl LoadConfig,
43) -> Result<(Config, RetryProvider<TempoNetwork>)> {
44    let config = opts.load_config()?;
45    let provider = ProviderBuilder::<TempoNetwork>::from_config(&config)?.build()?;
46    Ok((config, provider))
47}
48
49/// Attaches the fee payment to a built transaction: the sponsor signature when a sponsor is
50/// configured, otherwise the resolved fee token for `payer` (printing it when it was resolved).
51pub(crate) async fn apply_fee_payment<N, P>(
52    sponsor: Option<&TempoSponsor>,
53    provider: Option<&P>,
54    tx: &mut N::TransactionRequest,
55    payer: Address,
56) -> Result<()>
57where
58    N: Network,
59    N::TransactionRequest: FoundryTransactionBuilder<N>,
60    P: Provider<N>,
61{
62    if tx.gas_price().is_some() {
63        eyre::ensure!(
64            sponsor.is_none() && !tx.is_tempo_aa(),
65            "Tempo transaction options cannot be combined with a legacy transaction"
66        );
67        return Ok(());
68    }
69
70    if sponsor.is_some() {
71        maybe_attach_sponsor(sponsor, provider, tx, payer).await
72    } else {
73        resolve_and_print_fee_token(provider, tx, Some(payer)).await
74    }
75}
76
77/// Resolves the sponsored fee token and attaches the sponsor signature preview for `payer` when a
78/// sponsor is configured.
79pub(crate) async fn maybe_attach_sponsor<N, P>(
80    sponsor: Option<&TempoSponsor>,
81    provider: Option<&P>,
82    tx: &mut N::TransactionRequest,
83    payer: Address,
84) -> Result<()>
85where
86    N: Network,
87    N::TransactionRequest: FoundryTransactionBuilder<N>,
88    P: Provider<N>,
89{
90    if let Some(sponsor) = sponsor {
91        let provider = provider.map(|p| p as &dyn Provider<N>);
92        sponsor.resolve_and_set_fee_token(provider, tx).await?;
93        sponsor.attach_and_print::<N>(tx, payer).await?;
94    }
95    Ok(())
96}
97
98/// Resolves and sets the fee token paid by `fee_payer`, printing it when it was resolved.
99pub(crate) async fn resolve_and_print_fee_token<N, P>(
100    provider: Option<&P>,
101    tx: &mut N::TransactionRequest,
102    fee_payer: Option<Address>,
103) -> Result<()>
104where
105    N: Network,
106    N::TransactionRequest: FoundryTransactionBuilder<N>,
107    P: Provider<N>,
108{
109    let dyn_provider = provider.map(|p| p as &dyn Provider<N>);
110    let fee_token = resolve_and_set_fee_token(dyn_provider, tx, fee_payer).await?;
111    maybe_print_fee_token(provider, fee_token).await
112}
113
114/// Computes the sponsor hash of a built transaction, resolving the fee token for `fee_payer` first
115/// when one is configured. Used by `--tempo.print-sponsor-hash`.
116pub(crate) async fn sponsor_hash<N, P>(
117    provider: Option<&P>,
118    tx: &mut N::TransactionRequest,
119    from: Address,
120    fee_payer: Option<Address>,
121) -> Result<B256>
122where
123    N: Network,
124    N::TransactionRequest: FoundryTransactionBuilder<N>,
125    P: Provider<N>,
126{
127    if fee_payer.is_some() {
128        let provider = provider.map(|p| p as &dyn Provider<N>);
129        resolve_and_set_fee_token(provider, tx, fee_payer).await?;
130    }
131    tx.compute_sponsor_hash(from)
132        .ok_or_else(|| eyre::eyre!("This network does not support sponsored transactions"))
133}
134
135/// Prints a command result: the raw payload in JSON mode, the human rendering otherwise.
136pub(crate) fn print_payload<F>(payload: Value, human: F) -> Result<()>
137where
138    F: FnOnce(&Value) -> Result<()>,
139{
140    if shell::is_json() {
141        print_json_success(payload)?;
142    } else {
143        human(&payload)?;
144    }
145    Ok(())
146}
147
148pub(crate) fn print_expires(expires_at: Option<u64>) -> Result<()> {
149    if let Some(ts) = expires_at {
150        sh_status!("Transaction expires at unix timestamp {ts}")?;
151    }
152    Ok(())
153}
154
155/// Resolves a command signer, preferring an explicitly selected Tempo session.
156///
157/// Session resolution is fail-closed: when `--tempo.session` or `TEMPO_SESSION_ID` is set, wallet
158/// signer options are rejected by [`TempoOpts::session_signer_for_wallet`] instead of falling back
159/// to a long-lived signer.
160pub(crate) async fn resolve_session_or_wallet_signer(
161    tempo: &TempoOpts,
162    wallet: &WalletOpts,
163    chain_id: u64,
164) -> Result<(Option<WalletSigner>, Option<TempoAccountsWallet>)> {
165    // `--from` names the parent of a configurable access key, whose own access key in the Tempo
166    // Accounts store must not sign instead.
167    let mut store_wallet = wallet.clone();
168    if tempo.configurable_access_key.is_some() {
169        store_wallet.from = None;
170    }
171    let (signer, access_key) = match tempo.session_signer_for_wallet(wallet, chain_id)? {
172        Some(session) => (None, Some(session.access_key)),
173        None => foundry_common::tempo::maybe_signer(&store_wallet, Some(chain_id)).await?,
174    };
175    if let (Some(from), Some(access_key)) = (wallet.from, &access_key) {
176        eyre::ensure!(
177            access_key.account() == from,
178            "sender {from} does not match Tempo account {}",
179            access_key.account()
180        );
181    }
182    Ok((signer, access_key))
183}
184
185pub(crate) fn ensure_session_not_browser(tempo: &TempoOpts, browser: bool) -> Result<()> {
186    if browser && tempo.session_id()?.is_some() {
187        eyre::bail!("--tempo.session/TEMPO_SESSION_ID cannot be combined with --browser");
188    }
189    Ok(())
190}
191
192/// Fails with `message` unless `hardfork` is active on the RPC.
193pub(crate) async fn require_hardfork<P: Provider<TempoNetwork>>(
194    provider: &P,
195    hardfork: TempoHardfork,
196    message: &str,
197) -> Result<()> {
198    if !is_tempo_hardfork_active(provider, hardfork).await? {
199        eyre::bail!("{message}");
200    }
201    Ok(())
202}
203
204/// Fails early with `requirement` when a Tempo precompile is not active yet: a pre-fork call
205/// would succeed as a silent no-op instead of reverting. Prefers the hardfork query and falls
206/// back to checking the precompile's code when the RPC lacks the method.
207pub(crate) async fn ensure_tempo_precompile_active<P: Provider<TempoNetwork>>(
208    provider: &P,
209    hardfork: TempoHardfork,
210    precompile: Address,
211    requirement: &str,
212) -> Result<()> {
213    let active = match is_tempo_hardfork_active(provider, hardfork).await {
214        Ok(active) => active,
215        Err(_) => !provider.get_code_at(precompile).await?.is_empty(),
216    };
217    eyre::ensure!(active, "{requirement}");
218    Ok(())
219}
220
221/// Connector for reusing an already-configured RPC transport.
222///
223/// This preserves Foundry transport behavior such as MPP payment handling when a sponsor relay is
224/// layered over the default RPC.
225#[derive(Clone, Debug)]
226pub(crate) struct ExistingTransportConnector {
227    transport: BoxTransport,
228    is_local: bool,
229}
230
231impl TransportConnect for ExistingTransportConnector {
232    fn is_local(&self) -> bool {
233        self.is_local
234    }
235
236    async fn get_transport(&self) -> Result<BoxTransport, TransportError> {
237        Ok(self.transport.clone())
238    }
239}
240
241pub(crate) fn sponsor_relay_connector<N: Network>(
242    provider: &impl Provider<N>,
243    sponsor_url: &str,
244) -> Result<RelayConnector<ExistingTransportConnector, BuiltInConnectionString>> {
245    let default = ExistingTransportConnector {
246        transport: provider.client().transport().clone(),
247        is_local: provider.client().is_local(),
248    };
249    let relay = BuiltInConnectionString::from_str(sponsor_url)?;
250    Ok(RelayConnector::with_config(default, relay, SponsorshipMode::SignOnly, false))
251}
252
253/// Resolves the transaction network and any configured signer without letting an unrelated Tempo
254/// Accounts store change ordinary Ethereum commands.
255///
256/// Explicit signer options are resolved with `from` cleared so the store fallback is not consulted.
257/// The fallback is only enabled after selecting Tempo from transaction options, configuration,
258/// or the RPC chain.
259pub(crate) async fn resolve_transaction_network_and_signer(
260    tempo: &TempoOpts,
261    eth: &EthereumOpts,
262) -> Result<(NetworkVariant, Option<WalletSigner>, Option<TempoAccountsWallet>)> {
263    let config = eth.load_config()?;
264    resolve_transaction_network_and_signer_with_config(tempo, eth, &config).await
265}
266
267/// Resolves the transaction network and signer using an already loaded configuration.
268pub(crate) async fn resolve_transaction_network_and_signer_with_config(
269    tempo: &TempoOpts,
270    eth: &EthereumOpts,
271    config: &Config,
272) -> Result<(NetworkVariant, Option<WalletSigner>, Option<TempoAccountsWallet>)> {
273    let has_session = tempo.session_id()?.is_some();
274    let requires_tempo = tempo.is_tempo() || has_session;
275    crate::cmd::validate_tempo_network(config, requires_tempo)?;
276    if has_session {
277        return Ok((NetworkVariant::Tempo, None, None));
278    }
279
280    let mut explicit_wallet = eth.wallet.clone();
281    explicit_wallet.from = None;
282    let (signer, access_key) = foundry_common::tempo::maybe_signer(&explicit_wallet, None).await?;
283    let network =
284        crate::cmd::resolve_transaction_network(config, requires_tempo || access_key.is_some())
285            .await?;
286    if let (Some(from), Some(access_key)) = (eth.wallet.from, &access_key) {
287        eyre::ensure!(
288            access_key.account() == from,
289            "sender {from} does not match Tempo account {}",
290            access_key.account()
291        );
292    }
293    // `--from` names the parent of a configurable access key, which signs instead of its keys.
294    if !network.is_tempo()
295        || signer.is_some()
296        || access_key.is_some()
297        || eth.wallet.from.is_none()
298        || tempo.configurable_access_key.is_some()
299    {
300        return Ok((network, signer, access_key));
301    }
302
303    // Only consult the Accounts store after selecting Tempo.
304    let provider = ProviderBuilder::<Ethereum>::from_config(config)?.build()?;
305    let chain = get_chain(config.chain, &provider).await?;
306    let (signer, access_key) =
307        foundry_common::tempo::maybe_signer(&eth.wallet, Some(chain.id())).await?;
308    if let Some(access_key) = &access_key {
309        let from = eth.wallet.from.expect("checked above");
310        eyre::ensure!(
311            access_key.account() == from,
312            "sender {from} does not match active Tempo account {}",
313            access_key.account()
314        );
315    }
316    Ok((network, signer, access_key))
317}
318
319/// How a Cast command tells the owners of a configurable account that are not local how to sign.
320const CAST_OWNERS_HINT: &str = "Pass the other owner keys with --tempo.owner, or have each owner \
321     sign the digest from `cast mktx --raw-unsigned --tempo.digest` with \
322     `cast wallet sign --no-hash` and combine the signatures with `cast wallet assemble`.";
323
324/// How a Cast command tells the owners of a configurable account that are not local how to sign
325/// when its signature cannot be assembled from signatures made elsewhere: for a configurable
326/// access key's keychain signature, and for zone commands.
327pub(crate) const CAST_LOCAL_OWNERS_HINT: &str =
328    "Pass the other owner keys with --tempo.owner, or keep them in the Tempo Accounts store.";
329
330/// Detects a Tempo configurable account sender and selects its local owners, taking `signer` when
331/// it is one of them.
332///
333/// The sender is `--tempo.configurable-account`, `--from`, the account linked to the signer's
334/// keystore when T14 is active, or the signer's address. Detection only runs on Tempo, and not in
335/// `--curl` mode, whose transport answers with placeholders.
336pub(crate) async fn resolve_configurable_account<N: Network>(
337    tempo: &TempoOpts,
338    config: &Config,
339    wallet: &WalletOpts,
340    signer: &mut Option<WalletSigner>,
341) -> Result<Option<ConfigurableAccountSigner>>
342where
343    N::TransactionRequest: FoundryTransactionBuilder<N>,
344{
345    // Only Tempo requests carry a fee token.
346    let is_tempo = N::TransactionRequest::default().supports_fee_token();
347    if !is_tempo || (config.eth_rpc_curl && !tempo.has_configurable_account_options()) {
348        eyre::ensure!(
349            !tempo.has_configurable_account_options(),
350            "Tempo configurable accounts require a Tempo network and an RPC"
351        );
352        return Ok(None);
353    }
354    let hint = if tempo.configurable_access_key.is_some() {
355        CAST_LOCAL_OWNERS_HINT
356    } else {
357        CAST_OWNERS_HINT
358    };
359    let account = tempo.configurable_account_signer(config, wallet, signer, hint).await?;
360    if let Some(account) = &account {
361        if account.sender() == account.account() {
362            sh_status!("Sending as Tempo configurable account {}", account.account())?;
363        } else {
364            sh_status!(
365                "Sending as {} with Tempo configurable access key {}",
366                account.sender(),
367                account.account()
368            )?;
369        }
370    }
371    Ok(account)
372}
373
374/// Returns the Tempo configurable account that sends for `sender`, which is `sender` itself or the
375/// account linked to its keystore, with the owner quorum that gas estimation models: the local
376/// owners when they reach the threshold, as `cast send` signs, otherwise the largest quorum of
377/// maximum-size `WebAuthn` approvals. `signer` is the wallet signer the sender already resolved,
378/// and the account's configuration is read at `block`, where the estimate runs.
379pub(crate) async fn configurable_account_simulation<N: Network>(
380    tempo: &TempoOpts,
381    config: &Config,
382    wallet: &WalletOpts,
383    sender: Address,
384    signer: Option<Arc<WalletSigner>>,
385    block: BlockId,
386) -> Result<Option<(Address, ConfigurableAccountSimulationSpec)>>
387where
388    N::TransactionRequest: FoundryTransactionBuilder<N>,
389{
390    let is_tempo = N::TransactionRequest::default().supports_fee_token();
391    if !is_tempo || (config.eth_rpc_curl && !tempo.has_configurable_account_options()) {
392        eyre::ensure!(
393            !tempo.has_configurable_account_options(),
394            "Tempo configurable accounts require a Tempo network and an RPC"
395        );
396        return Ok(None);
397    }
398    let provider = ProviderBuilder::<TempoNetwork>::from_config(config)?.build()?;
399    // The sender resolves the signer unless `--from` names it, so that a keystore or hardware
400    // wallet is unlocked once.
401    let signer = match signer {
402        Some(signer) => Some(signer),
403        None if wallet.from.is_some() => {
404            let mut explicit_wallet = wallet.clone();
405            explicit_wallet.from = None;
406            explicit_wallet.maybe_signer().await?.0.map(Arc::new)
407        }
408        None => None,
409    };
410    let signers = signer.into_iter().collect::<Vec<_>>();
411    // A sender that is the linked keystore's own key was not named with `--from`.
412    let linked = tempo.linked_account(wallet)?;
413    let from = if tempo.configurable_access_key.is_some() {
414        // A configurable access key signs for the account `--from` names, never for its owner.
415        wallet.from
416    } else {
417        (!linked.is_some_and(|(_, owner)| owner == sender)).then_some(sender)
418    };
419    let Some((account, config, keys)) =
420        tempo.configurable_account_owners(&provider, from, linked, &signers, block).await?
421    else {
422        return Ok(None);
423    };
424    let spec = match ConfigurableAccountSigner::new(account, config.clone(), keys, "") {
425        Ok(signer) => signer.simulation_spec(),
426        Err(_) => simulation_spec(account, &config, &[]),
427    };
428    Ok(Some((account, spec)))
429}
430
431/// Fills a Tempo transaction request that was built outside [`crate::tx::CastTxBuilder`] before
432/// access-key signing.
433pub(crate) async fn fill_access_key_transaction<P>(
434    provider: &P,
435    tx: &mut TempoTransactionRequest,
436    access_key: &TempoAccountsWallet,
437    chain: Chain,
438    eip1559_fee_estimate: Eip1559FeeEstimatePreset,
439) -> Result<TempoAccountsWallet>
440where
441    P: Provider<TempoNetwork>,
442{
443    tx.set_chain_id(chain.id());
444    let prepared = access_key.prepare_request(provider, tx).await?;
445
446    if tx.nonce().is_none() {
447        tx.set_nonce(provider.get_transaction_count(prepared.account()).await?);
448    }
449    fill_transaction_gas_fees(provider, tx, chain.is_legacy(), false, eip1559_fee_estimate).await?;
450    if tx.gas_limit().is_none() {
451        tx.set_gas_limit(provider.estimate_gas(tx.clone()).await?);
452    }
453
454    Ok(prepared)
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460    use alloy_provider::{ProviderBuilder as AlloyProviderBuilder, mock::Asserter};
461    use alloy_rpc_client::RpcClient;
462
463    #[tokio::test]
464    async fn legacy_fee_payment_skips_stored_token_and_rejects_tempo_fields() {
465        let asserter = Asserter::new();
466        let provider =
467            AlloyProviderBuilder::new().network::<TempoNetwork>().connect_mocked_client(asserter);
468        let payer = Address::repeat_byte(0x11);
469        let mut tx = TempoTransactionRequest::default();
470        tx.set_gas_price(1);
471
472        apply_fee_payment(None, Some(&provider), &mut tx, payer).await.unwrap();
473        assert!(tx.fee_token().is_none());
474
475        tx.set_fee_token(Address::repeat_byte(0x22));
476        assert_eq!(
477            apply_fee_payment(None, Some(&provider), &mut tx, payer).await.unwrap_err().to_string(),
478            "Tempo transaction options cannot be combined with a legacy transaction"
479        );
480    }
481
482    #[tokio::test]
483    async fn sponsor_relay_reuses_existing_default_transport() {
484        let asserter = Asserter::new();
485        asserter.push_success(&alloy_primitives::U64::from(42));
486        let provider = AlloyProviderBuilder::new().connect_mocked_client(asserter);
487        let connector =
488            sponsor_relay_connector(&provider, "http://127.0.0.1:1").expect("valid relay");
489        let transport = connector.get_transport().await.expect("relay transport");
490        let client = RpcClient::builder().transport(transport, true);
491        let relayed = AlloyProviderBuilder::new().connect_client(client);
492
493        assert_eq!(relayed.get_block_number().await.unwrap(), 42);
494    }
495}