Skip to main content

cast/cmd/
keychain.rs

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