Skip to main content

cast/cmd/
keychain.rs

1use crate::{
2    cmd::{
3        auth::confirm_and_build,
4        configurable_key_auth::{
5            ConfigurableAccountArgs, send_keychain_tx_as_configurable_account,
6        },
7        print_json_or,
8        send::{SendOptions, cast_send},
9        tempo_policy_args::{parse_period, parse_scope, parse_selector_bytes},
10    },
11    tempo::{apply_fee_payment, print_expires, require_hardfork, sponsor_hash, tempo_provider},
12    tx::{CastTxBuilder, SendTxOpts, SenderKind, apply_poll_interval},
13};
14use alloy_consensus::BlockHeader;
15use alloy_ens::NameOrAddress;
16use alloy_network::{EthereumWallet, NetworkTransactionBuilder};
17use alloy_primitives::{Address, B256, Bytes, U256, hex};
18use alloy_provider::{Provider, ProviderBuilder as AlloyProviderBuilder};
19use alloy_rpc_types::BlockId;
20use alloy_signer::Signer;
21use alloy_sol_types::SolCall;
22use chrono::DateTime;
23use clap::Parser;
24use eyre::Result;
25use foundry_cli::{
26    json::{print_json_object, print_json_success},
27    opts::{RpcOpts, TempoOpts, TransactionOpts},
28    utils::{LoadConfig, now, parse_fee_token_address, parse_json, resolve_lane},
29};
30use foundry_common::{
31    provider::ProviderBuilder,
32    sh_warn, shell,
33    tempo::{
34        self, AccountsStoreView, KeyType, active_tempo_hardfork,
35        configurable_account::{ca_error, config_commitment},
36        is_tempo_hardfork_active, read_tempo_accounts_store, tempo_accounts_store_path,
37    },
38};
39use foundry_wallets::{
40    BrowserWalletOpts, WalletOpts, WalletSigner, wallet_browser::signer::BrowserSigner,
41};
42use serde::Deserialize;
43use serde_json::{Value, json};
44use std::fmt::Display;
45use tempo_alloy::{TempoNetwork, chainspec::hardfork::TempoHardfork, provider::TempoProviderExt};
46use tempo_contracts::precompiles::{
47    ACCOUNT_KEYCHAIN_ADDRESS, DEFAULT_FEE_TOKEN,
48    IAccountKeychain::{
49        self, CallScope, KeyInfo, KeyRestrictions, LegacyTokenLimit, SelectorRule, SignatureType,
50        TokenLimit,
51    },
52    ISignatureVerifier, ITIP20, PATH_USD_ADDRESS, SIGNATURE_VERIFIER_ADDRESS,
53    account_keychain::{
54        authorizeAdminKeyCall, authorizeKeyCall, authorizeKeyWithWitnessCall,
55        legacyAuthorizeKeyCall,
56    },
57};
58use tempo_primitives::transaction::{
59    CallScope as AuthCallScope, KeyAuthorization, PrimitiveSignature,
60    SignatureType as AuthSignatureType, SignedKeyAuthorization, TokenLimit as AuthTokenLimit,
61};
62use yansi::Paint;
63
64/// Tempo keychain management commands.
65///
66/// Manage access keys stored in `~/.tempo/wallet/store.json` and query or modify
67/// on-chain key state via the AccountKeychain precompile.
68#[derive(Debug, Parser)]
69pub enum KeychainSubcommand {
70    /// List all keys from the local Tempo Accounts store.
71    #[command(visible_alias = "ls")]
72    List,
73
74    /// Show all keys for a specific wallet address from the local Tempo Accounts store.
75    Show {
76        /// The wallet address to look up.
77        wallet_address: Address,
78    },
79
80    /// Check on-chain provisioning status of a key via the AccountKeychain precompile.
81    #[command(visible_alias = "info")]
82    Check {
83        /// The wallet (account) address.
84        wallet_address: Address,
85
86        /// The key address to check.
87        key_address: Address,
88
89        #[command(flatten)]
90        rpc: RpcOpts,
91    },
92
93    /// Inspect an access key policy using the Tempo Accounts store and on-chain state.
94    Inspect {
95        /// The key address to inspect.
96        key_address: Address,
97
98        /// Root account address. Required when the key is not present in the local Accounts store.
99        #[arg(long, visible_alias = "wallet-address", value_name = "ADDRESS")]
100        root_account: Option<Address>,
101
102        #[command(flatten)]
103        rpc: RpcOpts,
104    },
105
106    /// Diagnose access-key signing issues end-to-end.
107    ///
108    /// Walks the Tempo Accounts store, RPC, and on-chain key state and prints a green
109    /// checklist. The first failing step turns red and includes a one-line hint.
110    Doctor {
111        /// The key address to diagnose. Optional when `--root-account` is provided.
112        #[arg(required_unless_present = "root_account")]
113        key_address: Option<Address>,
114
115        /// Root account address. Required if the key cannot be resolved from the Accounts store,
116        /// or to diagnose the default key for a sender.
117        #[arg(long, visible_alias = "wallet-address", value_name = "ADDRESS")]
118        root_account: Option<Address>,
119
120        /// Hypothetical call target for the TIP-1011 scope check.
121        #[arg(long, value_name = "ADDRESS")]
122        to: Option<Address>,
123
124        /// Function selector for the TIP-1011 scope check (hex `0x12345678`,
125        /// known shorthand like `transfer`, or full signature like `foo(uint256)`).
126        #[arg(long, value_parser = parse_selector_bytes, requires = "to")]
127        selector: Option<[u8; 4]>,
128
129        /// Recipient address for the TIP-1011 scope check (per-selector recipient list).
130        #[arg(long, value_name = "ADDRESS", requires = "selector")]
131        recipient: Option<Address>,
132
133        /// Fee token to check the root account balance for. Defaults to PathUSD.
134        #[arg(
135            id = "doctor_fee_token",
136            long = "fee-token",
137            value_name = "TOKEN",
138            value_parser = parse_fee_token_address
139        )]
140        fee_token: Option<Address>,
141
142        #[command(flatten)]
143        tempo: TempoOpts,
144
145        #[command(flatten)]
146        rpc: RpcOpts,
147    },
148
149    /// Authorize a new key on-chain via the AccountKeychain precompile.
150    ///
151    /// With `--tempo.configurable-account`, a configurable account sends the call in a `0x05`
152    /// transaction that its local owners approve (T14): the wallet signer, `--tempo.owner` and the
153    /// Tempo Accounts store, which must reach the account's threshold.
154    #[command(visible_alias = "auth")]
155    Authorize {
156        /// The key address to authorize.
157        key_address: Address,
158
159        /// Signature type: secp256k1, p256, webauthn, or configurable (a configurable account as
160        /// the access key, T14).
161        #[arg(default_value = "secp256k1", value_parser = parse_signature_type)]
162        key_type: SignatureType,
163
164        /// Expiry timestamp (unix seconds). Defaults to u64::MAX (never expires).
165        #[arg(default_value_t = u64::MAX)]
166        expiry: u64,
167
168        /// Enforce spending limits for this key.
169        #[arg(long)]
170        enforce_limits: bool,
171
172        /// Spending limit in TOKEN:AMOUNT format. Can be specified multiple times.
173        #[arg(long = "limit", value_parser = parse_limit)]
174        limits: Vec<TokenLimit>,
175
176        /// Call scope restriction in `TARGET[:SELECTORS[@RECIPIENTS]]` format.
177        /// TARGET alone allows all calls. `TARGET:transfer,approve` restricts to those selectors.
178        /// `TARGET:transfer@0x123` restricts selector to specific recipients.
179        #[arg(long = "scope", value_parser = parse_scope)]
180        scope: Vec<CallScope>,
181
182        /// Call scope restrictions as a JSON array. An empty array denies all calls.
183        /// Requires a Tempo T3-capable chain.
184        /// Format: `[{"target":"0x...","selectors":["transfer"]}]` or
185        /// `[{"target":"0x...","selectors":[{"selector":"transfer","recipients":["0x..."]}]}]`
186        #[arg(long = "scopes", value_parser = parse_scopes_json_wrapped, conflicts_with = "scope")]
187        scopes_json: Option<ScopesJson>,
188
189        /// Optional TIP-1053 witness to bind to this on-chain authorization.
190        ///
191        /// `0x000...000` is a valid present witness and is distinct from omitting the flag.
192        ///
193        /// For `--admin`, the `authorizeAdminKey` precompile always takes a witness; omitting
194        /// this flag submits `bytes32(0)` (which fails if that witness is already burned).
195        #[arg(long)]
196        witness: Option<B256>,
197
198        /// Authorize a T6 admin access key via `authorizeAdminKey` (key-management only).
199        ///
200        /// Admin keys may authorize/revoke other keys but cannot carry an expiry, spending limits,
201        /// or call scopes. The account is the signing (precompile caller) account. Not supported
202        /// on T14 or later, where TIP-1137 retires admin keys.
203        #[arg(long)]
204        admin: bool,
205
206        /// Skip the EIP-7702 authorization disclosure confirmation.
207        #[arg(long)]
208        force: bool,
209
210        #[command(flatten)]
211        tx: TransactionOpts,
212
213        #[command(flatten)]
214        send_tx: SendTxOpts,
215    },
216
217    /// Revoke an authorized key on-chain via the AccountKeychain precompile.
218    #[command(visible_alias = "rev")]
219    Revoke {
220        /// The key address to revoke.
221        key_address: Address,
222
223        /// Skip the EIP-7702 authorization disclosure confirmation.
224        #[arg(long)]
225        force: bool,
226
227        #[command(flatten)]
228        tx: TransactionOpts,
229
230        #[command(flatten)]
231        send_tx: SendTxOpts,
232    },
233
234    /// Burn a TIP-1053 key-authorization witness for the signing account.
235    #[command(name = "burn-witness")]
236    BurnWitness {
237        /// Witness to burn. `bytes32(0)` is valid.
238        witness: B256,
239
240        /// Skip the EIP-7702 authorization disclosure confirmation.
241        #[arg(long)]
242        force: bool,
243
244        #[command(flatten)]
245        tx: TransactionOpts,
246
247        #[command(flatten)]
248        send_tx: SendTxOpts,
249    },
250
251    /// Check whether a TIP-1053 key-authorization witness has been burned.
252    #[command(name = "is-witness-burned")]
253    IsWitnessBurned {
254        /// Account whose witness burn set should be checked.
255        account: Address,
256
257        /// Witness to check. `bytes32(0)` is valid.
258        witness: B256,
259
260        #[command(flatten)]
261        rpc: RpcOpts,
262    },
263
264    /// Check whether a key is the root key or an active admin key for an account (T6).
265    #[command(name = "is-admin")]
266    IsAdmin {
267        /// The account (root) address.
268        account: Address,
269
270        /// The key address to check.
271        key_address: Address,
272
273        #[command(flatten)]
274        rpc: RpcOpts,
275    },
276
277    /// Verify a Tempo keychain signature against an account's active access key (T6).
278    ///
279    /// `signature` must be an encoded Tempo keychain signature (not a raw 65-byte secp256k1
280    /// signature). Returns true only for an active access key, never the root key. The supplied
281    /// `hash` should already be domain-separated by the caller.
282    Verify {
283        /// The expected (root) account that embeds the key.
284        account: Address,
285
286        /// The 32-byte message hash that was signed.
287        hash: B256,
288
289        /// The encoded Tempo keychain signature.
290        signature: Bytes,
291
292        #[command(flatten)]
293        rpc: RpcOpts,
294    },
295
296    /// Verify a Tempo keychain signature against an account's root or admin key (T6).
297    ///
298    /// `signature` must be an encoded Tempo keychain signature (not a raw 65-byte secp256k1
299    /// signature). Returns true for the root key or an active admin key. `hash` should already be
300    /// domain-separated by the caller.
301    #[command(name = "verify-admin")]
302    VerifyAdmin {
303        /// The expected (root) account that embeds the key.
304        account: Address,
305
306        /// The 32-byte message hash that was signed.
307        hash: B256,
308
309        /// The encoded Tempo keychain signature.
310        signature: Bytes,
311
312        #[command(flatten)]
313        rpc: RpcOpts,
314    },
315
316    /// Query the remaining spending limit for a key on a specific token.
317    #[command(name = "rl", visible_alias = "remaining-limit")]
318    RemainingLimit {
319        /// The wallet (account) address.
320        wallet_address: Address,
321
322        /// The key address.
323        key_address: Address,
324
325        /// The token address.
326        token: Address,
327
328        #[command(flatten)]
329        rpc: RpcOpts,
330    },
331
332    /// Update the spending limit for a key on a specific token.
333    #[command(name = "ul", visible_alias = "update-limit")]
334    UpdateLimit {
335        /// The key address.
336        key_address: Address,
337
338        /// The token address.
339        token: Address,
340
341        /// The new spending limit.
342        new_limit: U256,
343
344        /// Skip the EIP-7702 authorization disclosure confirmation.
345        #[arg(long)]
346        force: bool,
347
348        #[command(flatten)]
349        tx: TransactionOpts,
350
351        #[command(flatten)]
352        send_tx: SendTxOpts,
353    },
354
355    /// Set allowed call scopes for a key.
356    #[command(name = "ss", visible_alias = "set-scope")]
357    SetScope {
358        /// The key address.
359        key_address: Address,
360
361        /// Call scope restriction in `TARGET[:SELECTORS[@RECIPIENTS]]` format.
362        #[arg(long = "scope", required = true, value_parser = parse_scope)]
363        scope: Vec<CallScope>,
364
365        /// Skip the EIP-7702 authorization disclosure confirmation.
366        #[arg(long)]
367        force: bool,
368
369        #[command(flatten)]
370        tx: TransactionOpts,
371
372        #[command(flatten)]
373        send_tx: SendTxOpts,
374    },
375
376    /// Remove call scope for a key on a target.
377    #[command(name = "rs", visible_alias = "remove-scope")]
378    RemoveScope {
379        /// The key address.
380        key_address: Address,
381
382        /// The target address to remove scope for.
383        target: Address,
384
385        /// Skip the EIP-7702 authorization disclosure confirmation.
386        #[arg(long)]
387        force: bool,
388
389        #[command(flatten)]
390        tx: TransactionOpts,
391
392        #[command(flatten)]
393        send_tx: SendTxOpts,
394    },
395
396    /// Read or edit TIP-1011 access-key permissions.
397    Policy {
398        /// Skip the EIP-7702 authorization disclosure confirmation.
399        #[arg(long, global = true)]
400        force: bool,
401
402        #[command(subcommand)]
403        command: KeychainPolicySubcommand,
404    },
405}
406
407/// Tempo key-authorization artifact helpers.
408#[derive(Debug, Parser)]
409pub enum KeyAuthorizationSubcommand {
410    /// RLP-encode an unsigned Tempo key authorization.
411    Encode {
412        #[command(flatten)]
413        authorization: KeyAuthorizationArgs,
414
415        /// Bind this authorization to a target account (T6).
416        ///
417        /// Required for `--admin` so the authorization cannot be replayed across accounts sharing
418        /// the same admin key. May also bind a plain authorization without `--admin`.
419        #[arg(long, value_name = "ADDRESS")]
420        account: Option<Address>,
421    },
422
423    /// Sign and RLP-encode a Tempo key authorization.
424    ///
425    /// With an admin access-key signer the bound account is the key's root and is derived
426    /// automatically; with a direct signer, `--bind-account` binds to another root. A root-signed
427    /// `--admin` authorization defaults the account to the signer.
428    ///
429    /// With `--tempo.configurable-account`, the configurable account's owners sign the
430    /// authorization (T14, TIP-1111) and it is bound to the account. Its configuration is read
431    /// from the RPC.
432    Sign {
433        #[command(flatten)]
434        authorization: KeyAuthorizationArgs,
435
436        #[command(flatten)]
437        configurable: ConfigurableAccountArgs,
438
439        #[command(flatten)]
440        rpc: RpcOpts,
441
442        /// Bind this authorization to a target (root) account (T6).
443        ///
444        /// Named `--bind-account` to avoid clashing with the wallet keystore `--account` selector.
445        #[arg(long = "bind-account", value_name = "ADDRESS")]
446        account: Option<Address>,
447
448        #[command(flatten)]
449        wallet: Box<WalletOpts>,
450
451        #[command(flatten)]
452        browser: BrowserWalletOpts,
453    },
454
455    /// Decode and inspect a Tempo key authorization (signed or unsigned).
456    ///
457    /// Accepts the hex RLP from `encode` (unsigned) or `sign` (signed) and prints its fields,
458    /// including the T6 `is_admin`/`account` fields and the recovered signer for signed input.
459    Inspect {
460        /// Hex-encoded RLP key authorization (signed or unsigned).
461        authorization: String,
462
463        /// Expected bound account; rejects a mismatched or replayed account-bound authorization.
464        #[arg(long, value_name = "ADDRESS")]
465        account: Option<Address>,
466    },
467}
468
469/// Common fields for `cast key-authorization encode` and `cast key-authorization sign`.
470#[derive(Debug, Parser)]
471pub struct KeyAuthorizationArgs {
472    /// Chain ID for replay protection.
473    #[arg(long)]
474    chain_id: u64,
475
476    /// Key address to authorize.
477    key_address: Address,
478
479    /// Type of access key being authorized: secp256k1, p256, webauthn, or configurable (a
480    /// configurable account as the access key, T14).
481    /// The root signature type is determined by the configured signer.
482    #[arg(long, default_value = "secp256k1", value_parser = parse_auth_signature_type)]
483    key_type: AuthSignatureType,
484
485    /// Expiry timestamp (unix seconds). Omit for no expiry.
486    #[arg(long)]
487    expiry: Option<u64>,
488
489    /// Enforce spending limits for this key. With no --limit entries, this means no spending.
490    #[arg(long)]
491    enforce_limits: bool,
492
493    /// Spending limit in `TOKEN:AMOUNT[:PERIOD]` format. Can be specified multiple times.
494    #[arg(long = "limit", value_parser = parse_auth_limit)]
495    limits: Vec<AuthTokenLimit>,
496
497    /// Call scope restriction in `TARGET[:SELECTORS[@RECIPIENTS]]` format.
498    /// TARGET alone allows all calls to that target.
499    #[arg(long = "scope", value_parser = parse_auth_scope)]
500    scope: Vec<AuthCallScope>,
501
502    /// Call scope restrictions as a JSON array.
503    #[arg(long = "scopes", value_parser = parse_auth_scopes_json_wrapped, conflicts_with = "scope")]
504    scopes_json: Option<AuthScopesJson>,
505
506    /// Optional TIP-1053 witness to include in the authorization signing hash.
507    ///
508    /// `0x000...000` is a valid present witness and is distinct from omitting the flag.
509    #[arg(long)]
510    witness: Option<B256>,
511
512    /// Authorize a T6 admin access key (key-management only).
513    ///
514    /// Admin keys may authorize/revoke other keys but cannot carry an expiry, spending limits, or
515    /// call scopes, and require a bound account (`--account` for `encode`, signer-derived for
516    /// `sign`). Tempo nodes reject admin key authorizations on T14 or later, where TIP-1137
517    /// retires admin keys.
518    #[arg(long)]
519    admin: bool,
520}
521
522/// Higher-level access-key policy editing commands.
523#[derive(Debug, Parser)]
524pub enum KeychainPolicySubcommand {
525    /// Add or widen an allowed call rule for a target contract.
526    AddCall {
527        /// The key address to update.
528        key_address: Address,
529
530        /// Root account address. Required when the key is not present in the local Accounts store.
531        #[arg(long, visible_alias = "wallet-address", value_name = "ADDRESS")]
532        root_account: Option<Address>,
533
534        /// Target contract address.
535        #[arg(long)]
536        target: Address,
537
538        /// Function selector, full signature, or known TIP-20 shorthand.
539        #[arg(long, value_parser = parse_selector_bytes)]
540        selector: [u8; 4],
541
542        /// Optional recipient/spender restrictions for selector calls.
543        #[arg(long, value_delimiter = ',')]
544        recipients: Vec<Address>,
545
546        #[command(flatten)]
547        tx: TransactionOpts,
548
549        #[command(flatten)]
550        send_tx: SendTxOpts,
551    },
552
553    /// Update a token spending limit amount for a key.
554    SetLimit {
555        /// The key address to update.
556        key_address: Address,
557
558        /// Token address, numeric TIP-20 token id, or known Tempo fee-token symbol.
559        #[arg(long, value_parser = parse_fee_token_address)]
560        token: Address,
561
562        /// New raw token-denominated limit.
563        #[arg(long)]
564        amount: U256,
565
566        /// Limit period such as 7d, 24h, or 3600s.
567        ///
568        /// The current AccountKeychain update entrypoint cannot change periods, so non-zero
569        /// values are rejected.
570        #[arg(long, value_parser = parse_period)]
571        period: Option<u64>,
572
573        #[command(flatten)]
574        tx: TransactionOpts,
575
576        #[command(flatten)]
577        send_tx: SendTxOpts,
578    },
579
580    /// Remove all allowed-call rules for a target contract.
581    RemoveTarget {
582        /// The key address to update.
583        key_address: Address,
584
585        /// Target contract address to remove.
586        #[arg(long)]
587        target: Address,
588
589        #[command(flatten)]
590        tx: TransactionOpts,
591
592        #[command(flatten)]
593        send_tx: SendTxOpts,
594    },
595}
596
597fn parse_auth_signature_type(s: &str) -> Result<AuthSignatureType, String> {
598    match s.to_lowercase().as_str() {
599        "secp256k1" => Ok(AuthSignatureType::Secp256k1),
600        "p256" => Ok(AuthSignatureType::P256),
601        "webauthn" => Ok(AuthSignatureType::WebAuthn),
602        "configurable" | "configurableaccount" => Ok(AuthSignatureType::ConfigurableAccount),
603        _ => Err(format!(
604            "unknown signature type: {s} (expected secp256k1, p256, webauthn, or configurable)"
605        )),
606    }
607}
608
609fn parse_signature_type(s: &str) -> Result<SignatureType, String> {
610    parse_auth_signature_type(s).map(Into::into)
611}
612
613/// The key type of an ABI signature type; `None` for values outside the known variants.
614fn abi_key_type(t: SignatureType) -> Option<KeyType> {
615    AuthSignatureType::try_from(t).ok().map(KeyType::from)
616}
617
618const fn key_type_name(t: KeyType) -> &'static str {
619    match t {
620        KeyType::Secp256k1 => "secp256k1",
621        KeyType::P256 => "p256",
622        KeyType::WebAuthn => "webauthn",
623        KeyType::ConfigurableAccount => "configurableaccount",
624    }
625}
626
627const fn key_type_label(t: KeyType) -> &'static str {
628    match t {
629        KeyType::Secp256k1 => "Secp256k1",
630        KeyType::P256 => "P256",
631        KeyType::WebAuthn => "WebAuthn",
632        KeyType::ConfigurableAccount => "ConfigurableAccount",
633    }
634}
635
636/// Parse a `--limit TOKEN:AMOUNT[:PERIOD]` flag value.
637fn parse_auth_limit(s: &str) -> Result<AuthTokenLimit, String> {
638    let (token, amount, period) = match s.split(':').collect::<Vec<_>>()[..] {
639        [token, amount] => (token, amount, None),
640        [token, amount, period] => (token, amount, Some(period)),
641        _ => return Err(format!("invalid limit format: {s} (expected TOKEN:AMOUNT[:PERIOD])")),
642    };
643    Ok(AuthTokenLimit {
644        token: token.parse().map_err(|e| format!("invalid token address '{token}': {e}"))?,
645        limit: amount.parse().map_err(|e| format!("invalid amount '{amount}': {e}"))?,
646        period: period.map_or(Ok(0), parse_period)?,
647    })
648}
649
650fn parse_limit(s: &str) -> Result<TokenLimit, String> {
651    parse_auth_limit(s).map(|limit| TokenLimit {
652        token: limit.token,
653        amount: limit.limit,
654        period: limit.period,
655    })
656}
657
658fn parse_auth_scope(s: &str) -> Result<AuthCallScope, String> {
659    parse_scope(s).map(Into::into)
660}
661
662/// Represents a single scope entry in JSON format for `--scopes`.
663#[derive(Deserialize)]
664#[serde(deny_unknown_fields)]
665struct JsonCallScope {
666    target: Address,
667    #[serde(default)]
668    selectors: Option<Vec<JsonSelectorEntry>>,
669}
670
671/// A selector entry can be either a plain string or an object with recipients.
672#[derive(Deserialize)]
673#[serde(untagged)]
674enum JsonSelectorEntry {
675    Name(String),
676    WithRecipients(JsonSelectorWithRecipients),
677}
678
679// `deny_unknown_fields` is not honoured on untagged enum variants, so this needs its own struct.
680#[derive(Deserialize)]
681#[serde(deny_unknown_fields)]
682struct JsonSelectorWithRecipients {
683    selector: String,
684    #[serde(default)]
685    recipients: Vec<Address>,
686}
687
688/// Parse `--scopes` JSON flag value.
689fn parse_scopes_json(s: &str) -> Result<Vec<CallScope>, String> {
690    let entries: Vec<JsonCallScope> =
691        parse_json(s).map_err(|e| format!("invalid --scopes JSON: {e}"))?;
692    entries
693        .into_iter()
694        .map(|entry| {
695            let selector_rules = entry
696                .selectors
697                .unwrap_or_default()
698                .into_iter()
699                .map(|sel| {
700                    let (selector, recipients) = match sel {
701                        JsonSelectorEntry::Name(name) => (name, vec![]),
702                        JsonSelectorEntry::WithRecipients(JsonSelectorWithRecipients {
703                            selector,
704                            recipients,
705                        }) => (selector, recipients),
706                    };
707                    let selector = parse_selector_bytes(&selector)
708                        .map_err(|e| format!("in --scopes JSON: {e}"))?;
709                    Ok(SelectorRule { selector: selector.into(), recipients })
710                })
711                .collect::<Result<_, String>>()?;
712            Ok(CallScope { target: entry.target, selectorRules: selector_rules })
713        })
714        .collect()
715}
716
717/// Newtype wrapper for parsed `--scopes` JSON so clap can treat it as a single value.
718#[derive(Debug, Clone)]
719pub struct ScopesJson(Vec<CallScope>);
720
721fn parse_scopes_json_wrapped(s: &str) -> Result<ScopesJson, String> {
722    parse_scopes_json(s).map(ScopesJson)
723}
724
725/// Newtype wrapper for parsed key-authorization `--scopes` JSON.
726#[derive(Debug, Clone)]
727pub struct AuthScopesJson(Vec<AuthCallScope>);
728
729fn parse_auth_scopes_json_wrapped(s: &str) -> Result<AuthScopesJson, String> {
730    parse_scopes_json(s).map(|scopes| AuthScopesJson(scopes.into_iter().map(Into::into).collect()))
731}
732
733impl KeychainSubcommand {
734    #[allow(clippy::large_stack_frames)]
735    pub async fn run(self) -> Result<()> {
736        match self {
737            Self::List => list_keys(None),
738            Self::Show { wallet_address } => list_keys(Some(wallet_address)),
739            Self::Check { wallet_address, key_address, rpc } => {
740                run_check(wallet_address, key_address, rpc).await
741            }
742            Self::Inspect { key_address, root_account, rpc } => {
743                run_inspect(key_address, root_account, rpc).await
744            }
745            Self::Doctor {
746                key_address,
747                root_account,
748                to,
749                selector,
750                recipient,
751                fee_token,
752                mut tempo,
753                rpc,
754            } => {
755                let fee_token = fee_token.or(tempo.fee_token).unwrap_or(DEFAULT_FEE_TOKEN);
756                let mut doctor = Doctor::new(root_account, key_address, fee_token);
757                doctor
758                    .run(key_address, root_account, to, selector, recipient, &mut tempo, rpc)
759                    .await;
760                doctor.finish()
761            }
762            Self::Authorize {
763                key_address,
764                key_type,
765                expiry,
766                enforce_limits,
767                limits,
768                scope,
769                scopes_json,
770                witness,
771                admin,
772                force,
773                tx,
774                send_tx,
775            } => {
776                let scopes_present = scopes_json.is_some() || !scope.is_empty();
777                let scopes = scopes_json.map_or(scope, |ScopesJson(scopes)| scopes);
778                run_authorize(
779                    key_address,
780                    key_type,
781                    expiry,
782                    enforce_limits,
783                    limits,
784                    scopes,
785                    scopes_present,
786                    witness,
787                    admin,
788                    tx,
789                    send_tx,
790                    force,
791                )
792                .await
793            }
794            Self::Revoke { key_address, force, tx, send_tx } => {
795                send_keychain_call(
796                    &IAccountKeychain::revokeKeyCall { keyId: key_address },
797                    tx,
798                    &send_tx,
799                    force,
800                )
801                .await
802            }
803            Self::BurnWitness { witness, force, tx, send_tx } => {
804                let (_, provider) = tempo_provider(&send_tx.eth.rpc)?;
805                require_hardfork(
806                    &provider,
807                    TempoHardfork::T5,
808                    "burn-witness requires a Tempo T5-capable AccountKeychain RPC",
809                )
810                .await?;
811                send_keychain_call(
812                    &IAccountKeychain::burnKeyAuthorizationWitnessCall { witness },
813                    tx,
814                    &send_tx,
815                    force,
816                )
817                .await
818            }
819            Self::IsWitnessBurned { account, witness, rpc } => {
820                let (_, provider) = tempo_provider(&rpc)?;
821                require_hardfork(
822                    &provider,
823                    TempoHardfork::T5,
824                    "is-witness-burned requires a Tempo T5-capable AccountKeychain RPC",
825                )
826                .await?;
827                let burned = provider
828                    .account_keychain()
829                    .isKeyAuthorizationWitnessBurned(account, witness)
830                    .call()
831                    .await?;
832                print_json_or(
833                    json!({ "account": account, "witness": witness, "burned": burned }),
834                    burned,
835                )
836            }
837            Self::IsAdmin { account, key_address, rpc } => {
838                let (_, provider) = tempo_provider(&rpc)?;
839                require_hardfork(
840                    &provider,
841                    TempoHardfork::T6,
842                    "is-admin requires a Tempo T6-capable AccountKeychain RPC",
843                )
844                .await?;
845                let is_admin =
846                    provider.account_keychain().isAdminKey(account, key_address).call().await?;
847                print_json_or(
848                    json!({ "account": account, "key_address": key_address, "is_admin": is_admin }),
849                    is_admin,
850                )
851            }
852            Self::Verify { account, hash, signature, rpc } => {
853                run_verify_keychain(account, hash, signature, rpc, false).await
854            }
855            Self::VerifyAdmin { account, hash, signature, rpc } => {
856                run_verify_keychain(account, hash, signature, rpc, true).await
857            }
858            Self::RemainingLimit { wallet_address, key_address, token, rpc } => {
859                let (_, provider) = tempo_provider(&rpc)?;
860                let is_t3 = is_tempo_hardfork_active(&provider, TempoHardfork::T3).await?;
861                let (remaining, _) =
862                    remaining_limit(&provider, wallet_address, key_address, token, is_t3).await?;
863                if shell::is_json() {
864                    sh_println!("{}", json!({ "remaining": remaining.to_string() }))?;
865                } else {
866                    sh_println!("{remaining}")?;
867                }
868                Ok(())
869            }
870            Self::UpdateLimit { key_address, token, new_limit, force, tx, send_tx } => {
871                send_keychain_call(
872                    &IAccountKeychain::updateSpendingLimitCall {
873                        keyId: key_address,
874                        token,
875                        newLimit: new_limit,
876                    },
877                    tx,
878                    &send_tx,
879                    force,
880                )
881                .await
882            }
883            Self::SetScope { key_address, scope, force, tx, send_tx } => {
884                send_keychain_call(
885                    &IAccountKeychain::setAllowedCallsCall { keyId: key_address, scopes: scope },
886                    tx,
887                    &send_tx,
888                    force,
889                )
890                .await
891            }
892            Self::RemoveScope { key_address, target, force, tx, send_tx } => {
893                send_keychain_call(
894                    &IAccountKeychain::removeAllowedCallsCall { keyId: key_address, target },
895                    tx,
896                    &send_tx,
897                    force,
898                )
899                .await
900            }
901            Self::Policy { force, command } => command.run(force).await,
902        }
903    }
904}
905
906impl KeyAuthorizationSubcommand {
907    pub async fn run(self) -> Result<()> {
908        match self {
909            Self::Encode { authorization, account } => {
910                let authorization = authorization.into_authorization(account)?;
911                let encoded = alloy_rlp::encode(&authorization);
912                print_json_or(
913                    json!({
914                        "key_authorization": hex::encode_prefixed(&encoded),
915                        "signature_hash": authorization.signature_hash(),
916                        "rlp_length": encoded.len(),
917                        "is_admin": authorization.is_admin(),
918                        "account": authorization.account,
919                        "witness": authorization.witness(),
920                    }),
921                    hex::encode_prefixed(&encoded),
922                )
923            }
924            Self::Sign { authorization, configurable, rpc, account, wallet, browser } => {
925                if let Some(configurable_account) = configurable.account() {
926                    eyre::ensure!(
927                        !browser.browser,
928                        "browser wallets cannot sign as a configurable account owner; pass \
929                         browser approvals with --tempo.owner-signature"
930                    );
931                    return sign_configurable_key_authorization(
932                        authorization,
933                        &configurable,
934                        configurable_account,
935                        account,
936                        &wallet,
937                        &rpc,
938                    )
939                    .await;
940                }
941                run_key_auth_sign(authorization, account, *wallet, browser).await
942            }
943            Self::Inspect { authorization, account } => {
944                run_key_auth_inspect(&authorization, account)
945            }
946        }
947    }
948}
949
950impl KeychainPolicySubcommand {
951    pub async fn run(self, force: bool) -> Result<()> {
952        match self {
953            Self::AddCall {
954                key_address,
955                root_account,
956                target,
957                selector,
958                recipients,
959                tx,
960                send_tx,
961            } => {
962                run_policy_add_call(
963                    key_address,
964                    root_account,
965                    target,
966                    selector,
967                    recipients,
968                    tx,
969                    send_tx,
970                    force,
971                )
972                .await
973            }
974            Self::SetLimit { key_address, token, amount, period, tx, send_tx } => {
975                if period.is_some_and(|period| period != 0) {
976                    eyre::bail!(
977                        "--period is not supported by the current AccountKeychain updateSpendingLimit \
978                         precompile; periods can only be set when authorizing a key"
979                    );
980                }
981                // updateSpendingLimit authorizes against msg.sender; the root account is not part
982                // of calldata.
983                send_keychain_call(
984                    &IAccountKeychain::updateSpendingLimitCall {
985                        keyId: key_address,
986                        token,
987                        newLimit: amount,
988                    },
989                    tx,
990                    &send_tx,
991                    force,
992                )
993                .await
994            }
995            Self::RemoveTarget { key_address, target, tx, send_tx } => {
996                send_keychain_call(
997                    &IAccountKeychain::removeAllowedCallsCall { keyId: key_address, target },
998                    tx,
999                    &send_tx,
1000                    force,
1001                )
1002                .await
1003            }
1004        }
1005    }
1006}
1007
1008/// `cast keychain list` / `cast keychain show <wallet_address>` — display Tempo Accounts store
1009/// entries, optionally filtered to one wallet.
1010fn list_keys(wallet_address: Option<Address>) -> Result<()> {
1011    let store = load_accounts_store()?;
1012    let entries: Vec<_> = store
1013        .keys
1014        .iter()
1015        .filter(|e| wallet_address.is_none_or(|wallet| e.wallet_address == wallet))
1016        .collect();
1017
1018    if shell::is_json() {
1019        return print_json_object(entries.iter().map(|e| key_entry_to_json(e)).collect::<Vec<_>>());
1020    }
1021    if entries.is_empty() {
1022        return match wallet_address {
1023            Some(wallet) => sh_println!("No keys found for wallet {wallet}."),
1024            None => sh_println!("No keys found in store.json."),
1025        };
1026    }
1027    for (i, entry) in entries.iter().enumerate() {
1028        if i > 0 {
1029            sh_println!()?;
1030        }
1031        print_key_entry(entry)?;
1032    }
1033    Ok(())
1034}
1035
1036struct InspectedLimit {
1037    token: Address,
1038    configured_amount: String,
1039    remaining: U256,
1040    period_end: Option<u64>,
1041}
1042
1043enum AllowedCallsView {
1044    Unsupported,
1045    Unrestricted,
1046    Scoped(Vec<CallScope>),
1047}
1048
1049/// `cast keychain inspect <key_address>` — inspect on-chain key policy.
1050async fn run_inspect(
1051    key_address: Address,
1052    root_account: Option<Address>,
1053    rpc: RpcOpts,
1054) -> Result<()> {
1055    let (root_account, entry) = resolve_key_metadata(key_address, root_account)?;
1056    let (_, provider) = tempo_provider(&rpc)?;
1057
1058    let info = provider.get_keychain_key(root_account, key_address).await?;
1059    let provisioned = !info.keyId.is_zero();
1060    let is_t3 = is_tempo_hardfork_active(&provider, TempoHardfork::T3).await?;
1061    // On T6, `isAdminKey` is authoritative for the root/admin distinction.
1062    let is_admin = is_tempo_hardfork_active(&provider, TempoHardfork::T6).await?
1063        && provider.account_keychain().isAdminKey(root_account, key_address).call().await?;
1064    let role = key_role(key_address == root_account, is_admin);
1065
1066    let mut limits = Vec::new();
1067    if info.enforceLimits {
1068        for local in entry.iter().flat_map(|entry| &entry.limits) {
1069            let (remaining, period_end) =
1070                remaining_limit(&provider, root_account, key_address, local.currency, is_t3)
1071                    .await?;
1072            limits.push(InspectedLimit {
1073                token: local.currency,
1074                configured_amount: local.limit.clone(),
1075                remaining,
1076                period_end,
1077            });
1078        }
1079    }
1080
1081    let allowed_calls = if is_t3 {
1082        let allowed =
1083            provider.account_keychain().getAllowedCalls(root_account, key_address).call().await?;
1084        if allowed.isScoped {
1085            AllowedCallsView::Scoped(allowed.scopes)
1086        } else {
1087            AllowedCallsView::Unrestricted
1088        }
1089    } else {
1090        AllowedCallsView::Unsupported
1091    };
1092
1093    let key_type =
1094        if provisioned { abi_key_type(info.signatureType) } else { entry.map(|e| e.key_type) };
1095
1096    if shell::is_json() {
1097        return print_json_object(json!({
1098            "root_account": root_account,
1099            "key_id": key_address,
1100            "provisioned": provisioned,
1101            "type": key_type.map_or("unknown", key_type_name),
1102            "role": role,
1103            "is_admin": is_admin,
1104            "expiry": provisioned.then_some(info.expiry),
1105            "expiry_human": provisioned.then(|| format_expiry_for_inspect(info.expiry)),
1106            "enforce_limits": info.enforceLimits,
1107            "is_revoked": info.isRevoked,
1108            "limits": limits.iter().map(inspected_limit_to_json).collect::<Vec<_>>(),
1109            "allowed_calls": allowed_calls_to_json(&allowed_calls),
1110        }));
1111    }
1112
1113    sh_println!("Root account: {root_account}")?;
1114    sh_println!("Key id:       {key_address}")?;
1115    sh_println!("Type:         {}", key_type.map_or("unknown", key_type_label))?;
1116    sh_println!("Role:         {role}")?;
1117    if info.isRevoked {
1118        sh_println!("Status:       revoked")?;
1119    } else if !provisioned {
1120        sh_println!("Status:       not provisioned")?;
1121    } else {
1122        sh_println!("Status:       active")?;
1123        sh_println!("Expiry:       {}", format_expiry_for_inspect(info.expiry))?;
1124    }
1125    print_inspected_limits(info.enforceLimits, &limits)?;
1126    print_allowed_calls(&allowed_calls)
1127}
1128
1129/// `cast keychain check` / `cast keychain info` — query on-chain key status.
1130async fn run_check(wallet_address: Address, key_address: Address, rpc: RpcOpts) -> Result<()> {
1131    let (_, provider) = tempo_provider(&rpc)?;
1132    let info = provider.get_keychain_key(wallet_address, key_address).await?;
1133    let provisioned = !info.keyId.is_zero();
1134    let signature_type = abi_key_type(info.signatureType).map_or("unknown", key_type_name);
1135
1136    if shell::is_json() {
1137        return print_json_object(json!({
1138            "wallet_address": wallet_address,
1139            "key_address": key_address,
1140            "provisioned": provisioned,
1141            "signatureType": signature_type,
1142            "key_id": info.keyId,
1143            "expiry": info.expiry,
1144            "expiry_human": format_expiry(info.expiry),
1145            "enforce_limits": info.enforceLimits,
1146            "is_revoked": info.isRevoked,
1147        }));
1148    }
1149
1150    sh_println!("Wallet:         {wallet_address}")?;
1151    sh_println!("Key:            {key_address}")?;
1152    if info.isRevoked {
1153        return sh_println!("Status:         {} revoked", "✗".red());
1154    }
1155    if !provisioned {
1156        return sh_println!("Status:         {} not provisioned", "✗".red());
1157    }
1158    sh_println!("Status:         {} active", "✓".green())?;
1159    sh_println!("Signature Type: {signature_type}")?;
1160    sh_println!("Key ID:         {}", info.keyId)?;
1161    let expiry = format_expiry(info.expiry);
1162    if info.expiry != u64::MAX && info.expiry <= now().as_secs() {
1163        sh_println!("Expiry:         {expiry} ({})", "expired".red())?;
1164    } else {
1165        sh_println!("Expiry:         {expiry}")?;
1166    }
1167    sh_println!("Spending Limits: {}", if info.enforceLimits { "enforced" } else { "none" })
1168}
1169
1170/// `cast keychain verify` / `verify-admin` — verify a Tempo keychain signature (T6).
1171async fn run_verify_keychain(
1172    account: Address,
1173    hash: B256,
1174    signature: Bytes,
1175    rpc: RpcOpts,
1176    admin: bool,
1177) -> Result<()> {
1178    let (_, provider) = tempo_provider(&rpc)?;
1179    let command = if admin { "verify-admin" } else { "verify" };
1180    require_hardfork(
1181        &provider,
1182        TempoHardfork::T6,
1183        &format!("{command} requires a Tempo T6-capable SignatureVerifier RPC"),
1184    )
1185    .await?;
1186
1187    let verifier = ISignatureVerifier::new(SIGNATURE_VERIFIER_ADDRESS, &provider);
1188    let valid = if admin {
1189        verifier.verifyKeychainAdmin(account, hash, signature.clone()).call().await?
1190    } else {
1191        verifier.verifyKeychain(account, hash, signature.clone()).call().await?
1192    };
1193    print_json_or(
1194        json!({
1195            "account": account,
1196            "hash": hash,
1197            "signature": signature,
1198            "admin": admin,
1199            "valid": valid,
1200        }),
1201        valid,
1202    )
1203}
1204
1205/// Remaining spending limit for `token` and, on T3+, the current period end.
1206async fn remaining_limit<P: Provider<TempoNetwork>>(
1207    provider: &P,
1208    root_account: Address,
1209    key_address: Address,
1210    token: Address,
1211    is_t3: bool,
1212) -> Result<(U256, Option<u64>)> {
1213    if is_t3 {
1214        let limit = provider
1215            .get_keychain_remaining_limit_with_period(root_account, key_address, token)
1216            .await?;
1217        Ok((limit.remaining, Some(limit.periodEnd)))
1218    } else {
1219        let remaining = provider
1220            .account_keychain()
1221            .getRemainingLimit(root_account, key_address, token)
1222            .call()
1223            .await?;
1224        Ok((remaining, None))
1225    }
1226}
1227
1228// ---------------------------------------------------------------------------
1229// `cast keychain doctor`
1230// ---------------------------------------------------------------------------
1231//
1232// TODO(OSS-160 follow-up): browser-wallet KeyAuthorization signing still needs a
1233// wallet-facing probe once the upstream browser-wallet surface lands. TIP-1009
1234// and sponsorship have config-level diagnostics below, but full fee-payer digest
1235// validation needs a concrete transaction payload.
1236//
1237//   * Browser-wallet `KeyAuthorization` signing — wallet capability is being added in
1238//     foundry-rs/foundry#14743 + foundry-rs/foundry-core#67 + foundry-rs/foundry-browser-wallet#67.
1239//     Once merged, doctor can probe whether the connected browser/passkey wallet can sign the
1240//     digest.
1241
1242/// A doctor check as `(name, label)`.
1243type Check = (&'static str, &'static str);
1244
1245const ACCOUNTS_STORE: Check = ("accounts_store", "Accounts store");
1246const RPC: Check = ("rpc_reachability", "RPC reachable");
1247const CHAIN_ID: Check = ("chain_id_match", "Chain ID match");
1248const LOCAL_SIGNING: Check = ("local_signing", "Local signing");
1249const KEY_REGISTRATION: Check = ("key_registration", "Key registration");
1250const REVOCATION: Check = ("revocation", "Revocation");
1251const EXPIRY: Check = ("expiry", "Expiry");
1252const HARDFORK: Check = ("hardfork", "Hardfork");
1253const SPENDING_LIMITS: Check = ("spending_limits", "Spending limits");
1254const ALLOWED_CALLS: Check = ("allowed_calls", "Allowed calls");
1255const FEE_TOKEN_BALANCE: Check = ("fee_token_balance", "Fee-token balance");
1256const EXPIRING_NONCE: Check = ("expiring_nonce", "Expiring nonce");
1257const SPONSORSHIP: Check = ("sponsorship", "Sponsorship");
1258
1259const HARDFORK_UNKNOWN_HINT: &str = "retry against an RPC that reports Tempo hardfork activation";
1260const WIDEN_POLICY_HINT: &str = "widen the policy with `cast keychain policy add-call ...`";
1261
1262#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
1263#[serde(rename_all = "lowercase")]
1264enum DoctorStatus {
1265    Pass,
1266    Warn,
1267    Fail,
1268}
1269
1270#[derive(Debug, Clone, serde::Serialize)]
1271struct DoctorStep {
1272    name: &'static str,
1273    label: &'static str,
1274    status: DoctorStatus,
1275    detail: String,
1276    #[serde(skip_serializing_if = "Option::is_none")]
1277    hint: Option<String>,
1278}
1279
1280impl DoctorStep {
1281    fn new(
1282        (name, label): Check,
1283        status: DoctorStatus,
1284        detail: impl Into<String>,
1285        hint: Option<String>,
1286    ) -> Self {
1287        Self { name, label, status, detail: detail.into(), hint }
1288    }
1289
1290    fn pass(check: Check, detail: impl Into<String>) -> Self {
1291        Self::new(check, DoctorStatus::Pass, detail, None)
1292    }
1293
1294    fn warn(check: Check, detail: impl Into<String>, hint: impl Into<String>) -> Self {
1295        Self::new(check, DoctorStatus::Warn, detail, Some(hint.into()))
1296    }
1297
1298    fn fail(check: Check, detail: impl Into<String>, hint: impl Into<String>) -> Self {
1299        Self::new(check, DoctorStatus::Fail, detail, Some(hint.into()))
1300    }
1301}
1302
1303#[derive(Debug, Clone, Copy, Default, serde::Serialize)]
1304struct DoctorContext {
1305    #[serde(skip_serializing_if = "Option::is_none")]
1306    root_account: Option<Address>,
1307    #[serde(skip_serializing_if = "Option::is_none")]
1308    key_address: Option<Address>,
1309    #[serde(skip_serializing_if = "Option::is_none")]
1310    chain_id: Option<u64>,
1311    fee_token: Address,
1312}
1313
1314/// Result of resolving a Tempo Accounts store entry for the doctor.
1315#[derive(Debug)]
1316struct DoctorSubject {
1317    root_account: Address,
1318    key_address: Address,
1319    entry: Option<tempo::KeyEntry>,
1320    explicit: bool,
1321}
1322
1323/// Candidate subject collected before the RPC chain is known.
1324#[derive(Debug)]
1325struct DoctorCandidate {
1326    root_account: Address,
1327    key_address: Address,
1328    chain_id: Option<u64>,
1329    entry: Option<tempo::KeyEntry>,
1330    explicit: bool,
1331}
1332
1333impl DoctorCandidate {
1334    const fn from_entry(entry: tempo::KeyEntry) -> Self {
1335        Self {
1336            root_account: entry.wallet_address,
1337            key_address: entry.key_address,
1338            chain_id: Some(entry.chain_id),
1339            entry: Some(entry),
1340            explicit: false,
1341        }
1342    }
1343
1344    const fn explicit(root_account: Address, key_address: Address) -> Self {
1345        Self { root_account, key_address, chain_id: None, entry: None, explicit: true }
1346    }
1347
1348    fn has_inline_key(&self) -> bool {
1349        self.entry.as_ref().is_some_and(|entry| entry.has_inline_key())
1350    }
1351}
1352
1353enum KeyRegistration {
1354    OnChain(KeyInfo),
1355    Pending(Box<SignedKeyAuthorization>),
1356}
1357
1358#[derive(Debug, Clone)]
1359enum ChainTimestamp {
1360    Known(u64),
1361    Unknown { detail: String, hint: &'static str },
1362}
1363
1364impl ChainTimestamp {
1365    const fn timestamp(&self) -> Option<u64> {
1366        match self {
1367            Self::Known(timestamp) => Some(*timestamp),
1368            Self::Unknown { .. } => None,
1369        }
1370    }
1371
1372    /// The chain timestamp, or a warning step that `detail` could not be checked without it.
1373    fn get(&self, check: Check, detail: impl Display) -> Result<u64, DoctorStep> {
1374        match self {
1375            Self::Known(timestamp) => Ok(*timestamp),
1376            Self::Unknown { detail: reason, hint } => {
1377                Err(DoctorStep::warn(check, format!("{detail}: {reason}"), *hint))
1378            }
1379        }
1380    }
1381}
1382
1383/// Outcome of TIP-1011 allowed-call matching.
1384#[derive(Debug, PartialEq, Eq)]
1385enum AllowedCallMatch {
1386    /// The call is allowed.
1387    Allowed(String),
1388    /// The call is denied.
1389    Denied(String),
1390    /// The selector is allowed but recipients are restricted; user did not pass `--recipient`.
1391    RecipientRestricted(Vec<Address>),
1392}
1393
1394/// Accumulated `cast keychain doctor` report.
1395struct Doctor {
1396    steps: Vec<DoctorStep>,
1397    context: DoctorContext,
1398}
1399
1400impl Doctor {
1401    const fn new(
1402        root_account: Option<Address>,
1403        key_address: Option<Address>,
1404        fee_token: Address,
1405    ) -> Self {
1406        let context = DoctorContext { root_account, key_address, chain_id: None, fee_token };
1407        Self { steps: Vec::new(), context }
1408    }
1409
1410    /// Records `step`; `None` when it failed so `?` stops the diagnosis.
1411    fn check(&mut self, step: DoctorStep) -> Option<()> {
1412        let failed = step.status == DoctorStatus::Fail;
1413        self.steps.push(step);
1414        (!failed).then_some(())
1415    }
1416
1417    /// Unwraps `result`, recording the failing step and stopping the diagnosis on `Err`.
1418    fn attempt<T>(&mut self, result: Result<T, DoctorStep>) -> Option<T> {
1419        match result {
1420            Ok(value) => Some(value),
1421            Err(step) => {
1422                self.steps.push(step);
1423                None
1424            }
1425        }
1426    }
1427
1428    /// Diagnoses access-key signing failures, stopping at the first failing step.
1429    #[allow(clippy::too_many_arguments)]
1430    async fn run(
1431        &mut self,
1432        key_address: Option<Address>,
1433        root_account: Option<Address>,
1434        to: Option<Address>,
1435        selector: Option<[u8; 4]>,
1436        recipient: Option<Address>,
1437        tempo: &mut TempoOpts,
1438        rpc: RpcOpts,
1439    ) -> Option<()> {
1440        let resolved_expires_at = tempo.resolve_expires();
1441
1442        // Step 1: Tempo Accounts store lookup.
1443        let (step, candidates) =
1444            self.attempt(collect_local_candidates(key_address, root_account))?;
1445        self.steps.push(step);
1446
1447        // Step 2: RPC reachability.
1448        let config = self.attempt(rpc.load_config().map_err(|err| {
1449            DoctorStep::fail(
1450                RPC,
1451                format!("could not load RPC config: {err}"),
1452                "check --rpc-url and your foundry.toml",
1453            )
1454        }))?;
1455        let provider = self.attempt(
1456            ProviderBuilder::<TempoNetwork>::from_config(&config)
1457                .and_then(|builder| builder.build())
1458                .map_err(|err| {
1459                    DoctorStep::fail(
1460                        RPC,
1461                        format!("could not build provider: {err}"),
1462                        "verify --rpc-url is set and reachable",
1463                    )
1464                }),
1465        )?;
1466        let rpc_chain_id = self.attempt(provider.get_chain_id().await.map_err(|err| {
1467            DoctorStep::fail(
1468                RPC,
1469                format!("eth_chainId failed: {err}"),
1470                "confirm the node is reachable and not rate-limited",
1471            )
1472        }))?;
1473        self.context.chain_id = Some(rpc_chain_id);
1474        self.steps.push(DoctorStep::pass(RPC, format!("chain id {rpc_chain_id}")));
1475        let chain_timestamp = fetch_chain_timestamp(&provider).await;
1476
1477        // Step 3: chain-id match + final entry selection.
1478        let subject = self.attempt(
1479            select_subject_for_chain(candidates, rpc_chain_id, root_account).map_err(|detail| {
1480                DoctorStep::fail(
1481                    CHAIN_ID,
1482                    detail,
1483                    "use the RPC for the chain the local entry was created on, or pass --root-account",
1484                )
1485            }),
1486        )?;
1487        let DoctorSubject { root_account, key_address, .. } = subject;
1488        let detail = if subject.entry.is_some() {
1489            format!(
1490                "local entry on chain {rpc_chain_id} matches RPC (root {root_account}, key {key_address})"
1491            )
1492        } else {
1493            format!(
1494                "using explicit root {root_account} and key {key_address} on RPC chain {rpc_chain_id}"
1495            )
1496        };
1497        self.steps.push(DoctorStep::pass(CHAIN_ID, detail));
1498        self.context.root_account = Some(root_account);
1499        self.context.key_address = Some(key_address);
1500
1501        // Step 4: local signing readiness.
1502        self.check(check_local_signing_readiness(&subject))?;
1503
1504        // Step 5: on-chain key state.
1505        let registration = match provider.get_keychain_key(root_account, key_address).await {
1506            Ok(info) if !info.keyId.is_zero() => {
1507                let key_type = abi_key_type(info.signatureType).map_or("unknown", key_type_label);
1508                self.steps.push(DoctorStep::pass(
1509                    KEY_REGISTRATION,
1510                    format!("provisioned, type {key_type}"),
1511                ));
1512                KeyRegistration::OnChain(info)
1513            }
1514            Ok(_) => {
1515                // A configurable account's authorization is tied to it by its onchain commitment.
1516                let signs_as_configurable_account = subject
1517                    .entry
1518                    .as_ref()
1519                    .and_then(|entry| entry.key_authorization.as_ref())
1520                    .is_some_and(|signed| signed.signature().as_configurable_account().is_some());
1521                let commitment = if signs_as_configurable_account {
1522                    config_commitment(&provider, root_account, BlockId::latest())
1523                        .await
1524                        .ok()
1525                        .flatten()
1526                } else {
1527                    None
1528                };
1529                let (signed, detail) = self.attempt(validate_pending_key_authorization(
1530                    &subject,
1531                    rpc_chain_id,
1532                    &chain_timestamp,
1533                    commitment,
1534                ))?;
1535                self.steps.push(DoctorStep::pass(KEY_REGISTRATION, detail));
1536                KeyRegistration::Pending(Box::new(signed))
1537            }
1538            Err(err) => {
1539                return self.check(DoctorStep::fail(
1540                    KEY_REGISTRATION,
1541                    format!("AccountKeychain.getKey failed: {err}"),
1542                    "verify the RPC supports the AccountKeychain precompile",
1543                ));
1544            }
1545        };
1546
1547        // Steps 6-7: revocation and expiry.
1548        let expiry = match &registration {
1549            KeyRegistration::OnChain(info) => {
1550                if info.isRevoked {
1551                    return self.check(DoctorStep::fail(
1552                        REVOCATION,
1553                        "key is revoked on-chain",
1554                        "authorize a new key or re-authorize this one",
1555                    ));
1556                }
1557                self.steps.push(DoctorStep::pass(REVOCATION, "active"));
1558                check_expiry(
1559                    (info.expiry != u64::MAX).then_some(info.expiry),
1560                    &chain_timestamp,
1561                    "",
1562                    "authorize a new key with a later expiry",
1563                )
1564            }
1565            KeyRegistration::Pending(signed) => {
1566                self.steps.push(DoctorStep::pass(
1567                    REVOCATION,
1568                    "not on-chain yet; key_authorization will provision a fresh key",
1569                ));
1570                check_expiry(
1571                    signed.authorization().expiry.map(|expiry| expiry.get()),
1572                    &chain_timestamp,
1573                    "key_authorization ",
1574                    "refresh the access key to get a later key_authorization expiry",
1575                )
1576            }
1577        };
1578        self.check(expiry)?;
1579
1580        // Steps 8-10: hardfork detection, spending limits, allowed calls (TIP-1011, T3+ only).
1581        let (step, hardfork) = check_hardfork(&provider).await;
1582        self.steps.push(step);
1583        let is_t3 = hardfork.map(|hardfork| hardfork.is_t3());
1584        let fee_token = self.context.fee_token;
1585        let (limits, pending) = match &registration {
1586            KeyRegistration::OnChain(info) => {
1587                (check_spending_limits(&provider, &subject, info, fee_token, is_t3).await, None)
1588            }
1589            KeyRegistration::Pending(signed) => (
1590                check_authorization_spending_limits(signed, fee_token, is_t3),
1591                Some(signed.authorization()),
1592            ),
1593        };
1594        self.steps.push(limits);
1595        self.steps.push(
1596            check_allowed_calls(&provider, &subject, pending, is_t3, to, selector, recipient).await,
1597        );
1598
1599        // Transaction-option diagnostics that affect access-key sends.
1600        self.steps.push(check_expiring_nonce(
1601            tempo,
1602            resolved_expires_at,
1603            &chain_timestamp,
1604            hardfork,
1605        ));
1606
1607        let (sponsorship, fee_payer) = check_sponsorship(tempo, root_account).await;
1608        let sponsor_failed = sponsorship.status == DoctorStatus::Fail;
1609        self.steps.push(sponsorship);
1610        let balance = if sponsor_failed && tempo.has_sponsor_submission() {
1611            DoctorStep::warn(
1612                FEE_TOKEN_BALANCE,
1613                "skipped; sponsorship config is invalid",
1614                "fix the sponsorship configuration before checking the fee payer balance",
1615            )
1616        } else {
1617            let (account, owner) = match fee_payer {
1618                Some(sponsor) => (sponsor, "sponsor"),
1619                None => (root_account, "root account"),
1620            };
1621            check_fee_token_balance(&provider, account, fee_token, owner).await
1622        };
1623        self.steps.push(balance);
1624        Some(())
1625    }
1626
1627    /// Renders the doctor report.
1628    fn finish(self) -> Result<()> {
1629        let Self { steps, context } = self;
1630        let count = |status| steps.iter().filter(|s| s.status == status).count();
1631        let failure_count = count(DoctorStatus::Fail);
1632        let warning_count = count(DoctorStatus::Warn);
1633        let no_failures = failure_count == 0;
1634        let healthy = no_failures && warning_count == 0;
1635
1636        if shell::is_json() {
1637            let status = if !no_failures {
1638                "fail"
1639            } else if !healthy {
1640                "warn"
1641            } else {
1642                "pass"
1643            };
1644            return print_json_success(json!({
1645                "context": context,
1646                "steps": steps,
1647                "status": status,
1648                "no_failures": no_failures,
1649                "healthy": healthy,
1650                "warning_count": warning_count,
1651                "failure_count": failure_count,
1652            }));
1653        }
1654
1655        for step in &steps {
1656            let marker = match step.status {
1657                DoctorStatus::Pass => "✓".green().to_string(),
1658                DoctorStatus::Warn => "!".yellow().to_string(),
1659                DoctorStatus::Fail => "✗".red().to_string(),
1660            };
1661            sh_println!("{marker} {:<22} {}", step.label, step.detail)?;
1662            if let Some(hint) = &step.hint {
1663                sh_println!("  {} {hint}", "hint:".dim())?;
1664            }
1665        }
1666        sh_println!()?;
1667        if healthy {
1668            sh_println!("{} access-key signing path looks healthy", "✓".green())
1669        } else if no_failures {
1670            sh_println!("{} access-key signing path has warnings (see above)", "!".yellow())
1671        } else {
1672            sh_println!("{} access-key signing path has issues (see above)", "✗".red())
1673        }
1674    }
1675}
1676
1677/// Step 1 helper: collect Tempo Accounts store candidates.
1678fn collect_local_candidates(
1679    key_address: Option<Address>,
1680    root_account: Option<Address>,
1681) -> Result<(DoctorStep, Vec<DoctorCandidate>), DoctorStep> {
1682    let explicit = key_address
1683        .zip(root_account)
1684        .map(|(key_address, root_account)| DoctorCandidate::explicit(root_account, key_address));
1685    let store_path = tempo_accounts_store_path_display();
1686
1687    let Some(store) = read_tempo_accounts_store() else {
1688        return match explicit {
1689            Some(candidate) => Ok((
1690                DoctorStep::pass(
1691                    ACCOUNTS_STORE,
1692                    format!("could not read {store_path}; using explicit root/key"),
1693                ),
1694                vec![candidate],
1695            )),
1696            None => Err(DoctorStep::fail(
1697                ACCOUNTS_STORE,
1698                format!("could not read Tempo Accounts store at {store_path}"),
1699                "run `cast tempo login` or pass both KEY_ADDRESS and --root-account",
1700            )),
1701        };
1702    };
1703
1704    let matches: Vec<_> = store
1705        .keys
1706        .into_iter()
1707        .filter(|entry| {
1708            (key_address.is_some() || root_account.is_some())
1709                && key_address.is_none_or(|k| entry.key_address == k)
1710                && root_account.is_none_or(|r| entry.wallet_address == r)
1711        })
1712        .collect();
1713
1714    if matches.is_empty() {
1715        if let Some(candidate) = explicit {
1716            let detail = format!(
1717                "no local entry for key {} and root {}; using explicit root/key",
1718                candidate.key_address, candidate.root_account
1719            );
1720            return Ok((DoctorStep::pass(ACCOUNTS_STORE, detail), vec![candidate]));
1721        }
1722        let (descriptor, hint) = match (key_address, root_account) {
1723            (Some(k), None) => {
1724                (format!("key {k}"), "pass --root-account to diagnose an explicit key/root pair")
1725            }
1726            (None, Some(r)) => (
1727                format!("root account {r}"),
1728                "pass KEY_ADDRESS to diagnose a key absent from the Accounts store",
1729            ),
1730            _ => (
1731                "the requested key".to_string(),
1732                "run `cast tempo login` to add a key to ~/.tempo/wallet/store.json",
1733            ),
1734        };
1735        return Err(DoctorStep::fail(
1736            ACCOUNTS_STORE,
1737            format!("no entry for {descriptor} in {store_path}"),
1738            hint,
1739        ));
1740    }
1741
1742    let count = matches.len();
1743    let candidates = matches.into_iter().map(DoctorCandidate::from_entry).chain(explicit).collect();
1744    Ok((
1745        DoctorStep::pass(ACCOUNTS_STORE, format!("{count} candidate(s) in {store_path}")),
1746        candidates,
1747    ))
1748}
1749
1750/// Step 3 helper: filter candidates to the RPC chain id and pick a single entry.
1751fn select_subject_for_chain(
1752    candidates: Vec<DoctorCandidate>,
1753    rpc_chain_id: u64,
1754    explicit_root: Option<Address>,
1755) -> Result<DoctorSubject, String> {
1756    let local_chain_ids: Vec<u64> = candidates.iter().filter_map(|e| e.chain_id).collect();
1757    let chain_matched: Vec<_> = candidates
1758        .into_iter()
1759        .filter(|entry| entry.chain_id.is_none_or(|chain_id| chain_id == rpc_chain_id))
1760        .collect();
1761
1762    let Some(first) = chain_matched.first() else {
1763        return Err(format!(
1764            "no local entry matches RPC chain id {rpc_chain_id} (local entries on {local_chain_ids:?})"
1765        ));
1766    };
1767
1768    // If multiple entries belong to different roots and the user did not pin one, refuse to guess.
1769    if explicit_root.is_none()
1770        && chain_matched.iter().any(|entry| entry.root_account != first.root_account)
1771    {
1772        return Err(
1773            "multiple local entries match this chain across different root accounts; pass --root-account"
1774                .to_string(),
1775        );
1776    }
1777
1778    let explicit = chain_matched.iter().any(|entry| entry.explicit);
1779    // Prefer a locally signable store entry over metadata-only records.
1780    let preferred = chain_matched.iter().position(DoctorCandidate::has_inline_key).unwrap_or(0);
1781    let entry = chain_matched.into_iter().nth(preferred).expect("non-empty");
1782    Ok(DoctorSubject {
1783        root_account: entry.root_account,
1784        key_address: entry.key_address,
1785        entry: entry.entry,
1786        explicit,
1787    })
1788}
1789
1790/// Step 4 helper: verify whether the local side can actually sign as the key.
1791fn check_local_signing_readiness(subject: &DoctorSubject) -> DoctorStep {
1792    let Some(entry) = &subject.entry else {
1793        return DoctorStep::warn(
1794            LOCAL_SIGNING,
1795            "not verified; using explicit root/key absent from the Accounts store",
1796            "pass --tempo.access-key in the send command or run `cast tempo login`",
1797        );
1798    };
1799    if entry.has_inline_key() {
1800        DoctorStep::pass(
1801            LOCAL_SIGNING,
1802            format!("inline {} key available", key_type_name(entry.key_type)),
1803        )
1804    } else if subject.explicit {
1805        DoctorStep::warn(
1806            LOCAL_SIGNING,
1807            "local entry has no inline access-key private key; explicit root/key can still use --tempo.access-key",
1808            "pass --tempo.access-key in the send command or refresh the local key material",
1809        )
1810    } else {
1811        DoctorStep::fail(
1812            LOCAL_SIGNING,
1813            "local entry has no inline access-key private key",
1814            "run `cast tempo login` again, restore the key material, or pass --tempo.access-key when sending",
1815        )
1816    }
1817}
1818
1819/// Validates the local pending `key_authorization`, returning it with its pass detail.
1820///
1821/// `commitment` is the root account's onchain configuration commitment, which a key authorization
1822/// signed by a configurable account's owners must match; it is zero before the account registers.
1823fn validate_pending_key_authorization(
1824    subject: &DoctorSubject,
1825    rpc_chain_id: u64,
1826    chain_timestamp: &ChainTimestamp,
1827    commitment: Option<B256>,
1828) -> Result<(SignedKeyAuthorization, String), DoctorStep> {
1829    let fail = |detail: String, hint: &str| DoctorStep::fail(KEY_REGISTRATION, detail, hint);
1830    let not_registered = || {
1831        format!(
1832            "key {} is not registered for root account {}",
1833            subject.key_address, subject.root_account
1834        )
1835    };
1836
1837    let Some(entry) = &subject.entry else {
1838        return Err(fail(
1839            not_registered(),
1840            "authorize the key with `cast keychain authorize <KEY>` or add a local key_authorization",
1841        ));
1842    };
1843    let Some(signed) = entry.key_authorization.clone() else {
1844        return Err(fail(
1845            not_registered(),
1846            "authorize the key with `cast keychain authorize <KEY>` or refresh the local key_authorization",
1847        ));
1848    };
1849    let auth = signed.authorization();
1850
1851    if auth.key_id != subject.key_address {
1852        return Err(fail(
1853            format!(
1854                "local key_authorization is for key {}, expected {}",
1855                auth.key_id, subject.key_address
1856            ),
1857            "refresh the access key for this root/key pair",
1858        ));
1859    }
1860    if auth.chain_id != rpc_chain_id {
1861        return Err(fail(
1862            format!(
1863                "local key_authorization is for chain {}, RPC is chain {rpc_chain_id}",
1864                auth.chain_id
1865            ),
1866            "use the RPC for the chain the authorization was created on",
1867        ));
1868    }
1869    if entry.key_type != KeyType::from(auth.key_type) {
1870        return Err(fail(
1871            format!(
1872                "local key type {} does not match key_authorization type {}",
1873                key_type_label(entry.key_type),
1874                key_type_label(auth.key_type.into())
1875            ),
1876            "refresh the local key entry so its key material and authorization agree",
1877        ));
1878    }
1879    if let Some(expiry) = auth.expiry
1880        && let Some(now) = chain_timestamp.timestamp()
1881        && expiry.get() <= now
1882    {
1883        return Err(fail(
1884            format!(
1885                "local key_authorization expired {}",
1886                format_relative_timestamp_from(expiry.get(), now)
1887            ),
1888            "refresh the access key to get a later key_authorization expiry",
1889        ));
1890    }
1891    let signer = match signed.signature().as_configurable_account() {
1892        Some(signature) => commitment
1893            .ok_or_else(|| {
1894                eyre::eyre!(
1895                    "could not read the configuration commitment of {}",
1896                    signature.account()
1897                )
1898            })
1899            .and_then(|commitment| {
1900                signature.validate_account_commitment(commitment).map_err(ca_error)
1901            })
1902            .and_then(|()| signature.verify_approvals(signed.signature_hash()).map_err(ca_error))
1903            .map(|()| signature.account()),
1904        None => signed.recover_signer().map_err(ca_error),
1905    };
1906    match signer {
1907        Ok(recovered) if recovered == subject.root_account => {}
1908        Ok(recovered) => {
1909            return Err(fail(
1910                format!(
1911                    "local key_authorization recovers signer {recovered}, expected root {}",
1912                    subject.root_account
1913                ),
1914                "refresh the authorization with the correct root account",
1915            ));
1916        }
1917        Err(err) => {
1918            return Err(fail(
1919                format!("local key_authorization signature could not be verified: {err}"),
1920                "refresh the access key with `cast tempo login`",
1921            ));
1922        }
1923    }
1924
1925    let expiry = auth.expiry.map_or_else(
1926        || "never expires".to_string(),
1927        |expiry| {
1928            let expiry = expiry.get();
1929            let relative = match chain_timestamp.timestamp() {
1930                Some(now) => format_relative_timestamp_from(expiry, now),
1931                None => format_relative_timestamp(expiry),
1932            };
1933            format!("{relative} ({})", format_timestamp_iso(expiry))
1934        },
1935    );
1936    let witness = auth.witness().map(|witness| format!(", witness {witness}")).unwrap_or_default();
1937    let detail = format!(
1938        "not on-chain; local key_authorization can provision atomically, type {}, expiry {expiry}{witness}",
1939        key_type_label(auth.key_type.into()),
1940    );
1941    Ok((signed, detail))
1942}
1943
1944async fn fetch_chain_timestamp<P: Provider<TempoNetwork>>(provider: &P) -> ChainTimestamp {
1945    match provider.get_block(BlockId::latest()).await {
1946        Ok(Some(block)) => ChainTimestamp::Known(block.header.timestamp()),
1947        Ok(None) => ChainTimestamp::Unknown {
1948            detail: "latest block not found; chain timestamp unavailable".to_string(),
1949            hint: "verify the RPC can serve latest block data",
1950        },
1951        Err(err) => ChainTimestamp::Unknown {
1952            detail: format!("latest block query failed: {err}"),
1953            hint: "validity windows and expiries could not be checked against chain time",
1954        },
1955    }
1956}
1957
1958/// Expiry check shared by on-chain keys (`prefix` empty) and pending authorizations
1959/// (`prefix` = `"key_authorization "`). `None` means the key never expires.
1960fn check_expiry(
1961    expiry: Option<u64>,
1962    chain_timestamp: &ChainTimestamp,
1963    prefix: &str,
1964    hint: &str,
1965) -> DoctorStep {
1966    let Some(expiry) = expiry else {
1967        return DoctorStep::pass(EXPIRY, format!("{prefix}never expires"));
1968    };
1969    let subject = if prefix.is_empty() { "key " } else { prefix };
1970    let now = match chain_timestamp.get(EXPIRY, format!("{subject}expiry not checked")) {
1971        Ok(now) => now,
1972        Err(step) => return step,
1973    };
1974    let relative = format_relative_timestamp_from(expiry, now);
1975    if expiry <= now {
1976        DoctorStep::fail(EXPIRY, format!("{prefix}expired {relative}"), hint)
1977    } else {
1978        DoctorStep::pass(EXPIRY, format!("{prefix}{relative} ({})", format_timestamp_iso(expiry)))
1979    }
1980}
1981
1982async fn check_hardfork<P: Provider<TempoNetwork>>(
1983    provider: &P,
1984) -> (DoctorStep, Option<TempoHardfork>) {
1985    match active_tempo_hardfork(provider).await {
1986        Ok(hardfork) if hardfork.is_t3() => {
1987            (DoctorStep::pass(HARDFORK, "Tempo T3 active"), Some(hardfork))
1988        }
1989        Ok(hardfork) => {
1990            (DoctorStep::pass(HARDFORK, "pre-T3; TIP-1011 scopes not enforced"), Some(hardfork))
1991        }
1992        Err(err) => (
1993            DoctorStep::warn(
1994                HARDFORK,
1995                format!("could not determine Tempo T3 activation: {err}"),
1996                "TIP-1011 allowed-call and T3 spending-period checks will be skipped",
1997            ),
1998            None,
1999        ),
2000    }
2001}
2002
2003/// Step 9 helper: spending limits of an on-chain key.
2004async fn check_spending_limits<P: Provider<TempoNetwork>>(
2005    provider: &P,
2006    subject: &DoctorSubject,
2007    info: &KeyInfo,
2008    fee_token: Address,
2009    is_t3: Option<bool>,
2010) -> DoctorStep {
2011    let Some(is_t3) = is_t3 else {
2012        return DoctorStep::warn(
2013            SPENDING_LIMITS,
2014            "skipped; hardfork unknown",
2015            HARDFORK_UNKNOWN_HINT,
2016        );
2017    };
2018    if !info.enforceLimits {
2019        return DoctorStep::pass(SPENDING_LIMITS, "limits not enforced for this key");
2020    }
2021
2022    let local_limits = subject.entry.as_ref().map_or(&[][..], |entry| entry.limits.as_slice());
2023    // Token universe: local-entry limits ∪ {fee_token}.
2024    let mut tokens: Vec<Address> = local_limits.iter().map(|l| l.currency).collect();
2025    if !tokens.contains(&fee_token) {
2026        tokens.push(fee_token);
2027    }
2028
2029    let mut lines = Vec::new();
2030    let mut any_zero = false;
2031    for token in tokens {
2032        let (remaining, period_end) = match remaining_limit(
2033            provider,
2034            subject.root_account,
2035            subject.key_address,
2036            token,
2037            is_t3,
2038        )
2039        .await
2040        {
2041            Ok(limit) => limit,
2042            Err(err) => {
2043                return DoctorStep::warn(
2044                    SPENDING_LIMITS,
2045                    format!("{} query failed: {err}", address_label(token)),
2046                    "verify the AccountKeychain precompile is reachable",
2047                );
2048            }
2049        };
2050        any_zero |= remaining.is_zero();
2051        let configured =
2052            local_limits.iter().find(|l| l.currency == token).map_or("?", |l| l.limit.as_str());
2053        lines.push(format!(
2054            "{} remaining {remaining} / {configured}{}",
2055            address_label(token),
2056            format_period_suffix(period_end)
2057        ));
2058    }
2059
2060    let detail = lines.join("; ");
2061    if any_zero {
2062        DoctorStep::warn(
2063            SPENDING_LIMITS,
2064            detail,
2065            "raise the limit (e.g. `cast keychain ul ...`) or wait for the window reset",
2066        )
2067    } else {
2068        DoctorStep::pass(SPENDING_LIMITS, detail)
2069    }
2070}
2071
2072/// Step 9 helper: spending limits of a pending `key_authorization`.
2073fn check_authorization_spending_limits(
2074    signed: &SignedKeyAuthorization,
2075    fee_token: Address,
2076    is_t3: Option<bool>,
2077) -> DoctorStep {
2078    let auth = signed.authorization();
2079    if is_t3.is_none() && auth.has_periodic_limits() {
2080        return DoctorStep::warn(
2081            SPENDING_LIMITS,
2082            "skipped; hardfork unknown and key_authorization uses periodic limits",
2083            HARDFORK_UNKNOWN_HINT,
2084        );
2085    }
2086    if is_t3 == Some(false) && !auth.is_legacy_compatible() {
2087        return DoctorStep::fail(
2088            SPENDING_LIMITS,
2089            "key_authorization uses T3-only limits or call scopes on a pre-T3 chain",
2090            "use a T3 RPC or refresh the authorization with legacy-compatible restrictions",
2091        );
2092    }
2093
2094    match auth.limits.as_deref() {
2095        None => DoctorStep::pass(SPENDING_LIMITS, "limits not enforced by key_authorization"),
2096        Some([]) => DoctorStep::warn(
2097            SPENDING_LIMITS,
2098            "key_authorization allows no token spending",
2099            "refresh the access key with spending limits if the transaction spends TIP-20 tokens",
2100        ),
2101        Some(limits) => {
2102            let mut lines: Vec<String> = limits
2103                .iter()
2104                .map(|limit| {
2105                    let period = if limit.period == 0 {
2106                        String::new()
2107                    } else {
2108                        format!(" per {}s", limit.period)
2109                    };
2110                    format!("{} limit {}{period}", address_label(limit.token), limit.limit)
2111                })
2112                .collect();
2113            let fee_limit = limits.iter().find(|limit| limit.token == fee_token);
2114            if fee_limit.is_none() {
2115                lines.push(format!(
2116                    "{} not listed in key_authorization limits",
2117                    address_label(fee_token)
2118                ));
2119            }
2120            let detail = lines.join("; ");
2121            match fee_limit {
2122                None => DoctorStep::warn(
2123                    SPENDING_LIMITS,
2124                    detail,
2125                    "refresh the access key with a limit for the selected fee token",
2126                ),
2127                Some(limit) if limit.limit.is_zero() => DoctorStep::warn(
2128                    SPENDING_LIMITS,
2129                    detail,
2130                    "raise the fee-token limit before sending with this authorization",
2131                ),
2132                Some(_) => DoctorStep::pass(SPENDING_LIMITS, detail),
2133            }
2134        }
2135    }
2136}
2137
2138/// Step 10 helper: allowed calls (TIP-1011) of the on-chain key, or of `pending` when the key is
2139/// not registered yet.
2140async fn check_allowed_calls<P: Provider<TempoNetwork>>(
2141    provider: &P,
2142    subject: &DoctorSubject,
2143    pending: Option<&KeyAuthorization>,
2144    is_t3: Option<bool>,
2145    to: Option<Address>,
2146    selector: Option<[u8; 4]>,
2147    recipient: Option<Address>,
2148) -> DoctorStep {
2149    let Some(is_t3) = is_t3 else {
2150        return DoctorStep::warn(ALLOWED_CALLS, "skipped; hardfork unknown", HARDFORK_UNKNOWN_HINT);
2151    };
2152    if !is_t3 {
2153        return DoctorStep::pass(ALLOWED_CALLS, "TIP-1011 not enforced before T3");
2154    }
2155
2156    let scopes = match pending {
2157        Some(auth) => {
2158            let Some(scopes) = auth.allowed_calls.as_deref() else {
2159                return DoctorStep::pass(ALLOWED_CALLS, "any call permitted by key_authorization");
2160            };
2161            scopes.iter().cloned().map(Into::into).collect()
2162        }
2163        None => match provider
2164            .account_keychain()
2165            .getAllowedCalls(subject.root_account, subject.key_address)
2166            .call()
2167            .await
2168        {
2169            Ok(allowed) if !allowed.isScoped => {
2170                return DoctorStep::pass(ALLOWED_CALLS, "any call permitted");
2171            }
2172            Ok(allowed) => allowed.scopes,
2173            Err(err) => {
2174                return DoctorStep::warn(
2175                    ALLOWED_CALLS,
2176                    format!("getAllowedCalls failed: {err}"),
2177                    "verify the AccountKeychain precompile is reachable",
2178                );
2179            }
2180        },
2181    };
2182    diagnose_allowed_scopes(&scopes, to, selector, recipient)
2183}
2184
2185fn diagnose_allowed_scopes(
2186    scopes: &[CallScope],
2187    to: Option<Address>,
2188    selector: Option<[u8; 4]>,
2189    recipient: Option<Address>,
2190) -> DoctorStep {
2191    if scopes.is_empty() {
2192        let detail = "scoped, but no targets permitted";
2193        return if to.is_some() && selector.is_some() {
2194            DoctorStep::fail(ALLOWED_CALLS, detail, WIDEN_POLICY_HINT)
2195        } else {
2196            DoctorStep::warn(ALLOWED_CALLS, detail, WIDEN_POLICY_HINT)
2197        };
2198    }
2199    let Some(to) = to else {
2200        return DoctorStep::pass(
2201            ALLOWED_CALLS,
2202            format!(
2203                "scoped to {} target(s); pass --to/--selector to test a specific call",
2204                scopes.len()
2205            ),
2206        );
2207    };
2208    let Some(selector) = selector else {
2209        // --to without --selector: report whether the target is in scope at all.
2210        return if scopes.iter().any(|s| s.target == to) {
2211            DoctorStep::pass(
2212                ALLOWED_CALLS,
2213                format!("target {to} is in scope; pass --selector to test the function"),
2214            )
2215        } else {
2216            DoctorStep::warn(
2217                ALLOWED_CALLS,
2218                format!("target {to} not in any allowed scope"),
2219                WIDEN_POLICY_HINT,
2220            )
2221        };
2222    };
2223
2224    match match_allowed_call(scopes, to, selector, recipient) {
2225        AllowedCallMatch::Allowed(detail) => DoctorStep::pass(ALLOWED_CALLS, detail),
2226        AllowedCallMatch::Denied(reason) => {
2227            DoctorStep::fail(ALLOWED_CALLS, reason, WIDEN_POLICY_HINT)
2228        }
2229        AllowedCallMatch::RecipientRestricted(recipients) => DoctorStep::pass(
2230            ALLOWED_CALLS,
2231            format!(
2232                "selector {} on {} allowed only for {}; pass --recipient to verify exact match",
2233                format_selector(&selector),
2234                address_label_with_address(to),
2235                format_recipients(&recipients)
2236            ),
2237        ),
2238    }
2239}
2240
2241/// Pure TIP-1011 matching logic.
2242fn match_allowed_call(
2243    scopes: &[CallScope],
2244    to: Address,
2245    selector: [u8; 4],
2246    recipient: Option<Address>,
2247) -> AllowedCallMatch {
2248    let target = address_label_with_address(to);
2249    let matching_scopes: Vec<_> = scopes.iter().filter(|scope| scope.target == to).collect();
2250    if matching_scopes.is_empty() {
2251        return AllowedCallMatch::Denied(format!("target {to} not in any allowed scope"));
2252    }
2253    if matching_scopes.iter().any(|scope| scope.selectorRules.is_empty()) {
2254        return AllowedCallMatch::Allowed(format!("any selector on {target} permitted"));
2255    }
2256
2257    let selector_str = format_selector(&selector);
2258    let matching_rules: Vec<_> = matching_scopes
2259        .iter()
2260        .flat_map(|scope| &scope.selectorRules)
2261        .filter(|rule| rule.selector.0 == selector)
2262        .collect();
2263    if matching_rules.is_empty() {
2264        return AllowedCallMatch::Denied(format!(
2265            "selector {selector_str} on {target} not in allowed list"
2266        ));
2267    }
2268    if matching_rules.iter().any(|rule| rule.recipients.is_empty()) {
2269        return AllowedCallMatch::Allowed(format!(
2270            "{selector_str} on {target} permitted (any recipient)"
2271        ));
2272    }
2273
2274    match recipient {
2275        Some(r) if matching_rules.iter().any(|rule| rule.recipients.contains(&r)) => {
2276            AllowedCallMatch::Allowed(format!(
2277                "{selector_str} on {target} to recipient {r} permitted"
2278            ))
2279        }
2280        Some(r) => AllowedCallMatch::Denied(format!(
2281            "recipient {r} not in allowed list for {selector_str} on {target}"
2282        )),
2283        None => {
2284            let mut recipients = Vec::new();
2285            for recipient in matching_rules.iter().flat_map(|rule| &rule.recipients) {
2286                if !recipients.contains(recipient) {
2287                    recipients.push(*recipient);
2288                }
2289            }
2290            AllowedCallMatch::RecipientRestricted(recipients)
2291        }
2292    }
2293}
2294
2295/// Fee-token balance of the account paying for the transaction.
2296async fn check_fee_token_balance<P: Provider<TempoNetwork>>(
2297    provider: &P,
2298    account: Address,
2299    fee_token: Address,
2300    owner_label: &str,
2301) -> DoctorStep {
2302    let token = address_label(fee_token);
2303    match ITIP20::new(fee_token, provider).balanceOf(account).call().await {
2304        Ok(balance) if balance.is_zero() => DoctorStep::warn(
2305            FEE_TOKEN_BALANCE,
2306            format!("0 {token} on {owner_label} {account}"),
2307            format!("fund {owner_label} {account} with {token}"),
2308        ),
2309        Ok(balance) => DoctorStep::pass(
2310            FEE_TOKEN_BALANCE,
2311            format!("{balance} {token} on {owner_label} {account}"),
2312        ),
2313        Err(err) => DoctorStep::warn(
2314            FEE_TOKEN_BALANCE,
2315            format!("balanceOf failed: {err}"),
2316            "verify --fee-token points to a TIP-20 token",
2317        ),
2318    }
2319}
2320
2321/// Validate TIP-1009 expiring-nonce options, if supplied.
2322fn check_expiring_nonce(
2323    tempo: &TempoOpts,
2324    resolved_expires_at: Option<u64>,
2325    chain_timestamp: &ChainTimestamp,
2326    hardfork: Option<TempoHardfork>,
2327) -> DoctorStep {
2328    if !tempo.expiring_nonce && tempo.valid_before.is_none() && tempo.valid_after.is_none() {
2329        return DoctorStep::pass(EXPIRING_NONCE, "not requested");
2330    }
2331    match chain_timestamp.get(EXPIRING_NONCE, "validity window not checked") {
2332        Ok(now) => check_expiring_nonce_window(tempo, resolved_expires_at, now, hardfork),
2333        Err(step) => step,
2334    }
2335}
2336
2337/// Checks the validity window against the chain timestamp. The upper bound depends on the active
2338/// hardfork and is skipped when it is unknown.
2339fn check_expiring_nonce_window(
2340    tempo: &TempoOpts,
2341    resolved_expires_at: Option<u64>,
2342    chain_timestamp: u64,
2343    hardfork: Option<TempoHardfork>,
2344) -> DoctorStep {
2345    let valid_before = tempo.valid_before;
2346    let valid_after = tempo.valid_after;
2347
2348    if let (Some(after), Some(before)) = (valid_after, valid_before)
2349        && after >= before
2350    {
2351        return DoctorStep::fail(
2352            EXPIRING_NONCE,
2353            format!("valid-after {after} is not before valid-before {before}"),
2354            "choose a valid window where valid-after < valid-before",
2355        );
2356    }
2357
2358    if let Some(before) = valid_before {
2359        if before <= chain_timestamp {
2360            return DoctorStep::fail(
2361                EXPIRING_NONCE,
2362                format!(
2363                    "valid-before {} is expired at chain timestamp {chain_timestamp}",
2364                    format_timestamp_iso(before)
2365                ),
2366                "use a later --tempo.valid-before or rerun with --tempo.expires",
2367            );
2368        }
2369        let ttl = before - chain_timestamp;
2370        if ttl <= 3 {
2371            return DoctorStep::fail(
2372                EXPIRING_NONCE,
2373                format!(
2374                    "valid-before must be more than 3s after chain timestamp {chain_timestamp}; current ttl is {ttl}s"
2375                ),
2376                "use a later --tempo.valid-before or rerun with --tempo.expires",
2377            );
2378        }
2379        if ttl <= 5 {
2380            return DoctorStep::warn(
2381                EXPIRING_NONCE,
2382                format!("valid for only {ttl}s at chain timestamp {chain_timestamp}"),
2383                "use a larger validity window before signing",
2384            );
2385        }
2386        if let Some(max_expiry_secs) =
2387            hardfork.map(|hardfork| hardfork.expiring_nonce_max_expiry_secs())
2388            && ttl > max_expiry_secs
2389        {
2390            return if resolved_expires_at.is_some() {
2391                DoctorStep::warn(
2392                    EXPIRING_NONCE,
2393                    format!(
2394                        "--tempo.expires resolved to a deadline {ttl}s ahead of chain timestamp {chain_timestamp}; the active hardfork allows at most {max_expiry_secs}s"
2395                    ),
2396                    "use a shorter --tempo.expires or check local clock/RPC timestamp skew",
2397                )
2398            } else {
2399                DoctorStep::warn(
2400                    EXPIRING_NONCE,
2401                    format!(
2402                        "valid-before is {ttl}s ahead of chain timestamp {chain_timestamp}; expiring nonce transactions must expire within {max_expiry_secs}s on the active hardfork"
2403                    ),
2404                    "prefer --tempo.expires for bounded retry-safe sends",
2405                )
2406            };
2407        }
2408    }
2409
2410    if let Some(after) = valid_after
2411        && after > chain_timestamp
2412    {
2413        return DoctorStep::warn(
2414            EXPIRING_NONCE,
2415            format!("transaction is not valid until {}", format_timestamp_iso(after)),
2416            "wait until valid-after or choose an earlier lower bound",
2417        );
2418    }
2419
2420    if (valid_before.is_some() || valid_after.is_some()) && !tempo.expiring_nonce {
2421        return DoctorStep::warn(
2422            EXPIRING_NONCE,
2423            "validity window set without --tempo.expiring-nonce",
2424            "use --tempo.expiring-nonce or --tempo.expires so nonce_key is set to the expiring lane",
2425        );
2426    }
2427
2428    let mut detail = format!("enabled at chain timestamp {chain_timestamp}");
2429    if let Some(before) = valid_before {
2430        detail.push_str(&format!(", valid-before {}", format_timestamp_iso(before)));
2431    }
2432    if let Some(after) = valid_after {
2433        detail.push_str(&format!(", valid-after {}", format_timestamp_iso(after)));
2434    }
2435    if let Some(expires_at) = resolved_expires_at {
2436        detail.push_str(&format!(
2437            ", --tempo.expires resolved to {}",
2438            format_timestamp_iso(expires_at)
2439        ));
2440    }
2441    DoctorStep::pass(EXPIRING_NONCE, detail)
2442}
2443
2444/// Validate sponsorship configuration, if supplied; returns the step and the fee payer.
2445async fn check_sponsorship(tempo: &TempoOpts, sender: Address) -> (DoctorStep, Option<Address>) {
2446    if tempo.print_sponsor_hash {
2447        return (
2448            DoctorStep::pass(
2449                SPONSORSHIP,
2450                "--tempo.print-sponsor-hash requested, but doctor has no concrete tx payload",
2451            ),
2452            None,
2453        );
2454    }
2455    let not_requested = || (DoctorStep::pass(SPONSORSHIP, "not requested"), None);
2456    if !tempo.has_sponsor_submission() {
2457        return not_requested();
2458    }
2459    let sponsor = match tempo.sponsor_config().await {
2460        Ok(Some(sponsor)) => sponsor.sponsor(),
2461        Ok(None) => return not_requested(),
2462        Err(err) => {
2463            return (
2464                DoctorStep::fail(
2465                    SPONSORSHIP,
2466                    format!(
2467                        "invalid sponsor config: {}",
2468                        sanitize_sponsor_config_error(&err.to_string(), tempo)
2469                    ),
2470                    "pass --tempo.sponsor with either --tempo.sponsor-signer or --tempo.sponsor-sig",
2471                ),
2472                None,
2473            );
2474        }
2475    };
2476
2477    let step = if sponsor == sender {
2478        DoctorStep::fail(
2479            SPONSORSHIP,
2480            format!("sponsor {sponsor} equals transaction sender {sender}"),
2481            "use a different fee payer for sponsored transactions",
2482        )
2483    } else if tempo.sponsor_sig.is_some() {
2484        DoctorStep::warn(
2485            SPONSORSHIP,
2486            format!("signature syntax parsed for sponsor {sponsor}"),
2487            "doctor cannot recover fee_payer_signature without the exact transaction digest",
2488        )
2489    } else {
2490        DoctorStep::pass(SPONSORSHIP, format!("sponsor signer configured for {sponsor}"))
2491    };
2492    (step, Some(sponsor))
2493}
2494
2495fn sanitize_sponsor_config_error(message: &str, tempo: &TempoOpts) -> String {
2496    let mut sanitized = message.to_string();
2497    if let Some(spec) = tempo.sponsor_signer.as_deref()
2498        && spec.starts_with("private-key://")
2499    {
2500        sanitized = sanitized.replace(spec, "private-key://<redacted>");
2501    }
2502    redact_private_key_uri_tokens(&sanitized)
2503}
2504
2505fn redact_private_key_uri_tokens(message: &str) -> String {
2506    const PREFIX: &str = "private-key://";
2507    let mut redacted = String::with_capacity(message.len());
2508    let mut rest = message;
2509    while let Some(idx) = rest.find(PREFIX) {
2510        redacted.push_str(&rest[..idx + PREFIX.len()]);
2511        redacted.push_str("<redacted>");
2512        let after_prefix = &rest[idx + PREFIX.len()..];
2513        let end = after_prefix
2514            .find(|c: char| c.is_whitespace() || matches!(c, '`' | '\'' | '"' | ',' | ';' | ')'))
2515            .unwrap_or(after_prefix.len());
2516        rest = &after_prefix[end..];
2517    }
2518    redacted.push_str(rest);
2519    redacted
2520}
2521
2522/// `cast keychain authorize` / `cast keychain auth` — authorize a key on-chain.
2523#[allow(clippy::too_many_arguments)]
2524async fn run_authorize(
2525    key_address: Address,
2526    key_type: SignatureType,
2527    expiry: u64,
2528    enforce_limits: bool,
2529    limits: Vec<TokenLimit>,
2530    allowed_calls: Vec<CallScope>,
2531    scopes_present: bool,
2532    witness: Option<B256>,
2533    admin: bool,
2534    tx_opts: TransactionOpts,
2535    send_tx: SendTxOpts,
2536    force: bool,
2537) -> Result<()> {
2538    let enforce = enforce_limits || !limits.is_empty();
2539    let (_, provider) = tempo_provider(&send_tx.eth.rpc)?;
2540    if key_type == SignatureType::ConfigurableAccount {
2541        require_hardfork(
2542            &provider,
2543            TempoHardfork::T14,
2544            "a configurable account access key requires the Tempo T14 hardfork",
2545        )
2546        .await?;
2547    }
2548
2549    // TIP-1137 deprecates admin keys from T14, the hardfork that adds configurable accounts.
2550    eyre::ensure!(
2551        !(admin && tx_opts.tempo.has_configurable_account_options()),
2552        "--admin cannot be combined with --tempo.configurable-account or \
2553         --tempo.configurable-access-key"
2554    );
2555
2556    // T6 admin keys are key-management only and use a dedicated precompile entrypoint.
2557    if admin {
2558        let hardfork = active_tempo_hardfork(&provider).await?;
2559        eyre::ensure!(hardfork.is_t6(), "--admin requires a Tempo T6-capable AccountKeychain RPC");
2560        // From T14 the precompile rejects `authorizeAdminKey` with a bare `InvalidKeyId()`.
2561        eyre::ensure!(
2562            !hardfork.is_t14(),
2563            "--admin is not supported on Tempo T14 or later: TIP-1137 retires admin keys; \
2564             authorize a regular access key without --admin instead"
2565        );
2566        // u64::MAX is the no-expiry default; anything else is an explicit expiry admin keys reject.
2567        eyre::ensure!(expiry == u64::MAX, "--admin cannot be combined with an explicit --expiry");
2568        eyre::ensure!(
2569            !enforce,
2570            "--admin cannot be combined with spending limits (--enforce-limits / --limit)"
2571        );
2572        eyre::ensure!(
2573            !scopes_present,
2574            "--admin cannot be combined with call scopes (--scope / --scopes)"
2575        );
2576
2577        // `authorizeAdminKey` requires a witness argument; omitting `--witness` submits bytes32(0).
2578        let call = authorizeAdminKeyCall {
2579            keyId: key_address,
2580            signatureType: key_type,
2581            witness: witness.unwrap_or(B256::ZERO),
2582        };
2583        return send_keychain_call(&call, tx_opts, &send_tx, force).await;
2584    }
2585
2586    let is_t3 = is_tempo_hardfork_active(&provider, TempoHardfork::T3).await?;
2587    if witness.is_some() {
2588        require_hardfork(
2589            &provider,
2590            TempoHardfork::T5,
2591            "--witness requires a Tempo T5-capable AccountKeychain RPC",
2592        )
2593        .await?;
2594    }
2595
2596    let calldata = if is_t3 {
2597        let config = KeyRestrictions {
2598            expiry,
2599            enforceLimits: enforce,
2600            limits,
2601            allowAnyCalls: !scopes_present,
2602            allowedCalls: allowed_calls,
2603        };
2604        match witness {
2605            Some(witness) => authorizeKeyWithWitnessCall {
2606                keyId: key_address,
2607                signatureType: key_type,
2608                config,
2609                witness,
2610            }
2611            .abi_encode(),
2612            None => authorizeKeyCall { keyId: key_address, signatureType: key_type, config }
2613                .abi_encode(),
2614        }
2615    } else {
2616        // Legacy (pre-T3) authorizeKey(address,SignatureType,uint64,bool,LegacyTokenLimit[])
2617        eyre::ensure!(
2618            !scopes_present,
2619            "call scopes (--scope / --scopes) require a Tempo T3-capable chain"
2620        );
2621        if let Some(limit) = limits.iter().find(|limit| limit.period != 0) {
2622            eyre::bail!(
2623                "legacy AccountKeychain authorization does not support periodic limits; remove \
2624                 the period from --limit {}:{}:{} or use a Tempo T3-capable chain",
2625                limit.token,
2626                limit.amount,
2627                limit.period
2628            );
2629        }
2630        legacyAuthorizeKeyCall {
2631            keyId: key_address,
2632            signatureType: key_type,
2633            expiry,
2634            enforceLimits: enforce,
2635            limits: limits
2636                .into_iter()
2637                .map(|l| LegacyTokenLimit { token: l.token, amount: l.amount })
2638                .collect(),
2639        }
2640        .abi_encode()
2641    };
2642
2643    if tx_opts.tempo.has_configurable_account_options() {
2644        return send_keychain_tx_as_configurable_account(calldata, tx_opts, &send_tx, force).await;
2645    }
2646    send_keychain_tx(calldata, tx_opts, &send_tx, None, force).await?;
2647    Ok(())
2648}
2649
2650async fn run_key_auth_sign(
2651    args: KeyAuthorizationArgs,
2652    account: Option<Address>,
2653    wallet: WalletOpts,
2654    browser: BrowserWalletOpts,
2655) -> Result<()> {
2656    let is_admin = args.admin;
2657    let chain_id = args.chain_id;
2658
2659    // TODO: remove this check once browser supports T5/T6 KeyAuthorization fields. Guard before
2660    // `browser.run()` so the browser flow never starts for unsupported authorizations.
2661    if browser.browser && (args.witness.is_some() || is_admin || account.is_some()) {
2662        eyre::bail!(
2663            "browser key authorization signing does not support T5/T6 fields yet: witness, admin, account"
2664        );
2665    }
2666    // TODO: remove once the browser wallet serializes configurable account key authorizations.
2667    if browser.browser && args.key_type == AuthSignatureType::ConfigurableAccount {
2668        eyre::bail!(
2669            "browser key authorization signing does not support the configurable key type yet"
2670        );
2671    }
2672
2673    if let Some(browser) = browser.run::<TempoNetwork>().await? {
2674        let signer_address = browser.address();
2675        ensure_root_sender(signer_address, wallet.from, "key authorization")?;
2676        // The browser path rejects admin/witness/account above, so there is nothing to bind.
2677        let authorization = args.into_authorization(None)?;
2678        let key_type = authorization.key_type;
2679        let signature_hash = authorization.signature_hash();
2680        let signed =
2681            foundry_common::tempo::sign_key_authorization_with_browser(&browser, authorization)
2682                .await?;
2683        return print_signed_key_authorization(&signed, signature_hash, signer_address, key_type);
2684    }
2685
2686    let (signer, tempo_access_key) =
2687        foundry_common::tempo::maybe_signer(&wallet, Some(chain_id)).await?;
2688    let signer_address = match (&signer, &tempo_access_key) {
2689        (Some(signer), None) => signer.address(),
2690        (None, Some(wallet)) => wallet.key_id()?,
2691        _ => eyre::bail!(
2692            "a signer is required to sign key authorizations; pass a signer with \
2693             --browser, --private-key, --keystore, Ledger, Trezor, AWS, GCP, or Turnkey"
2694        ),
2695    };
2696
2697    // Resolve the account this authorization is bound to (T6 replay protection).
2698    let bound_account = if let Some(access_key) = &tempo_access_key {
2699        // The access key (an admin key) signs for its root, so bind to the root, not the signer.
2700        if let Some(explicit) = account {
2701            eyre::ensure!(
2702                explicit == access_key.account(),
2703                "--bind-account {explicit} does not match the selected Tempo access key's root account {}",
2704                access_key.account(),
2705            );
2706        }
2707        Some(access_key.account())
2708    } else {
2709        ensure_root_sender(signer_address, wallet.from, "key authorization")?;
2710        account.or(is_admin.then_some(signer_address))
2711    };
2712
2713    let authorization = args.into_authorization(bound_account)?;
2714    let key_type = authorization.key_type;
2715    let signature_hash = authorization.signature_hash();
2716    let signature = match (&signer, &tempo_access_key) {
2717        (Some(signer), None) => {
2718            PrimitiveSignature::Secp256k1(signer.sign_hash(&signature_hash).await?)
2719        }
2720        (None, Some(wallet)) => wallet.sign_hash(&signature_hash).await?,
2721        _ => eyre::bail!("exactly one signer is required to sign a key authorization"),
2722    };
2723    let signed = authorization.into_signed(signature);
2724    print_signed_key_authorization(&signed, signature_hash, signer_address, key_type)
2725}
2726
2727/// Signs `args` as `account`'s owners, bound to the account, and prints it.
2728///
2729/// The wallet signer, when given, approves as one owner.
2730async fn sign_configurable_key_authorization(
2731    args: KeyAuthorizationArgs,
2732    configurable: &ConfigurableAccountArgs,
2733    account: Address,
2734    bind_account: Option<Address>,
2735    wallet: &WalletOpts,
2736    rpc: &RpcOpts,
2737) -> Result<()> {
2738    // TIP-1137 deprecates admin keys from T14, the hardfork that adds configurable accounts.
2739    eyre::ensure!(!args.admin, "--admin cannot be combined with --tempo.configurable-account");
2740    if let Some(bound) = bind_account {
2741        eyre::ensure!(
2742            bound == account,
2743            "--bind-account {bound} does not match the configurable account {account}"
2744        );
2745    }
2746    let (owner, access_key) =
2747        foundry_common::tempo::maybe_signer(wallet, Some(args.chain_id)).await?;
2748    eyre::ensure!(
2749        access_key.is_none(),
2750        "configurable account owners sign with their own keys, not a Tempo access key"
2751    );
2752    let key_type = args.key_type;
2753    let authorization = args.into_authorization(Some(account))?;
2754    let signed = configurable.sign(rpc, account, owner.as_ref(), authorization).await?;
2755    print_signed_key_authorization(&signed, signed.signature_hash(), account, key_type)
2756}
2757
2758fn print_signed_key_authorization(
2759    signed: &SignedKeyAuthorization,
2760    signature_hash: B256,
2761    signer_address: Address,
2762    authorized_key_type: AuthSignatureType,
2763) -> Result<()> {
2764    let encoded = alloy_rlp::encode(signed);
2765    print_json_or(
2766        json!({
2767            "signed_key_authorization": hex::encode_prefixed(&encoded),
2768            "signature_hash": signature_hash,
2769            "rlp_length": encoded.len(),
2770            "signer": signer_address,
2771            "authorized_key_type": key_type_name(authorized_key_type.into()),
2772            "signature_type": key_type_name(signed.signature().signature_type().into()),
2773            "witness": signed.authorization().witness(),
2774            "is_admin": signed.authorization().is_admin(),
2775            "account": signed.authorization().account,
2776        }),
2777        hex::encode_prefixed(&encoded),
2778    )
2779}
2780
2781/// Decode a hex RLP key authorization (signed or unsigned) and validate its account binding.
2782///
2783/// Tries the signed shape first, then the unsigned one. Returns the authorization, whether the
2784/// input was signed, and the best-effort recovered signer. When `expected_account` is set the
2785/// decoded authorization must be bound to exactly that account.
2786fn decode_and_validate_key_authorization(
2787    authorization: &str,
2788    expected_account: Option<Address>,
2789) -> Result<(KeyAuthorization, bool, Option<Address>)> {
2790    let raw = authorization.trim();
2791    let (auth, signed, signer) =
2792        match tempo::decode_key_authorization::<SignedKeyAuthorization>(raw) {
2793            // Signer recovery is best-effort so `inspect` still surfaces fields for a corrupt sig.
2794            // A configurable account is the signer only when its owner quorum verifies against
2795            // an initial configuration that derives it; a later configuration needs the account's
2796            // onchain commitment, which `inspect` does not read.
2797            Ok(signed) => {
2798                let signer = match signed.signature().as_configurable_account() {
2799                    Some(signature) => (signature.validate_account_commitment(B256::ZERO).is_ok()
2800                        && signature.verify_approvals(signed.signature_hash()).is_ok())
2801                    .then(|| signature.account()),
2802                    None => signed.recover_signer().ok(),
2803                };
2804                (signed.authorization().clone(), true, signer)
2805            }
2806            Err(signed_err) => match tempo::decode_key_authorization::<KeyAuthorization>(raw) {
2807                Ok(unsigned) => (unsigned, false, None),
2808                Err(unsigned_err) => eyre::bail!(
2809                    "could not decode key authorization as signed ({signed_err}) or unsigned \
2810                 ({unsigned_err})"
2811                ),
2812            },
2813        };
2814
2815    // Mirror the chain's T6 admin invariants so `inspect` rejects a malformed admin authorization.
2816    eyre::ensure!(
2817        auth.account != Some(Address::ZERO),
2818        "key authorization account cannot be the zero address"
2819    );
2820    if auth.is_admin() {
2821        // A root-signed admin authorization may omit `account` (it is only required when the signer
2822        // is not the target root), so `inspect` does not require it here. Binding is still enforced
2823        // below when `--account` is supplied.
2824        eyre::ensure!(auth.expiry.is_none(), "admin key authorization cannot carry an expiry");
2825        eyre::ensure!(
2826            auth.limits.is_none(),
2827            "admin key authorization cannot carry spending limits"
2828        );
2829        eyre::ensure!(
2830            auth.allowed_calls.is_none(),
2831            "admin key authorization cannot carry call scopes"
2832        );
2833    }
2834
2835    // `--account` rejects a replayed or mismatched account-bound authorization.
2836    if let Some(expected) = expected_account {
2837        match auth.account {
2838            Some(account) if account == expected => {}
2839            Some(account) => eyre::bail!(
2840                "key authorization is bound to account {account} but {expected} was expected"
2841            ),
2842            None => eyre::bail!(
2843                "expected key authorization bound to account {expected} but it has no account field"
2844            ),
2845        }
2846    }
2847
2848    Ok((auth, signed, signer))
2849}
2850
2851/// `cast key-authorization inspect` — decode a signed or unsigned key authorization and print its
2852/// fields, including the T6 `is_admin` / `account` fields.
2853fn run_key_auth_inspect(authorization: &str, expected_account: Option<Address>) -> Result<()> {
2854    let (auth, signed, signer) =
2855        decode_and_validate_key_authorization(authorization, expected_account)?;
2856    let key_type = key_type_name(auth.key_type.into());
2857
2858    if shell::is_json() {
2859        let json = json!({
2860            "signed": signed,
2861            "signer": signer,
2862            "chain_id": auth.chain_id,
2863            "key_address": auth.key_id,
2864            "key_type": key_type,
2865            "is_admin": auth.is_admin(),
2866            "account": auth.account,
2867            "expiry": auth.expiry,
2868            "witness": auth.witness(),
2869            "enforce_limits": auth.limits.is_some(),
2870            "scoped_calls": auth.allowed_calls.is_some(),
2871        });
2872        return sh_println!("{}", serde_json::to_string_pretty(&json)?);
2873    }
2874
2875    sh_println!("Signed:       {signed}")?;
2876    if let Some(signer) = signer {
2877        sh_println!("Signer:       {signer}")?;
2878    }
2879    sh_println!("Chain ID:     {}", auth.chain_id)?;
2880    sh_println!("Key Address:  {}", auth.key_id)?;
2881    sh_println!("Key Type:     {key_type}")?;
2882    sh_println!("Admin:        {}", auth.is_admin())?;
2883    if let Some(account) = auth.account {
2884        sh_println!("Account:      {account}")?;
2885    }
2886    match auth.expiry {
2887        Some(expiry) => sh_println!("Expiry:       {expiry}")?,
2888        None => sh_println!("Expiry:       none")?,
2889    }
2890    match auth.witness() {
2891        Some(witness) => sh_println!("Witness:      {witness}")?,
2892        None => sh_println!("Witness:      none")?,
2893    }
2894    sh_println!("Enforce Lim:  {}", auth.limits.is_some())?;
2895    sh_println!("Scoped Calls: {}", auth.allowed_calls.is_some())
2896}
2897
2898impl KeyAuthorizationArgs {
2899    /// Build a [`KeyAuthorization`] from these args, binding it to `account` when present.
2900    ///
2901    /// Admin keys are key-management only: no expiry, spending limits, or call scopes, and they
2902    /// must be bound to a target account (`--account` for `encode`, signer-derived for `sign`) to
2903    /// prevent cross-account replay. A TIP-1053 witness is still allowed.
2904    fn into_authorization(self, account: Option<Address>) -> Result<KeyAuthorization> {
2905        let (scopes, scopes_present) = match self.scopes_json {
2906            Some(AuthScopesJson(scopes)) => (scopes, true),
2907            None => {
2908                let present = !self.scope.is_empty();
2909                (self.scope, present)
2910            }
2911        };
2912        let has_limits = self.enforce_limits || !self.limits.is_empty();
2913
2914        eyre::ensure!(account != Some(Address::ZERO), "--account cannot be the zero address");
2915        if self.admin {
2916            eyre::ensure!(account.is_some(), "--admin requires --account");
2917            eyre::ensure!(self.expiry.is_none(), "--admin cannot be combined with --expiry");
2918            eyre::ensure!(
2919                !has_limits,
2920                "--admin cannot be combined with spending limits (--enforce-limits / --limit)"
2921            );
2922            eyre::ensure!(
2923                !scopes_present,
2924                "--admin cannot be combined with call scopes (--scope / --scopes)"
2925            );
2926        }
2927
2928        let mut authorization =
2929            KeyAuthorization::unrestricted(self.chain_id, self.key_type, self.key_address);
2930        if let Some(expiry) = self.expiry {
2931            eyre::ensure!(expiry != 0, "--expiry must be greater than zero");
2932            authorization = authorization.with_expiry(expiry);
2933        }
2934        if has_limits {
2935            authorization = authorization.with_limits(self.limits);
2936        }
2937        if scopes_present {
2938            authorization = authorization.with_allowed_calls(scopes);
2939        }
2940        if let Some(witness) = self.witness {
2941            authorization = authorization.with_witness(witness);
2942        }
2943        // Apply T6 admin / account binding last, after the restriction fields are validated above.
2944        Ok(match account {
2945            Some(account) if self.admin => authorization.into_admin(account),
2946            Some(account) => authorization.with_account(account),
2947            None => authorization,
2948        })
2949    }
2950}
2951
2952/// `cast keychain policy add-call` — merge a selector rule into a target scope.
2953#[allow(clippy::too_many_arguments)]
2954async fn run_policy_add_call(
2955    key_address: Address,
2956    root_account: Option<Address>,
2957    target: Address,
2958    selector: [u8; 4],
2959    recipients: Vec<Address>,
2960    tx_opts: TransactionOpts,
2961    send_tx: SendTxOpts,
2962    force: bool,
2963) -> Result<()> {
2964    let (root_account, _) = resolve_key_metadata(key_address, root_account)?;
2965    let (_, provider) = tempo_provider(&send_tx.eth.rpc)?;
2966    require_hardfork(
2967        &provider,
2968        TempoHardfork::T3,
2969        "allowed-call policy editing requires the Tempo T3 hardfork",
2970    )
2971    .await?;
2972
2973    let allowed =
2974        provider.account_keychain().getAllowedCalls(root_account, key_address).call().await?;
2975    let new_rule = SelectorRule { selector: selector.into(), recipients };
2976    let existing = allowed
2977        .isScoped
2978        .then(|| allowed.scopes.into_iter().find(|scope| scope.target == target))
2979        .flatten();
2980    let (scope, changed) = match existing {
2981        Some(mut scope) => {
2982            if scope.selectorRules.is_empty() {
2983                sh_warn!(
2984                    "Allowed calls for {} already allow any selector; leaving wildcard scope unchanged",
2985                    address_label_with_address(target)
2986                )?;
2987            }
2988            let changed = add_selector_rule_to_scope(&mut scope, new_rule);
2989            (scope, changed)
2990        }
2991        None => (CallScope { target, selectorRules: vec![new_rule] }, true),
2992    };
2993
2994    if !changed {
2995        return if shell::is_json() {
2996            sh_println!("{}", json!({ "status": "already_present", "target": target }))
2997        } else {
2998            sh_status!("Allowed call already present for {}", address_label_with_address(target))
2999        };
3000    }
3001
3002    send_keychain_call(
3003        &IAccountKeychain::setAllowedCallsCall { keyId: key_address, scopes: vec![scope] },
3004        tx_opts,
3005        &send_tx,
3006        force,
3007    )
3008    .await
3009}
3010
3011#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3012pub(crate) enum KeychainTxOutcome {
3013    Aborted,
3014    Submitted,
3015    PrintedSponsorHash,
3016}
3017
3018pub(crate) enum KeychainRootSigner {
3019    Browser(BrowserSigner<TempoNetwork>),
3020    Wallet(Box<WalletSigner>),
3021}
3022
3023impl KeychainRootSigner {
3024    fn address(&self) -> Address {
3025        match self {
3026            Self::Browser(browser) => browser.address(),
3027            Self::Wallet(signer) => signer.address(),
3028        }
3029    }
3030
3031    fn sender(&self) -> SenderKind<'_> {
3032        match self {
3033            Self::Browser(browser) => browser.address().into(),
3034            Self::Wallet(signer) => signer.as_ref().into(),
3035        }
3036    }
3037}
3038
3039/// Resolve the root-authorized signer used for AccountKeychain policy changes.
3040pub(crate) async fn resolve_keychain_root_signer(
3041    send_tx: &SendTxOpts,
3042    expected_from: Option<Address>,
3043    print_sponsor_hash: bool,
3044) -> Result<KeychainRootSigner> {
3045    const WHAT: &str = "AccountKeychain transaction";
3046    let (signer, tempo_access_key) =
3047        foundry_common::tempo::maybe_signer(&send_tx.eth.wallet, None).await?;
3048    if let Some(browser) = send_tx.browser.run::<TempoNetwork>().await? {
3049        ensure_root_sender(browser.address(), expected_from, WHAT)?;
3050        return Ok(KeychainRootSigner::Browser(browser));
3051    }
3052
3053    // The T6 spec allows an active admin access key to authorize/revoke other keys, but submitting
3054    // these AccountKeychain mutators as access-key-signed precompile calldata reverts on-chain with
3055    // `UnauthorizedCaller()` on the pinned Tempo build (gas estimation succeeds because it injects
3056    // an override key id, while real execution recovers the signer). Reject before broadcasting
3057    // rather than emitting a guaranteed-revert transaction; use a root signer for direct mutations.
3058    if tempo_access_key.is_some() {
3059        eyre::bail!(
3060            "submitting AccountKeychain admin mutators (authorize / revoke / policy) signed by a \
3061             Tempo access key currently reverts on-chain with UnauthorizedCaller() on the pinned \
3062             Tempo build, even for an active admin key. Use a root account signer (--browser for \
3063             passkey roots, or --private-key / --keystore / Ledger / Trezor / AWS / GCP / Turnkey) \
3064             for direct mutations."
3065        );
3066    }
3067
3068    let signer = match signer {
3069        Some(signer) => signer,
3070        None if print_sponsor_hash => eyre::bail!(
3071            "--tempo.print-sponsor-hash requires a root account signer, such as \
3072             --browser, --private-key, or --keystore"
3073        ),
3074        None => send_tx.eth.wallet.signer().await?,
3075    };
3076    ensure_root_sender(signer.address(), expected_from, WHAT)?;
3077    Ok(KeychainRootSigner::Wallet(Box::new(signer)))
3078}
3079
3080/// Send an AccountKeychain precompile call as a root-authorized transaction.
3081async fn send_keychain_call(
3082    call: &impl SolCall,
3083    tx_opts: TransactionOpts,
3084    send_tx: &SendTxOpts,
3085    force: bool,
3086) -> Result<()> {
3087    send_keychain_tx(call.abi_encode(), tx_opts, send_tx, None, force).await?;
3088    Ok(())
3089}
3090
3091/// Send calldata to the Tempo AccountKeychain precompile as a root-authorized transaction.
3092pub(crate) async fn send_keychain_tx(
3093    calldata: Vec<u8>,
3094    tx_opts: TransactionOpts,
3095    send_tx: &SendTxOpts,
3096    expected_from: Option<Address>,
3097    force: bool,
3098) -> Result<KeychainTxOutcome> {
3099    let root_signer =
3100        resolve_keychain_root_signer(send_tx, expected_from, tx_opts.tempo.print_sponsor_hash)
3101            .await?;
3102    send_precompile_tx_with_root_signer(
3103        ACCOUNT_KEYCHAIN_ADDRESS,
3104        calldata,
3105        tx_opts,
3106        send_tx,
3107        root_signer,
3108        force,
3109        || Ok(()),
3110    )
3111    .await
3112}
3113
3114/// Send calldata to the Tempo precompile at `to` with an already-resolved root signer.
3115pub(crate) async fn send_precompile_tx_with_root_signer(
3116    to: Address,
3117    calldata: Vec<u8>,
3118    mut tx_opts: TransactionOpts,
3119    send_tx: &SendTxOpts,
3120    root_signer: KeychainRootSigner,
3121    force: bool,
3122    before_submit: impl FnOnce() -> Result<()>,
3123) -> Result<KeychainTxOutcome> {
3124    if tx_opts.tempo.sponsor_url.is_some() {
3125        eyre::bail!(
3126            "--sponsor-url is not supported by cast keychain; use --tempo.sponsor with \
3127             --tempo.sponsor-signer or --tempo.sponsor-sig"
3128        );
3129    }
3130
3131    let print_sponsor_hash = tx_opts.tempo.print_sponsor_hash;
3132    let sponsor_fee_payer = tx_opts.tempo.sponsor;
3133    let expires_at = tx_opts.tempo.resolve_expires();
3134    let tempo_sponsor =
3135        if print_sponsor_hash { None } else { tx_opts.tempo.sponsor_config().await? };
3136
3137    let (config, provider) = tempo_provider(&send_tx.eth)?;
3138    apply_poll_interval(&provider, send_tx.poll_interval);
3139    // `--curl` must preserve the first RPC request for the user's intended action.
3140    let fee_provider = (!config.eth_rpc_curl).then_some(&provider);
3141
3142    // Resolve `--tempo.lane <name>` against the lanes file (default
3143    // `<root>/tempo.lanes.toml`) and populate `tx_opts.tempo.nonce_key` from the lane.
3144    let resolved_lane = resolve_lane(&mut tx_opts.tempo, &config.root)?;
3145
3146    let builder = CastTxBuilder::new(&provider, tx_opts, &config)
3147        .await?
3148        .with_to(Some(NameOrAddress::Address(to)))
3149        .await?
3150        .with_code_sig_and_args(None, Some(hex::encode_prefixed(&calldata)), vec![])
3151        .await?;
3152
3153    let from = root_signer.address();
3154    if print_sponsor_hash {
3155        let Some(mut tx) =
3156            confirm_and_build(builder, root_signer.sender(), force, None, false).await?
3157        else {
3158            return Ok(KeychainTxOutcome::Aborted);
3159        };
3160        let hash = sponsor_hash(fee_provider, &mut tx, from, sponsor_fee_payer).await?;
3161        if shell::is_json() {
3162            sh_println!("{}", json!({ "sponsor_hash": format!("{hash:?}") }))?;
3163        } else {
3164            sh_println!("{hash:?}")?;
3165        }
3166        return Ok(KeychainTxOutcome::PrintedSponsorHash);
3167    }
3168
3169    print_expires(expires_at)?;
3170
3171    let send_opts =
3172        SendOptions::new(send_tx, &config).resolving_fee_token(tempo_sponsor.is_none(), &config);
3173    let is_browser = matches!(root_signer, KeychainRootSigner::Browser(_));
3174    let (builder, lane) = if is_browser {
3175        (builder.with_browser_wallet(), None)
3176    } else {
3177        (builder, resolved_lane.as_ref())
3178    };
3179    let Some(mut tx) = confirm_and_build(builder, root_signer.sender(), force, lane, false).await?
3180    else {
3181        return Ok(KeychainTxOutcome::Aborted);
3182    };
3183    apply_fee_payment::<TempoNetwork, _>(tempo_sponsor.as_ref(), fee_provider, &mut tx, from)
3184        .await?;
3185    before_submit()?;
3186
3187    match root_signer {
3188        KeychainRootSigner::Browser(browser) => {
3189            tx.prep_for_submission();
3190            let tx_hash = browser.send_transaction_via_browser(tx).await?;
3191            send_opts.print_tx_result(&provider, tx_hash).await?;
3192        }
3193        KeychainRootSigner::Wallet(signer) => {
3194            let provider = AlloyProviderBuilder::<_, _, TempoNetwork>::default()
3195                .wallet(EthereumWallet::from(*signer))
3196                .connect_provider(&provider);
3197            cast_send(provider, tx, &send_opts).await?;
3198        }
3199    }
3200
3201    Ok(KeychainTxOutcome::Submitted)
3202}
3203
3204/// Ensures `what` is signed by the expected root account when one is known.
3205fn ensure_root_sender(actual: Address, expected: Option<Address>, what: &str) -> Result<()> {
3206    if let Some(expected) = expected
3207        && actual != expected
3208    {
3209        eyre::bail!(
3210            "{what} must be signed by root account {expected}; resolved signer is {actual}"
3211        );
3212    }
3213    Ok(())
3214}
3215
3216/// Resolves the root account of `key_address` and its local Accounts store entry, if any.
3217fn resolve_key_metadata(
3218    key_address: Address,
3219    root_account: Option<Address>,
3220) -> Result<(Address, Option<tempo::KeyEntry>)> {
3221    let store = read_tempo_accounts_store();
3222    if let Some(root_account) = root_account {
3223        let entry = store.and_then(|store| {
3224            store.keys.into_iter().find(|entry| {
3225                entry.wallet_address == root_account && entry.key_address == key_address
3226            })
3227        });
3228        return Ok((root_account, entry));
3229    }
3230
3231    let path = tempo_accounts_store_path_display();
3232    let Some(store) = store else {
3233        eyre::bail!(
3234            "key {key_address} was not found because the Tempo Accounts store could not be read at {path}; pass --root-account"
3235        );
3236    };
3237    let mut matches =
3238        store.keys.into_iter().filter(|entry| entry.key_address == key_address).peekable();
3239    let Some(root_account) = matches.peek().map(|entry| entry.wallet_address) else {
3240        eyre::bail!("key {key_address} was not found in {path}; pass --root-account");
3241    };
3242    let matches: Vec<_> = matches.collect();
3243    if matches.iter().any(|entry| entry.wallet_address != root_account) {
3244        eyre::bail!(
3245            "key {key_address} matches multiple root accounts in {path}; pass --root-account"
3246        );
3247    }
3248    let preferred = matches.iter().position(|entry| !entry.limits.is_empty()).unwrap_or(0);
3249    Ok((root_account, matches.into_iter().nth(preferred)))
3250}
3251
3252fn tempo_accounts_store_path_display() -> String {
3253    let Some(path) = tempo_accounts_store_path() else {
3254        return "(unknown)".to_string();
3255    };
3256    if let Some(home) =
3257        std::env::var_os("HOME").filter(|home| !home.is_empty()).map(std::path::PathBuf::from)
3258        && let Ok(relative) = path.strip_prefix(&home)
3259        && relative == std::path::Path::new(".tempo/wallet/store.json")
3260    {
3261        return "~/.tempo/wallet/store.json".to_string();
3262    }
3263    path.display().to_string()
3264}
3265
3266/// Merges `rule` into `scope`; returns whether the scope changed.
3267fn add_selector_rule_to_scope(scope: &mut CallScope, rule: SelectorRule) -> bool {
3268    if scope.selectorRules.is_empty() {
3269        return false;
3270    }
3271    let Some(existing) =
3272        scope.selectorRules.iter_mut().find(|existing| existing.selector == rule.selector)
3273    else {
3274        scope.selectorRules.push(rule);
3275        return true;
3276    };
3277    if existing.recipients.is_empty() {
3278        return false;
3279    }
3280    if rule.recipients.is_empty() {
3281        existing.recipients = Vec::new();
3282        return true;
3283    }
3284    let mut changed = false;
3285    for recipient in rule.recipients {
3286        if !existing.recipients.contains(&recipient) {
3287            existing.recipients.push(recipient);
3288            changed = true;
3289        }
3290    }
3291    changed
3292}
3293
3294fn inspected_limit_to_json(limit: &InspectedLimit) -> Value {
3295    json!({
3296        "token": limit.token,
3297        "token_label": address_label(limit.token),
3298        "configured_amount": limit.configured_amount,
3299        "remaining": limit.remaining.to_string(),
3300        "period_end": limit.period_end,
3301        "period_end_human": limit.period_end.filter(|&end| end != 0).map(format_period_end),
3302    })
3303}
3304
3305fn allowed_calls_to_json(allowed_calls: &AllowedCallsView) -> Value {
3306    let (mode, scopes) = match allowed_calls {
3307        AllowedCallsView::Unsupported => ("unsupported", &[][..]),
3308        AllowedCallsView::Unrestricted => ("any", &[][..]),
3309        AllowedCallsView::Scoped(scopes) => {
3310            (if scopes.is_empty() { "none" } else { "scoped" }, scopes.as_slice())
3311        }
3312    };
3313    let scopes: Vec<_> = scopes
3314        .iter()
3315        .map(|scope| {
3316            json!({
3317                "target": scope.target,
3318                "target_label": address_label(scope.target),
3319                "selectors": scope.selectorRules.iter().map(|rule| json!({
3320                    "selector": hex::encode_prefixed(rule.selector),
3321                    "signature": selector_signature(&rule.selector.0),
3322                    "recipients": rule.recipients,
3323                })).collect::<Vec<_>>(),
3324            })
3325        })
3326        .collect();
3327    json!({ "mode": mode, "scopes": scopes })
3328}
3329
3330fn print_inspected_limits(enforce_limits: bool, limits: &[InspectedLimit]) -> Result<()> {
3331    if !enforce_limits {
3332        return sh_println!("Limits:       none");
3333    }
3334    sh_println!("Limits:")?;
3335    if limits.is_empty() {
3336        return sh_println!("  enforced, but no local limit metadata was found");
3337    }
3338    for limit in limits {
3339        sh_println!(
3340            "  {}: {} / {} remaining{}",
3341            address_label(limit.token),
3342            limit.remaining,
3343            limit.configured_amount,
3344            format_period_suffix(limit.period_end)
3345        )?;
3346    }
3347    Ok(())
3348}
3349
3350fn print_allowed_calls(allowed_calls: &AllowedCallsView) -> Result<()> {
3351    let scopes = match allowed_calls {
3352        AllowedCallsView::Unsupported => {
3353            return sh_println!("Allowed calls: unsupported before T3");
3354        }
3355        AllowedCallsView::Unrestricted => return sh_println!("Allowed calls: any"),
3356        AllowedCallsView::Scoped(scopes) if scopes.is_empty() => {
3357            return sh_println!("Allowed calls: none");
3358        }
3359        AllowedCallsView::Scoped(scopes) => scopes,
3360    };
3361    sh_println!("Allowed calls:")?;
3362    for scope in scopes {
3363        sh_println!("  {}:", address_label_with_address(scope.target))?;
3364        if scope.selectorRules.is_empty() {
3365            sh_println!("    any selector")?;
3366        }
3367        for rule in &scope.selectorRules {
3368            sh_println!(
3369                "    {} -> {}",
3370                format_selector(&rule.selector.0),
3371                format_recipients(&rule.recipients)
3372            )?;
3373        }
3374    }
3375    Ok(())
3376}
3377
3378fn address_label(address: Address) -> String {
3379    if address == PATH_USD_ADDRESS { "PathUSD".to_string() } else { address.to_string() }
3380}
3381
3382fn address_label_with_address(address: Address) -> String {
3383    if address == PATH_USD_ADDRESS { format!("PathUSD ({address})") } else { address.to_string() }
3384}
3385
3386fn format_selector(selector: &[u8; 4]) -> String {
3387    selector_signature(selector).map_or_else(|| hex::encode_prefixed(selector), str::to_string)
3388}
3389
3390fn selector_signature(selector: &[u8; 4]) -> Option<&'static str> {
3391    const KNOWN: [([u8; 4], &str); 7] = [
3392        (ITIP20::transferCall::SELECTOR, "transfer(address,uint256)"),
3393        (ITIP20::approveCall::SELECTOR, "approve(address,uint256)"),
3394        (ITIP20::transferFromCall::SELECTOR, "transferFrom(address,address,uint256)"),
3395        (ITIP20::transferWithMemoCall::SELECTOR, "transferWithMemo(address,uint256,bytes32)"),
3396        (
3397            ITIP20::transferFromWithMemoCall::SELECTOR,
3398            "transferFromWithMemo(address,address,uint256,bytes32)",
3399        ),
3400        (ITIP20::mintCall::SELECTOR, "mint(address,uint256)"),
3401        (ITIP20::burnCall::SELECTOR, "burn(uint256)"),
3402    ];
3403    KNOWN.iter().find(|(known, _)| known == selector).map(|(_, signature)| *signature)
3404}
3405
3406fn format_recipients(recipients: &[Address]) -> String {
3407    if recipients.is_empty() {
3408        return "any recipient".to_string();
3409    }
3410    let recipients = recipients.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ");
3411    format!("recipients [{recipients}]")
3412}
3413
3414fn format_expiry_for_inspect(expiry: u64) -> String {
3415    if expiry == u64::MAX {
3416        return "never".to_string();
3417    }
3418    format!("{} ({})", format_timestamp_iso(expiry), format_relative_timestamp(expiry))
3419}
3420
3421fn format_period_end(period_end: u64) -> String {
3422    format!("period resets {}", format_relative_timestamp(period_end))
3423}
3424
3425/// ` (period resets ...)` for a non-zero period end, empty otherwise.
3426fn format_period_suffix(period_end: Option<u64>) -> String {
3427    period_end
3428        .filter(|&end| end != 0)
3429        .map(|end| format!(" ({})", format_period_end(end)))
3430        .unwrap_or_default()
3431}
3432
3433fn format_utc(timestamp: u64, format: &str) -> String {
3434    DateTime::from_timestamp(timestamp as i64, 0)
3435        .map_or_else(|| timestamp.to_string(), |dt| dt.format(format).to_string())
3436}
3437
3438fn format_timestamp_iso(timestamp: u64) -> String {
3439    format_utc(timestamp, "%Y-%m-%dT%H:%M:%SZ")
3440}
3441
3442fn format_relative_timestamp(timestamp: u64) -> String {
3443    format_relative_timestamp_from(timestamp, now().as_secs())
3444}
3445
3446fn format_relative_timestamp_from(timestamp: u64, now: u64) -> String {
3447    if timestamp == now {
3448        "now".to_string()
3449    } else if timestamp > now {
3450        format!("in {}", format_duration_words(timestamp - now))
3451    } else {
3452        format!("{} ago", format_duration_words(now - timestamp))
3453    }
3454}
3455
3456fn format_duration_words(seconds: u64) -> String {
3457    const MINUTE: u64 = 60;
3458    const HOUR: u64 = 60 * MINUTE;
3459    const DAY: u64 = 24 * HOUR;
3460    match seconds {
3461        DAY.. => {
3462            let days = seconds / DAY;
3463            if days == 1 { "1 day".to_string() } else { format!("{days} days") }
3464        }
3465        HOUR.. => format!("{}h", seconds / HOUR),
3466        MINUTE.. => format!("{}m", seconds / MINUTE),
3467        _ => format!("{seconds}s"),
3468    }
3469}
3470
3471fn format_expiry(expiry: u64) -> String {
3472    if expiry == u64::MAX {
3473        return "never".to_string();
3474    }
3475    format_utc(expiry, "%Y-%m-%d %H:%M:%S UTC")
3476}
3477
3478fn load_accounts_store() -> Result<AccountsStoreView> {
3479    read_tempo_accounts_store().ok_or_else(|| {
3480        let path = tempo_accounts_store_path()
3481            .map_or_else(|| "(unknown)".to_string(), |p| p.display().to_string());
3482        eyre::eyre!("could not read Tempo Accounts store at {path}")
3483    })
3484}
3485
3486/// `root` when the key is the account EOA itself, `admin` when it is a T6 admin key, otherwise
3487/// `limited`.
3488const fn key_role(is_root: bool, is_admin: bool) -> &'static str {
3489    if is_root {
3490        "root"
3491    } else if is_admin {
3492        "admin"
3493    } else {
3494        "limited"
3495    }
3496}
3497
3498fn print_key_entry(entry: &tempo::KeyEntry) -> Result<()> {
3499    let is_direct = entry.key_address == entry.wallet_address;
3500    let auth = entry.key_authorization.as_ref().map(|signed| signed.authorization());
3501    let is_admin = auth.is_some_and(KeyAuthorization::is_admin);
3502
3503    sh_println!("Wallet:       {}", entry.wallet_address)?;
3504    sh_println!("Chain ID:     {}", entry.chain_id)?;
3505    sh_println!("Key Type:     {}", key_type_name(entry.key_type))?;
3506    sh_println!("Key Address:  {}", entry.key_address)?;
3507    sh_println!(
3508        "Mode:         {}",
3509        if is_direct { "direct (EOA)" } else { "keychain (access key)" }
3510    )?;
3511    if let Some(expiry) = entry.expiry {
3512        sh_println!("Expiry:       {}", format_expiry(expiry))?;
3513    }
3514    sh_println!("Role:         {}", key_role(is_direct, is_admin))?;
3515    sh_println!("Has Key:      {}", entry.has_inline_key())?;
3516    sh_println!("Has Auth:     {}", auth.is_some())?;
3517    if let Some(auth) = auth {
3518        let witness = auth.witness().map_or_else(|| "(none)".to_string(), |w| w.to_string());
3519        sh_println!("Auth Witness: {witness}")?;
3520        sh_println!("Auth Admin:   {is_admin}")?;
3521        if let Some(account) = auth.account {
3522            sh_println!("Auth Account: {account}")?;
3523        }
3524    }
3525    if !entry.limits.is_empty() {
3526        sh_println!("Limits:")?;
3527        for limit in &entry.limits {
3528            sh_println!("  {} → {}", limit.currency, limit.limit)?;
3529        }
3530    }
3531    Ok(())
3532}
3533
3534fn key_entry_to_json(entry: &tempo::KeyEntry) -> Value {
3535    let is_direct = entry.key_address == entry.wallet_address;
3536    let auth = entry.key_authorization.as_ref().map(|signed| signed.authorization());
3537    let is_admin = auth.is_some_and(KeyAuthorization::is_admin);
3538    let limits: Vec<_> =
3539        entry.limits.iter().map(|l| json!({ "currency": l.currency, "limit": l.limit })).collect();
3540    json!({
3541        "wallet_address": entry.wallet_address,
3542        "chain_id": entry.chain_id,
3543        "key_type": key_type_name(entry.key_type),
3544        "key_address": entry.key_address,
3545        "mode": if is_direct { "direct" } else { "keychain" },
3546        "expiry": entry.expiry,
3547        "expiry_human": entry.expiry.map(format_expiry),
3548        "has_key": entry.has_inline_key(),
3549        "has_authorization": auth.is_some(),
3550        "role": key_role(is_direct, is_admin),
3551        "authorization_witness": auth.and_then(KeyAuthorization::witness),
3552        "authorization_is_admin": is_admin,
3553        "authorization_account": auth.and_then(|auth| auth.account),
3554        "limits": limits,
3555    })
3556}
3557
3558#[cfg(test)]
3559mod tests {
3560    use super::*;
3561    use alloy_rlp::Decodable;
3562
3563    fn addr(byte: u8) -> Address {
3564        Address::repeat_byte(byte)
3565    }
3566
3567    fn rule(selector: [u8; 4], recipients: Vec<Address>) -> SelectorRule {
3568        SelectorRule { selector: selector.into(), recipients }
3569    }
3570
3571    fn scope(target: Address, rules: Vec<SelectorRule>) -> CallScope {
3572        CallScope { target, selectorRules: rules }
3573    }
3574
3575    fn stored_entry(wallet: Address, chain_id: u64, key: Address) -> tempo::KeyEntry {
3576        tempo::KeyEntry::new(wallet, chain_id, KeyType::Secp256k1, key)
3577    }
3578
3579    fn signed_authorization_with_limits(
3580        limits: Option<Vec<AuthTokenLimit>>,
3581    ) -> SignedKeyAuthorization {
3582        let mut authorization =
3583            KeyAuthorization::unrestricted(31337, AuthSignatureType::Secp256k1, addr(0x42));
3584        authorization.limits = limits;
3585        authorization.into_signed(PrimitiveSignature::default())
3586    }
3587
3588    fn key_auth_args() -> KeyAuthorizationArgs {
3589        KeyAuthorizationArgs {
3590            chain_id: 31337,
3591            key_address: addr(0x42),
3592            key_type: AuthSignatureType::Secp256k1,
3593            expiry: None,
3594            enforce_limits: false,
3595            limits: vec![],
3596            scope: vec![],
3597            scopes_json: None,
3598            witness: None,
3599            admin: false,
3600        }
3601    }
3602
3603    fn admin_args() -> KeyAuthorizationArgs {
3604        KeyAuthorizationArgs { admin: true, ..key_auth_args() }
3605    }
3606
3607    fn signed_hex(authorization: KeyAuthorization) -> String {
3608        let signed = authorization.into_signed(PrimitiveSignature::from_bytes(&[0u8; 65]).unwrap());
3609        hex::encode_prefixed(alloy_rlp::encode(&signed))
3610    }
3611
3612    #[test]
3613    fn parse_scopes_json_shapes() {
3614        let plain = r#"[{"target":"0x20c0000000000000000000000000000000000001","selectors":["transfer","approve"]},{"target":"0x86A2EE8FAf9A840F7a2c64CA3d51209F9A02081D"}]"#;
3615        let result = parse_scopes_json(plain).unwrap();
3616        assert_eq!(result.len(), 2);
3617        assert_eq!(result[0].selectorRules.len(), 2);
3618        assert!(result[1].selectorRules.is_empty());
3619
3620        let with_recipients = r#"[{"target":"0x20c0000000000000000000000000000000000001","selectors":[{"selector":"transfer","recipients":["0x1111111111111111111111111111111111111111"]}]}]"#;
3621        let result = parse_scopes_json(with_recipients).unwrap();
3622        assert_eq!(result[0].selectorRules[0].recipients.len(), 1);
3623
3624        let unknown_scope_field =
3625            r#"[{"target":"0x20c0000000000000000000000000000000000001","selector":["transfer"]}]"#;
3626        assert!(parse_scopes_json(unknown_scope_field).is_err());
3627        let unknown_selector_field = r#"[{"target":"0x20c0000000000000000000000000000000000001","selectors":[{"selector":"transfer","recipients":[],"bogus":true}]}]"#;
3628        assert!(parse_scopes_json(unknown_selector_field).is_err());
3629    }
3630
3631    #[test]
3632    fn parse_limit_grammar() {
3633        let token = "0x20c0000000000000000000000000000000000000";
3634        let limit = parse_auth_limit(&format!("{token}:10000000")).unwrap();
3635        assert_eq!(limit.token, token.parse::<Address>().unwrap());
3636        assert_eq!(limit.limit, U256::from(10_000_000));
3637        assert_eq!(limit.period, 0);
3638        assert_eq!(parse_auth_limit(&format!("{token}:5:1d")).unwrap().period, 86_400);
3639        assert_eq!(parse_limit(&format!("{token}:5:1d")).unwrap().period, 86_400);
3640        assert!(parse_auth_limit(token).unwrap_err().contains("invalid limit format"));
3641        assert!(parse_auth_limit(&format!("{token}:x")).unwrap_err().contains("invalid amount"));
3642    }
3643
3644    #[test]
3645    fn add_selector_rule_merging() {
3646        let transfer = parse_selector_bytes("transfer").unwrap();
3647        let (first, second) = (addr(0x11), addr(0x22));
3648
3649        let mut merged = scope(PATH_USD_ADDRESS, vec![rule(transfer, vec![first])]);
3650        assert!(add_selector_rule_to_scope(&mut merged, rule(transfer, vec![second])));
3651        assert_eq!(merged.selectorRules.len(), 1);
3652        assert_eq!(merged.selectorRules[0].recipients, vec![first, second]);
3653
3654        let mut widened = scope(PATH_USD_ADDRESS, vec![rule(transfer, vec![first])]);
3655        assert!(add_selector_rule_to_scope(&mut widened, rule(transfer, vec![])));
3656        assert!(widened.selectorRules[0].recipients.is_empty());
3657
3658        let mut wildcard = scope(PATH_USD_ADDRESS, vec![]);
3659        assert!(!add_selector_rule_to_scope(&mut wildcard, rule(transfer, vec![])));
3660        assert!(wildcard.selectorRules.is_empty());
3661    }
3662
3663    #[test]
3664    fn into_authorization_builds_fields() {
3665        let plain = key_auth_args().into_authorization(None).unwrap();
3666        assert!(!plain.is_admin());
3667        assert_eq!(plain.account, None);
3668        assert_eq!(plain.witness(), None);
3669        assert_eq!(plain.allowed_calls, None);
3670        assert!(plain.is_legacy_compatible());
3671
3672        // `bytes32(0)` is a present witness, distinct from omitting the flag.
3673        let zero_witness = KeyAuthorizationArgs { witness: Some(B256::ZERO), ..key_auth_args() }
3674            .into_authorization(None)
3675            .unwrap();
3676        assert_eq!(zero_witness.witness(), Some(B256::ZERO));
3677        assert_ne!(plain.signature_hash(), zero_witness.signature_hash());
3678        assert_ne!(alloy_rlp::encode(&plain), alloy_rlp::encode(&zero_witness));
3679
3680        // An explicit empty `--scopes []` denies all calls rather than allowing any.
3681        let deny_all =
3682            KeyAuthorizationArgs { scopes_json: Some(AuthScopesJson(vec![])), ..key_auth_args() }
3683                .into_authorization(None)
3684                .unwrap();
3685        assert_eq!(deny_all.allowed_calls, Some(vec![]));
3686        assert_ne!(plain.signature_hash(), deny_all.signature_hash());
3687
3688        // Account binding round-trips and feeds the signing hash.
3689        let bound = key_auth_args().into_authorization(Some(addr(0xCD))).unwrap();
3690        assert!(!bound.is_admin());
3691        assert_eq!(bound.account, Some(addr(0xCD)));
3692        let admin_a = admin_args().into_authorization(Some(addr(0x01))).unwrap();
3693        let admin_b = admin_args().into_authorization(Some(addr(0x02))).unwrap();
3694        assert!(admin_a.is_admin());
3695        assert_ne!(admin_a.signature_hash(), admin_b.signature_hash());
3696
3697        let signed =
3698            admin_a.clone().into_signed(PrimitiveSignature::from_bytes(&[0u8; 65]).unwrap());
3699        let encoded = alloy_rlp::encode(&signed);
3700        let decoded = SignedKeyAuthorization::decode(&mut encoded.as_slice()).unwrap();
3701        assert_eq!(decoded.authorization(), &admin_a);
3702
3703        // Local store entries expose the decoded authorization witness.
3704        let witness = B256::repeat_byte(0x53);
3705        let signed =
3706            KeyAuthorization::unrestricted(31337, AuthSignatureType::Secp256k1, addr(0x42))
3707                .with_witness(witness)
3708                .into_signed(PrimitiveSignature::from_bytes(&[0u8; 65]).unwrap());
3709        let json = key_entry_to_json(&tempo::KeyEntry::default().with_key_authorization(signed));
3710        assert_eq!(json["authorization_witness"], witness.to_string());
3711    }
3712
3713    #[test]
3714    fn into_authorization_rejects_invalid_args() {
3715        let account = Some(addr(0xAB));
3716        let cases: [(KeyAuthorizationArgs, Option<Address>, &str); 6] = [
3717            (admin_args(), None, "--admin requires --account"),
3718            (
3719                KeyAuthorizationArgs { expiry: Some(1_782_647_677), ..admin_args() },
3720                account,
3721                "--expiry",
3722            ),
3723            (
3724                KeyAuthorizationArgs { enforce_limits: true, ..admin_args() },
3725                account,
3726                "spending limits",
3727            ),
3728            (
3729                KeyAuthorizationArgs { scopes_json: Some(AuthScopesJson(vec![])), ..admin_args() },
3730                account,
3731                "call scopes",
3732            ),
3733            (key_auth_args(), Some(Address::ZERO), "--account cannot be the zero address"),
3734            (
3735                KeyAuthorizationArgs { expiry: Some(0), ..key_auth_args() },
3736                None,
3737                "--expiry must be greater than zero",
3738            ),
3739        ];
3740        for (args, account, expected) in cases {
3741            let err = args.into_authorization(account).unwrap_err().to_string();
3742            assert!(err.contains(expected), "expected {expected:?}, got: {err}");
3743        }
3744    }
3745
3746    #[test]
3747    fn inspect_decodes_signed_and_unsigned_shapes() {
3748        let account = addr(0xAB);
3749        let hex = signed_hex(admin_args().into_authorization(Some(account)).unwrap());
3750        let (auth, signed, _) = decode_and_validate_key_authorization(&hex, None).unwrap();
3751        assert!(signed, "signed input must be reported as signed");
3752        assert!(auth.is_admin());
3753        assert_eq!(auth.account, Some(account));
3754
3755        let unsigned = key_auth_args().into_authorization(None).unwrap();
3756        let hex = hex::encode_prefixed(alloy_rlp::encode(&unsigned));
3757        let (auth, signed, signer) = decode_and_validate_key_authorization(&hex, None).unwrap();
3758        assert!(!signed, "unsigned input must be reported as unsigned");
3759        assert_eq!(auth, unsigned);
3760        assert!(signer.is_none(), "unsigned input must not recover a signer");
3761    }
3762
3763    #[test]
3764    fn inspect_enforces_admin_invariants_and_account_binding() {
3765        let unrestricted =
3766            || KeyAuthorization::unrestricted(31337, AuthSignatureType::Secp256k1, addr(0x42));
3767        // Built directly (bypassing the CLI constructor's guard) to prove `inspect` mirrors the
3768        // chain's admin invariants.
3769        let admin_with_expiry = unrestricted().with_expiry(1_782_647_677).into_admin(addr(0xAB));
3770        let mut admin_without_account = unrestricted();
3771        admin_without_account.is_admin = true;
3772
3773        // T6 allows a root-signed admin authorization to omit `account`; `inspect` is a decoder and
3774        // must not reject it unless `--account` asks for a binding it cannot verify.
3775        let hex = hex::encode_prefixed(alloy_rlp::encode(&admin_without_account));
3776        let (auth, _, _) = decode_and_validate_key_authorization(&hex, None).unwrap();
3777        assert!(auth.is_admin());
3778        assert_eq!(auth.account, None);
3779
3780        let cases = [
3781            (
3782                signed_hex(admin_args().into_authorization(Some(addr(0xAB))).unwrap()),
3783                Some(addr(0xCD)),
3784                "was expected",
3785            ),
3786            (
3787                hex::encode_prefixed(alloy_rlp::encode(&admin_with_expiry)),
3788                None,
3789                "cannot carry an expiry",
3790            ),
3791            (hex, Some(addr(0xAB)), "no account field"),
3792        ];
3793        for (hex, expected_account, expected) in cases {
3794            let err = decode_and_validate_key_authorization(&hex, expected_account)
3795                .unwrap_err()
3796                .to_string();
3797            assert!(err.contains(expected), "expected {expected:?}, got: {err}");
3798        }
3799    }
3800
3801    #[test]
3802    fn root_sender_mismatch_message_names_the_artifact() {
3803        let (expected, actual) = (addr(0x11), addr(0x22));
3804        let err = ensure_root_sender(actual, Some(expected), "key authorization").unwrap_err();
3805        assert_eq!(
3806            err.to_string(),
3807            format!(
3808                "key authorization must be signed by root account {expected}; resolved signer is {actual}"
3809            )
3810        );
3811        assert!(ensure_root_sender(actual, None, "key authorization").is_ok());
3812    }
3813
3814    #[test]
3815    fn match_allowed_call_cases() {
3816        use AllowedCallMatch::{Allowed, Denied, RecipientRestricted};
3817        let transfer = ITIP20::transferCall::SELECTOR;
3818        let approve = ITIP20::approveCall::SELECTOR;
3819        let (target, other, bob, carol) = (addr(0xAA), addr(0xCC), addr(0xBB), addr(0xDD));
3820        let wildcard = vec![scope(target, vec![])];
3821        let any_recipient = vec![scope(target, vec![rule(transfer, vec![])])];
3822        let restricted = vec![scope(target, vec![rule(transfer, vec![bob])])];
3823        let duplicated = vec![
3824            scope(target, vec![rule(transfer, vec![bob])]),
3825            scope(target, vec![rule(approve, vec![]), rule(transfer, vec![carol])]),
3826        ];
3827        let kind = |m: &AllowedCallMatch| match m {
3828            Allowed(_) => "allowed",
3829            Denied(_) => "denied",
3830            RecipientRestricted(_) => "restricted",
3831        };
3832
3833        let cases = [
3834            (&wildcard, target, transfer, None, "allowed"),
3835            (&wildcard, other, transfer, None, "denied"),
3836            (&any_recipient, target, transfer, Some(bob), "allowed"),
3837            (&any_recipient, target, approve, None, "denied"),
3838            (&restricted, target, transfer, None, "restricted"),
3839            (&restricted, target, transfer, Some(bob), "allowed"),
3840            (&restricted, target, transfer, Some(carol), "denied"),
3841            (&duplicated, target, approve, None, "allowed"),
3842            (&duplicated, target, transfer, Some(carol), "allowed"),
3843        ];
3844        for (scopes, to, selector, recipient, expected) in cases {
3845            let result = match_allowed_call(scopes, to, selector, recipient);
3846            assert_eq!(kind(&result), expected, "{result:?}");
3847        }
3848
3849        // Recipient lists are aggregated across duplicate target scopes.
3850        assert_eq!(
3851            match_allowed_call(&duplicated, target, transfer, None),
3852            RecipientRestricted(vec![bob, carol])
3853        );
3854    }
3855
3856    #[test]
3857    fn doctor_args_parse() {
3858        let root = "0x1111111111111111111111111111111111111111";
3859        let key = "0x2222222222222222222222222222222222222222";
3860        let KeychainSubcommand::Doctor { key_address, root_account, .. } =
3861            KeychainSubcommand::try_parse_from(["keychain", "doctor", "--root-account", root])
3862                .unwrap()
3863        else {
3864            panic!("expected doctor");
3865        };
3866        assert!(key_address.is_none());
3867        assert!(root_account.is_some());
3868
3869        assert!(
3870            KeychainSubcommand::try_parse_from([
3871                "keychain",
3872                "doctor",
3873                key,
3874                "--selector",
3875                "transfer"
3876            ])
3877            .is_err(),
3878            "--selector without --to should error"
3879        );
3880
3881        let KeychainSubcommand::Doctor { fee_token, tempo, .. } =
3882            KeychainSubcommand::try_parse_from([
3883                "keychain",
3884                "doctor",
3885                key,
3886                "--root-account",
3887                root,
3888                "--fee-token",
3889                "PathUSD",
3890                "--tempo.expiring-nonce",
3891                "--tempo.valid-before",
3892                "9999999999",
3893            ])
3894            .unwrap()
3895        else {
3896            panic!("expected doctor");
3897        };
3898        assert_eq!(fee_token, Some(PATH_USD_ADDRESS));
3899        assert!(tempo.expiring_nonce);
3900        assert_eq!(tempo.valid_before, Some(9_999_999_999));
3901    }
3902
3903    #[test]
3904    fn select_subject_for_chain_preferences() {
3905        let (root, key, other_key) = (addr(0x11), addr(0x22), addr(0x33));
3906
3907        // Explicit root/key without a local entry is accepted and warns about local signing.
3908        let subject =
3909            select_subject_for_chain(vec![DoctorCandidate::explicit(root, key)], 31337, Some(root))
3910                .unwrap();
3911        assert_eq!((subject.root_account, subject.key_address), (root, key));
3912        assert!(subject.entry.is_none());
3913        assert_eq!(check_local_signing_readiness(&subject).status, DoctorStatus::Warn);
3914
3915        // A local entry on another chain is skipped in favour of the explicit pair.
3916        let wrong_chain = stored_entry(root, 1, key).with_locally_signable(true);
3917        let subject = select_subject_for_chain(
3918            vec![DoctorCandidate::from_entry(wrong_chain), DoctorCandidate::explicit(root, key)],
3919            31337,
3920            Some(root),
3921        )
3922        .unwrap();
3923        assert_eq!(subject.key_address, key);
3924        assert!(subject.entry.is_none());
3925
3926        // Locally signable entries win over metadata-only records.
3927        let subject = select_subject_for_chain(
3928            vec![
3929                DoctorCandidate::from_entry(stored_entry(root, 31337, key)),
3930                DoctorCandidate::from_entry(
3931                    stored_entry(root, 31337, other_key).with_locally_signable(true),
3932                ),
3933            ],
3934            31337,
3935            Some(root),
3936        )
3937        .unwrap();
3938        assert_eq!(subject.key_address, other_key);
3939
3940        // A stale entry is kept for its authorization metadata when the pair is also explicit.
3941        let stale = stored_entry(root, 31337, key)
3942            .with_key_authorization(signed_authorization_with_limits(None));
3943        let subject = select_subject_for_chain(
3944            vec![DoctorCandidate::from_entry(stale), DoctorCandidate::explicit(root, key)],
3945            31337,
3946            Some(root),
3947        )
3948        .unwrap();
3949        assert!(subject.explicit);
3950        assert!(subject.entry.as_ref().is_some_and(|entry| entry.key_authorization.is_some()));
3951        assert_eq!(check_local_signing_readiness(&subject).status, DoctorStatus::Warn);
3952
3953        // Without an inline key a non-explicit local entry fails; with one it passes.
3954        let mut subject = DoctorSubject {
3955            root_account: root,
3956            key_address: key,
3957            entry: Some(stored_entry(root, 31337, key)),
3958            explicit: false,
3959        };
3960        assert_eq!(check_local_signing_readiness(&subject).status, DoctorStatus::Fail);
3961        subject.entry = Some(stored_entry(root, 31337, key).with_locally_signable(true));
3962        assert_eq!(check_local_signing_readiness(&subject).status, DoctorStatus::Pass);
3963    }
3964
3965    #[test]
3966    fn authorization_spending_limits_warnings() {
3967        let fee_token = addr(0xAA);
3968        let limit = |token, limit, period| AuthTokenLimit { token, limit, period };
3969        let cases = [
3970            (limit(addr(0xBB), U256::ONE, 0), Some(true), "not listed"),
3971            (limit(fee_token, U256::ZERO, 0), Some(true), ""),
3972            (limit(fee_token, U256::ONE, 60), None, "hardfork unknown"),
3973        ];
3974        for (limit, is_t3, detail) in cases {
3975            let signed = signed_authorization_with_limits(Some(vec![limit]));
3976            let step = check_authorization_spending_limits(&signed, fee_token, is_t3);
3977            assert_eq!(step.status, DoctorStatus::Warn, "{step:?}");
3978            assert!(step.detail.contains(detail), "{step:?}");
3979        }
3980    }
3981
3982    #[test]
3983    fn key_role_precedence() {
3984        assert_eq!(key_role(true, false), "root");
3985        assert_eq!(key_role(true, true), "root");
3986        assert_eq!(key_role(false, true), "admin");
3987        assert_eq!(key_role(false, false), "limited");
3988    }
3989
3990    #[tokio::test]
3991    async fn allowed_calls_hardfork_gates() {
3992        let provider = alloy_provider::ProviderBuilder::new_with_network::<TempoNetwork>()
3993            .connect_mocked_client(alloy_provider::mock::Asserter::new());
3994        let subject = DoctorSubject {
3995            root_account: addr(0x11),
3996            key_address: addr(0x22),
3997            entry: None,
3998            explicit: true,
3999        };
4000        let step = check_allowed_calls(&provider, &subject, None, None, None, None, None).await;
4001        assert_eq!(step.status, DoctorStatus::Warn);
4002        assert_eq!(step.detail, "skipped; hardfork unknown");
4003        let step =
4004            check_allowed_calls(&provider, &subject, None, Some(false), None, None, None).await;
4005        assert_eq!(step.status, DoctorStatus::Pass);
4006        assert_eq!(step.detail, "TIP-1011 not enforced before T3");
4007    }
4008
4009    #[test]
4010    fn expiry_uses_chain_timestamp() {
4011        let known = ChainTimestamp::Known(100);
4012        assert_eq!(check_expiry(Some(100), &known, "", "hint").status, DoctorStatus::Fail);
4013        assert_eq!(check_expiry(Some(101), &known, "", "hint").status, DoctorStatus::Pass);
4014        assert_eq!(check_expiry(None, &known, "", "hint").detail, "never expires");
4015
4016        let unknown =
4017            ChainTimestamp::Unknown { detail: "latest block not found".to_string(), hint: "h" };
4018        let step = check_expiry(Some(100), &unknown, "key_authorization ", "hint");
4019        assert_eq!(step.status, DoctorStatus::Warn);
4020        assert_eq!(step.detail, "key_authorization expiry not checked: latest block not found");
4021    }
4022
4023    #[test]
4024    fn expiring_nonce_window_thresholds() {
4025        let opts = |expiring_nonce, valid_after, valid_before| TempoOpts {
4026            expiring_nonce,
4027            valid_after,
4028            valid_before,
4029            ..Default::default()
4030        };
4031        let t10 = Some(TempoHardfork::T10);
4032        let t11 = Some(TempoHardfork::T11);
4033        let cases = [
4034            // Validated even without --tempo.expiring-nonce.
4035            (opts(false, Some(20), Some(20)), 10, t10, DoctorStatus::Fail),
4036            (opts(false, None, Some(10)), 10, t10, DoctorStatus::Fail),
4037            (opts(true, None, Some(103)), 100, t10, DoctorStatus::Fail),
4038            (opts(true, None, Some(104)), 100, t10, DoctorStatus::Warn),
4039            (opts(true, None, Some(105)), 100, t10, DoctorStatus::Warn),
4040            (opts(true, None, Some(120)), 100, t10, DoctorStatus::Pass),
4041            // The upper bound follows the active hardfork and is skipped when it is unknown.
4042            (opts(true, None, Some(131)), 100, t10, DoctorStatus::Warn),
4043            (opts(true, None, Some(131)), 100, t11, DoctorStatus::Pass),
4044            (opts(true, None, Some(400)), 100, t11, DoctorStatus::Pass),
4045            (opts(true, None, Some(401)), 100, t11, DoctorStatus::Warn),
4046            (opts(true, None, Some(401)), 100, None, DoctorStatus::Pass),
4047        ];
4048        for (tempo, now, hardfork, expected) in cases {
4049            let step = check_expiring_nonce_window(&tempo, None, now, hardfork);
4050            assert_eq!(step.status, expected, "{step:?}");
4051        }
4052    }
4053
4054    #[test]
4055    fn diagnose_allowed_scopes_denials() {
4056        let exact =
4057            diagnose_allowed_scopes(&[], Some(addr(0x11)), Some([0xaa, 0xbb, 0xcc, 0xdd]), None);
4058        assert_eq!(exact.status, DoctorStatus::Fail);
4059
4060        let scopes = [scope(addr(0x11), vec![rule([0xaa, 0xbb, 0xcc, 0xdd], vec![])])];
4061        let target_only = diagnose_allowed_scopes(&scopes, Some(addr(0x22)), None, None);
4062        assert_eq!(target_only.status, DoctorStatus::Warn);
4063    }
4064
4065    #[test]
4066    fn sponsor_config_error_redacts_private_key_uri() {
4067        let tempo = TempoOpts {
4068            sponsor_signer: Some("private-key://super-secret".to_string()),
4069            ..Default::default()
4070        };
4071        let sanitized = sanitize_sponsor_config_error(
4072            "unsupported Tempo sponsor signer `private-key://super-secret`",
4073            &tempo,
4074        );
4075        assert!(sanitized.contains("private-key://<redacted>"));
4076        assert!(!sanitized.contains("super-secret"));
4077    }
4078}