Skip to main content

cast/cmd/
configurable_key_auth.rs

1//! Tempo access keys authorized by a configurable account's owners (T14, TIP-1111).
2//!
3//! `cast keychain authorize` sends `authorizeKey` from the account in a `0x05` transaction.
4//! `cast key-authorization sign` signs an inline key authorization: the owners approve
5//! `configurable_account_digest(authorization.signature_hash(), account, version)`, and their
6//! approvals form its `0x05` signature. The account's configuration is read from the chain, as
7//! `cast wallet` does.
8
9use crate::{
10    cmd::{
11        auth::confirm_and_build,
12        send::{SendOptions, cast_send_with_configurable_account},
13    },
14    tempo::{apply_fee_payment, print_expires, resolve_configurable_account, tempo_provider},
15    tx::{CastTxBuilder, SendTxOpts, apply_poll_interval},
16};
17use alloy_ens::NameOrAddress;
18use alloy_primitives::{Address, hex};
19use alloy_provider::Provider;
20use alloy_signer::Signer;
21use clap::Args;
22use eyre::{Result, WrapErr};
23use foundry_cli::{
24    opts::TransactionOpts,
25    utils::{LoadConfig, resolve_lane},
26};
27use foundry_common::tempo::configurable_account::{
28    combine_approvals, current_config, parse_owner_signature,
29};
30use foundry_wallets::WalletSigner;
31use tempo_alloy::TempoNetwork;
32use tempo_contracts::precompiles::ACCOUNT_KEYCHAIN_ADDRESS;
33use tempo_primitives::transaction::{
34    KeyAuthorization, PrimitiveSignature, SignedKeyAuthorization, configurable_account_digest,
35};
36
37/// Sign a key authorization as a Tempo configurable account's owners (T14, TIP-1111).
38#[derive(Clone, Debug, Args)]
39#[command(next_help_heading = "Configurable account (T14)")]
40pub struct ConfigurableAccountArgs {
41    /// Sign as this configurable account, whose current configuration is read from the RPC.
42    ///
43    /// The authorization is bound to the account and stays valid only while the configuration
44    /// does not change. The wallet signer approves as one owner; `--tempo.owner-signature` adds
45    /// approvals made elsewhere. The account's own `0x05` transaction or the authorized key's
46    /// first transaction can carry it.
47    #[arg(long = "tempo.configurable-account", value_name = "ADDRESS")]
48    configurable_account: Option<Address>,
49
50    /// An owner approval made elsewhere: a hex Tempo primitive signature, a JSON signature or a
51    /// WebAuthn assertion, or a file holding one. Owners sign the owner digest with
52    /// `cast wallet sign --no-hash <DIGEST>`. Repeat for several owners.
53    #[arg(
54        long = "tempo.owner-signature",
55        value_name = "SIGNATURE",
56        value_parser = parse_owner_signature,
57        requires = "configurable_account"
58    )]
59    owner_signatures: Vec<PrimitiveSignature>,
60}
61
62impl ConfigurableAccountArgs {
63    /// The configurable account whose owners sign, if any.
64    pub const fn account(&self) -> Option<Address> {
65        self.configurable_account
66    }
67
68    /// Signs `authorization`, bound to `account`, with the approvals of `owner` and
69    /// `--tempo.owner-signature`.
70    pub async fn sign(
71        &self,
72        rpc: &impl LoadConfig,
73        account: Address,
74        owner: Option<&WalletSigner>,
75        authorization: KeyAuthorization,
76    ) -> Result<SignedKeyAuthorization> {
77        let (_, provider) = tempo_provider(rpc)?;
78        let chain_id = provider.get_chain_id().await?;
79        eyre::ensure!(
80            chain_id == authorization.chain_id,
81            "--chain-id {} does not match the RPC's chain {chain_id}, where the configuration \
82             of {account} is read",
83            authorization.chain_id
84        );
85        let inner = authorization.signature_hash();
86
87        // A 1-of-1, salt-0 account is recomputed from an owner's key before it registers.
88        let initial = configurable_account_digest(inner, account, 0);
89        let mut keys = self
90            .owner_signatures
91            .iter()
92            .filter_map(|approval| approval.recover_signer(&initial).ok())
93            .collect::<Vec<_>>();
94        keys.extend(owner.map(Signer::address));
95        let config = current_config(&provider, account, &keys).await?.ok_or_else(|| {
96            eyre::eyre!(
97                "{account} is not a registered configurable account, and no owner key derives it"
98            )
99        })?;
100
101        let digest = configurable_account_digest(inner, account, config.version);
102        let mut approvals = self.owner_signatures.clone();
103        if let Some(owner) = owner {
104            approvals.push(PrimitiveSignature::Secp256k1(owner.sign_hash(&digest).await?));
105        }
106        let signature =
107            combine_approvals(account, &config, inner, approvals).wrap_err_with(|| {
108                format!(
109                    "other owners sign the owner digest with `cast wallet sign --no-hash \
110                     {digest}`; pass their signatures with --tempo.owner-signature"
111                )
112            })?;
113        Ok(authorization.into_signed(signature))
114    }
115}
116
117/// Sends `calldata` to the AccountKeychain precompile from the configurable account that
118/// `--tempo.configurable-account` names, in a `0x05` transaction that its local owners approve
119/// (T14): the wallet signer, `--tempo.owner` and the Tempo Accounts store, as `cast send` does.
120pub(crate) async fn send_keychain_tx_as_configurable_account(
121    calldata: Vec<u8>,
122    mut tx: TransactionOpts,
123    send_tx: &SendTxOpts,
124    force: bool,
125) -> Result<()> {
126    eyre::ensure!(
127        tx.tempo.sponsor_url.is_none() && !tx.tempo.print_sponsor_hash,
128        "--sponsor-url and --tempo.print-sponsor-hash are not supported for configurable accounts"
129    );
130    eyre::ensure!(
131        tx.tempo.configurable_access_key.is_none(),
132        "an access key cannot manage the keys of the account it signs for"
133    );
134    eyre::ensure!(
135        !send_tx.browser.browser,
136        "browser wallets cannot approve as a configurable account owner"
137    );
138    eyre::ensure!(
139        tx.tempo.session_id()?.is_none(),
140        "configurable account owners approve with their own keys; Tempo Accounts sessions cannot \
141         sign for them"
142    );
143    let (config, provider) = tempo_provider(&send_tx.eth)?;
144    apply_poll_interval(&provider, send_tx.poll_interval);
145
146    // `--from` may name the account, so the wallet's own key is resolved without it.
147    let mut key_wallet = send_tx.eth.wallet.clone();
148    key_wallet.from = None;
149    let (mut signer, access_key) = foundry_common::tempo::maybe_signer(&key_wallet, None).await?;
150    eyre::ensure!(
151        access_key.is_none(),
152        "configurable account owners approve with their own keys, not a Tempo access key"
153    );
154    let account = resolve_configurable_account::<TempoNetwork>(
155        &tx.tempo,
156        &config,
157        &send_tx.eth.wallet,
158        &mut signer,
159    )
160    .await?
161    .ok_or_else(|| eyre::eyre!("the sender is not a Tempo configurable account"))?;
162
163    let print_expires_at = tx.tempo.resolve_expires();
164    let tempo_sponsor = tx.tempo.sponsor_config().await?;
165    let resolved_lane = resolve_lane(&mut tx.tempo, &config.root)?;
166    let mut builder = CastTxBuilder::new(&provider, tx, &config)
167        .await?
168        .with_to(Some(NameOrAddress::Address(ACCOUNT_KEYCHAIN_ADDRESS)))
169        .await?
170        .with_code_sig_and_args(None, Some(hex::encode_prefixed(&calldata)), vec![])
171        .await?;
172    account.prepare_request::<TempoNetwork>(builder.tx_mut());
173    let Some(mut request) =
174        confirm_and_build(builder, account.account(), force, resolved_lane.as_ref(), false).await?
175    else {
176        return Ok(());
177    };
178    print_expires(print_expires_at)?;
179    apply_fee_payment::<TempoNetwork, _>(
180        tempo_sponsor.as_ref(),
181        Some(&provider),
182        &mut request,
183        account.account(),
184    )
185    .await?;
186    cast_send_with_configurable_account(
187        &provider,
188        request,
189        &account,
190        &SendOptions::new(send_tx, &config),
191    )
192    .await?;
193    Ok(())
194}