Skip to main content

foundry_cli/opts/tempo/
configurable_account.rs

1use super::TempoOpts;
2use alloy_eips::BlockId;
3use alloy_primitives::Address;
4use alloy_provider::Provider;
5use alloy_signer::Signer;
6use eyre::{Result, WrapErr};
7use foundry_common::{
8    provider::ProviderBuilder,
9    tempo::{
10        configurable_account::{
11            ConfigurableAccountOwnerKey, ConfigurableAccountSigner, detect_configurable_account,
12            linked_account, parse_config, stored_owner_keys,
13        },
14        resolve_tempo_sponsor_signer,
15    },
16};
17use foundry_config::Config;
18use foundry_wallets::{WalletOpts, WalletSigner, utils::maybe_get_keystore_path};
19use std::sync::Arc;
20use tempo_alloy::TempoNetwork;
21use tempo_primitives::transaction::ConfigurableAccountConfig;
22
23impl TempoOpts {
24    /// Returns whether the configurable account options select the sender.
25    pub const fn has_configurable_account_options(&self) -> bool {
26        self.configurable_account.is_some()
27            || self.configurable_access_key.is_some()
28            || self.configurable_account_config.is_some()
29            || !self.owners.is_empty()
30    }
31
32    /// Returns the configurable account linked to the keystore of `wallet` by `cast wallet new`,
33    /// and its owner key, unless `--from` or `--eoa` selects the key.
34    pub fn linked_account(&self, wallet: &WalletOpts) -> Result<Option<(Address, Address)>> {
35        if self.eoa || wallet.from.is_some() {
36            return Ok(None);
37        }
38        match maybe_get_keystore_path(
39            wallet.keystore_path.as_deref(),
40            wallet.keystore_account_name.as_deref(),
41        )? {
42            Some(path) => linked_account(&path),
43            None => Ok(None),
44        }
45    }
46
47    /// Resolves the `--tempo.owner` signers.
48    pub async fn owner_signers(&self) -> Result<Vec<WalletSigner>> {
49        let mut owners = Vec::with_capacity(self.owners.len());
50        for spec in &self.owners {
51            owners.push(Box::pin(resolve_tempo_sponsor_signer(spec)).await?);
52        }
53        Ok(owners)
54    }
55
56    /// Detects a configurable account sender and selects the local owners that sign for it,
57    /// taking `signer` when it is one of them.
58    ///
59    /// The sender is `--tempo.configurable-account`, else `--from`, else the account linked to
60    /// the signer's keystore (see [`Self::linked_account`]) when T14 is active, else the signer's
61    /// address. It is a configurable account when the chain says so (see
62    /// [`detect_configurable_account`]), or `--tempo.config` gives its configuration. Its owners
63    /// are taken from `signer`, `--tempo.owner` and the Tempo Accounts store. Fails with `hint`
64    /// when the local owners do not reach the threshold.
65    ///
66    /// With `--tempo.configurable-access-key`, that account signs as an access key of `--from`
67    /// instead (see [`ConfigurableAccountSigner::with_parent`]).
68    ///
69    /// Returns `None`, and leaves `signer` in place, for a sender that is not a configurable
70    /// account, and before T14.
71    pub async fn configurable_account_signer(
72        &self,
73        config: &Config,
74        wallet: &WalletOpts,
75        signer: &mut Option<WalletSigner>,
76        hint: &str,
77    ) -> Result<Option<ConfigurableAccountSigner>> {
78        let provider = ProviderBuilder::<TempoNetwork>::from_config(config)?.build()?;
79        let signers = signer.take().map(Arc::new).into_iter().collect::<Vec<_>>();
80        let linked = self.linked_account(wallet)?;
81        let owners = self
82            .configurable_account_owners(
83                &provider,
84                wallet.from,
85                linked,
86                &signers,
87                BlockId::latest(),
88            )
89            .await?;
90        let Some((account, config, keys)) = owners else {
91            // Only a configurable account keeps the signer.
92            *signer = signers.into_iter().next().and_then(Arc::into_inner);
93            return Ok(None);
94        };
95        let account = ConfigurableAccountSigner::new(account, config, keys, hint)?;
96        Ok(Some(match self.configurable_access_key.and(wallet.from) {
97            Some(parent) => account.with_parent(parent),
98            None => account,
99        }))
100    }
101
102    /// Detects a configurable account sender as [`Self::configurable_account_signer`] does, at
103    /// `block`, and returns the account, its configuration there and all its local owner keys,
104    /// which may not reach the threshold.
105    ///
106    /// With `--tempo.configurable-access-key`, the returned account is that access key, and
107    /// `from` is the account it signs for, which must be given.
108    pub async fn configurable_account_owners<P: Provider<TempoNetwork>>(
109        &self,
110        provider: &P,
111        from: Option<Address>,
112        linked: Option<(Address, Address)>,
113        signers: &[Arc<WalletSigner>],
114        block: BlockId,
115    ) -> Result<Option<(Address, ConfigurableAccountConfig, Vec<ConfigurableAccountOwnerKey>)>>
116    {
117        let from = match self.configurable_access_key {
118            Some(key) => {
119                let parent = from.ok_or_else(|| {
120                    eyre::eyre!(
121                        "--tempo.configurable-access-key needs the account it signs for: pass \
122                         --from"
123                    )
124                })?;
125                eyre::ensure!(parent != key, "a configurable account cannot be its own access key");
126                Some(key)
127            }
128            None => from,
129        };
130        if let (Some(account), Some(from)) = (self.configurable_account, from) {
131            eyre::ensure!(
132                account == from,
133                "--tempo.configurable-account {account} does not match the sender {from}"
134            );
135        }
136        let only_signer = match signers {
137            [signer] => Some(signer.address()),
138            _ => None,
139        };
140        let explicit = self.configurable_account.or(from);
141        // A linked account only replaces its own owner key as the implicit sender.
142        let linked = linked
143            .filter(|(_, owner)| explicit.is_none() && only_signer == Some(*owner))
144            .map(|(account, _)| account);
145        let Some(mut account) = explicit.or(only_signer) else {
146            eyre::ensure!(
147                !self.has_configurable_account_options(),
148                "configurable account options need a sender: pass --from or \
149                 --tempo.configurable-account"
150            );
151            return Ok(None);
152        };
153        let config = self.configurable_account_config.as_deref().map(parse_config).transpose()?;
154
155        let owners = self.owner_signers().await?.into_iter().map(Arc::new).collect::<Vec<_>>();
156        let keys = signers.iter().chain(&owners).map(|signer| signer.address()).collect::<Vec<_>>();
157        let required = self.has_configurable_account_options();
158        let mut detected = None;
159        if let Some(linked) = linked {
160            // Before T14 the linked account does not exist yet, and the key sends as before.
161            detected =
162                detect_configurable_account(provider, linked, &keys, config.clone(), false, block)
163                    .await
164                    .wrap_err_with(|| {
165                        format!(
166                            "could not check the configurable account {linked} linked to the \
167                         keystore; pass --from {account} or --eoa to send from the key"
168                        )
169                    })?;
170            if detected.is_some() {
171                account = linked;
172            }
173        }
174        if detected.is_none() {
175            detected =
176                detect_configurable_account(provider, account, &keys, config, required, block)
177                    .await?;
178        }
179        let Some(config) = detected else { return Ok(None) };
180
181        let chain_id = provider.get_chain_id().await?;
182        let keys = signers
183            .iter()
184            .chain(&owners)
185            .filter(|signer| config.owner_weight(signer.address()).is_some())
186            .map(|signer| ConfigurableAccountOwnerKey::Wallet(signer.clone()))
187            .chain(stored_owner_keys(chain_id, &config))
188            .collect();
189        Ok(Some((account, config, keys)))
190    }
191}