1use crate::{
5 cmd::{
6 auth::confirm_and_build,
7 confirm_continue,
8 keychain::{KeychainRootSigner, send_precompile_tx_with_root_signer},
9 send::{SendOptions, cast_send_raw},
10 },
11 tempo::{apply_fee_payment, print_expires, tempo_provider},
12 tx::{CastTxBuilder, SendTxOpts, apply_poll_interval},
13};
14use alloy_chains::Chain;
15use alloy_eips::{Decodable2718, Encodable2718};
16use alloy_ens::NameOrAddress;
17use alloy_primitives::{Address, hex, keccak256};
18use alloy_provider::Provider;
19use alloy_signer::Signer;
20use alloy_sol_types::SolCall;
21use clap::Parser;
22use eyre::{Context, Result};
23use foundry_cli::{
24 json::print_json_success,
25 opts::{RpcOpts, TransactionOpts},
26 utils::{LoadConfig, now, resolve_lane},
27};
28use foundry_common::{
29 provider::ProviderBuilder,
30 shell,
31 tempo::{
32 active_tempo_hardfork,
33 configurable_account::{
34 abi_owners, ca_error, combine_approvals, current_config, decode_unsigned_tx,
35 parse_owner_signature, simulation_spec,
36 },
37 },
38};
39use foundry_config::{Config, FoundryHardfork};
40use serde_json::{Value, json};
41use std::{str::FromStr, time::Duration};
42use tempo_alloy::{
43 TempoNetwork,
44 chainspec::hardfork::TempoHardfork,
45 rpc::{ConfigurableAccountSimulationSpec, PrimitiveSignatureType},
46};
47use tempo_contracts::precompiles::{CONFIGURABLE_ACCOUNT_ADDRESS, IConfigurableAccount};
48use tempo_primitives::transaction::{
49 CONFIGURABLE_ACCOUNT_UPGRADE_DOMAIN, ConfigurableAccountConfig, ConfigurableAccountOwner,
50 PrimitiveSignature, TempoSignature, TempoTxEnvelope, configurable_account_digest,
51};
52
53pub(crate) async fn new_wallet_is_configurable(
65 eoa: bool,
66 requested: bool,
67 chain: Option<Chain>,
68 rpc: &RpcOpts,
69) -> Result<bool> {
70 let chain = match chain {
73 Some(chain) => Some(chain),
74 None if requested => match std::env::var("CHAIN") {
75 Ok(chain) => Some(
76 chain
77 .parse()
78 .map_err(|_| eyre::eyre!("invalid CHAIN: `{chain}` is not a chain"))?,
79 ),
80 Err(std::env::VarError::NotPresent) => None,
81 Err(err) => eyre::bail!("invalid CHAIN: {err}"),
82 },
83 None => None,
84 };
85 if eoa || chain.is_some_and(|chain| !chain.is_tempo()) {
86 return Ok(false);
87 }
88 let loaded = rpc.load_config().map_err(Into::into).and_then(|config| {
89 let url = rpc.url(Some(&config))?.is_some();
90 eyre::Ok((config, url))
91 });
92 let (config, url) = match loaded {
93 Ok(loaded) => loaded,
94 Err(_) if !requested => return Ok(false),
95 Err(err) => return Err(err),
96 };
97 let chain = chain.or(config.chain);
98
99 let mut signal = None;
100 if url {
101 match rpc_tempo_hardfork(&config).await {
102 Ok(rpc_signal) => signal = rpc_signal,
103 Err(err) => {
104 sh_warn!("Could not ask the RPC for its chain ({err}); using the configured chain")?
105 }
106 }
107 }
108 let signal = match signal {
109 Some(signal) => Some(signal),
110 None => match chain {
111 Some(chain) => chain.is_tempo().then(|| scheduled_hardfork(chain)),
112 None if config.networks.is_tempo() => Some(match config.hardfork {
113 Some(FoundryHardfork::Tempo(hardfork)) => {
114 (format!("the configured hardfork {hardfork}"), Some(hardfork))
115 }
116 _ => scheduled_hardfork(Chain::from_id(TEMPO_MAINNET)),
117 }),
118 None => None,
119 },
120 };
121
122 let Some((source, hardfork)) = signal else {
123 if requested {
124 sh_status!(
125 "No Tempo chain was given (--chain, CHAIN, an RPC or foundry.toml); creating an EOA."
126 )?;
127 }
128 return Ok(false);
129 };
130 if hardfork.is_some_and(|hardfork| hardfork >= TempoHardfork::T14) {
131 return Ok(true);
132 }
133 if requested {
134 sh_status!("Tempo T14 is not active on {source}; creating an EOA.")?;
135 }
136 Ok(false)
137}
138
139const TEMPO_MAINNET: u64 = 4217;
141
142async fn rpc_tempo_hardfork(config: &Config) -> Result<Option<(String, Option<TempoHardfork>)>> {
144 let provider = ProviderBuilder::<TempoNetwork>::from_config(config)?
147 .max_retry(0)
148 .timeout(Duration::from_secs(5))
149 .build()?;
150 let chain = Chain::from_id(provider.get_chain_id().await?);
151 if let Ok(hardfork) = active_tempo_hardfork(&provider).await {
152 return Ok(Some(("the RPC chain".to_string(), Some(hardfork))));
153 }
154 Ok(chain.is_tempo().then(|| scheduled_hardfork(chain)))
155}
156
157fn scheduled_hardfork(chain: Chain) -> (String, Option<TempoHardfork>) {
159 let timestamp = now().as_secs();
160 (format!("chain {chain}"), TempoHardfork::from_chain_and_timestamp(chain.id(), timestamp))
161}
162
163fn parse_owner(value: &str) -> Result<ConfigurableAccountOwner> {
165 let (owner, weight) = match value.split_once(':') {
166 Some((owner, weight)) => (owner, weight.parse().wrap_err("invalid owner weight")?),
167 None => (value, 1),
168 };
169 Ok(ConfigurableAccountOwner { owner: Address::from_str(owner)?, weight })
170}
171
172fn print_config(account: Address, config: &ConfigurableAccountConfig) -> Result<()> {
174 if shell::is_json() {
175 return print_json_success(config_json(account, config)?);
176 }
177 sh_println!("Account: {account}")?;
178 sh_println!("Version: {}", config.version)?;
179 sh_println!("Threshold: {}", config.threshold)?;
180 sh_println!("Salt: {}", config.salt)?;
181 sh_println!("Commitment: {}", config.commitment().map_err(ca_error)?)?;
182 sh_println!("Owners:")?;
183 for owner in &config.owners {
184 sh_println!(" {} (weight {})", owner.owner, owner.weight)?;
185 }
186 Ok(())
187}
188
189fn config_json(account: Address, config: &ConfigurableAccountConfig) -> Result<Value> {
190 Ok(json!({
191 "account": account,
192 "version": config.version,
193 "threshold": config.threshold,
194 "salt": config.salt,
195 "commitment": config.commitment().map_err(ca_error)?,
196 "owners": config.owners.iter().map(|owner| json!({
197 "owner": owner.owner,
198 "weight": owner.weight,
199 })).collect::<Vec<_>>(),
200 }))
201}
202
203#[derive(Debug, Parser)]
205#[command(args_conflicts_with_subcommands = true, subcommand_negates_reqs = true)]
206pub struct OwnersArgs {
207 #[command(subcommand)]
208 command: Option<OwnersSubcommand>,
209
210 #[arg(required = true)]
212 account: Option<Address>,
213
214 #[command(flatten)]
215 rpc: RpcOpts,
216}
217
218#[derive(Clone, Debug, Parser)]
225pub enum OwnersSubcommand {
226 Add {
228 account: Address,
230
231 owner: Address,
233
234 #[arg(long, default_value_t = 1)]
236 weight: u8,
237
238 #[arg(long)]
240 threshold: Option<u8>,
241
242 #[command(flatten)]
243 send: OwnerSendArgs,
244 },
245
246 #[command(visible_alias = "rm")]
248 Remove {
249 account: Address,
251
252 owner: Address,
254
255 #[arg(long)]
257 threshold: Option<u8>,
258
259 #[command(flatten)]
260 send: OwnerSendArgs,
261 },
262
263 Threshold {
265 account: Address,
267
268 threshold: u8,
270
271 #[command(flatten)]
272 send: OwnerSendArgs,
273 },
274}
275
276#[derive(Clone, Debug, Parser)]
278pub struct OwnerSendArgs {
279 #[arg(long)]
281 force: bool,
282
283 #[command(flatten)]
284 tx: TransactionOpts,
285
286 #[command(flatten)]
287 send_tx: SendTxOpts,
288}
289
290impl OwnersArgs {
291 pub async fn run(self) -> Result<()> {
292 let Some(command) = self.command else {
293 let account = self.account.expect("required by clap");
294 let (_, provider) = tempo_provider(&self.rpc)?;
295 let Some(config) = current_config(&provider, account, &[]).await? else {
296 eyre::bail!(
297 "{account} is not a registered configurable account. An account registers on \
298 its first transaction; until then its configuration is only known to its \
299 owners."
300 );
301 };
302 return print_config(account, &config);
303 };
304
305 update_config(command).await
306 }
307}
308
309async fn update_config(command: OwnersSubcommand) -> Result<()> {
311 let (account, OwnerSendArgs { force, mut tx, send_tx }) = match &command {
312 OwnersSubcommand::Add { account, send, .. }
313 | OwnersSubcommand::Remove { account, send, .. }
314 | OwnersSubcommand::Threshold { account, send, .. } => (*account, send.clone()),
315 };
316 eyre::ensure!(
317 tx.tempo.sponsor_url.is_none() && !tx.tempo.print_sponsor_hash,
318 "--sponsor-url and --tempo.print-sponsor-hash are not supported for configurable accounts"
319 );
320 eyre::ensure!(
321 tx.tempo.session_id()?.is_none(),
322 "configuration updates need an owner key; Tempo Accounts sessions cannot sign them"
323 );
324 let signer = send_tx.eth.wallet.signer().await?;
325 let (config, provider) = tempo_provider(&send_tx.eth)?;
326 apply_poll_interval(&provider, send_tx.poll_interval);
327
328 let current =
329 current_config(&provider, account, &[signer.address()]).await?.ok_or_else(|| {
330 eyre::eyre!(
331 "{account} is not a registered configurable account, and the wallet {} does not \
332 derive it",
333 signer.address()
334 )
335 })?;
336 let mut next = current.clone();
337 match command {
338 OwnersSubcommand::Add { owner, weight, threshold, .. } => {
339 eyre::ensure!(
340 next.owner_weight(owner).is_none(),
341 "{owner} is already an owner of {account}"
342 );
343 next.owners.push(ConfigurableAccountOwner { owner, weight });
344 next.owners.sort_by_key(|owner| owner.owner);
345 next.threshold = threshold.unwrap_or(next.threshold);
346 }
347 OwnersSubcommand::Remove { owner, threshold, .. } => {
348 eyre::ensure!(
349 next.owner_weight(owner).is_some(),
350 "{owner} is not an owner of {account}"
351 );
352 next.owners.retain(|entry| entry.owner != owner);
353 next.threshold = threshold.unwrap_or(next.threshold);
354 }
355 OwnersSubcommand::Threshold { threshold, .. } => next.threshold = threshold,
356 }
357 next.version = current.version.checked_add(1).ok_or_else(|| eyre::eyre!("version overflow"))?;
358 next.validate().map_err(|err| eyre::eyre!("invalid new configuration: {err}"))?;
359 let calldata = IConfigurableAccount::updateConfigCall {
360 current: IConfigurableAccount::ConfigurableAccountConfig {
361 salt: current.salt,
362 version: current.version,
363 threshold: current.threshold,
364 owners: abi_owners(¤t),
365 },
366 threshold: next.threshold,
367 owners: abi_owners(&next),
368 }
369 .abi_encode();
370
371 let signer_weight = current.owner_weight(signer.address()).unwrap_or_default();
372 if signer_weight < current.threshold {
373 eyre::bail!(
374 "the wallet {} has weight {signer_weight} in {account}, which requires {}. Collect \
375 the owners' approvals instead:\n cast mktx {CONFIGURABLE_ACCOUNT_ADDRESS} {} --from \
376 {account} --raw-unsigned --tempo.digest\nthen `cast wallet sign --no-hash <DIGEST>` \
377 (adding `--p256` for a raw P-256 owner) on each owner's machine, `cast wallet \
378 assemble`, and `cast publish`",
379 signer.address(),
380 current.threshold,
381 hex::encode_prefixed(&calldata),
382 );
383 }
384
385 let print_expires_at = tx.tempo.resolve_expires();
386 let tempo_sponsor = tx.tempo.sponsor_config().await?;
387 let resolved_lane = resolve_lane(&mut tx.tempo, &config.root)?;
388 let mut builder = CastTxBuilder::new(&provider, tx, &config)
389 .await?
390 .with_to(Some(NameOrAddress::Address(CONFIGURABLE_ACCOUNT_ADDRESS)))
391 .await?
392 .with_code_sig_and_args(None, Some(hex::encode_prefixed(&calldata)), vec![])
393 .await?;
394 builder.tx_mut().configurable_account_simulation = Some(simulation_spec(
396 account,
397 ¤t,
398 &[(signer.address(), PrimitiveSignatureType::Secp256k1)],
399 ));
400 let Some(mut request) =
401 confirm_and_build(builder, account, force, resolved_lane.as_ref(), false).await?
402 else {
403 return Ok(());
404 };
405 print_expires(print_expires_at)?;
406 apply_fee_payment::<TempoNetwork, _>(
407 tempo_sponsor.as_ref(),
408 Some(&provider),
409 &mut request,
410 account,
411 )
412 .await?;
413
414 let unsigned = request.build_aa().map_err(|err| eyre::eyre!("{err}"))?;
415 let inner = unsigned.signature_hash();
416 let approval =
417 signer.sign_hash(&configurable_account_digest(inner, account, current.version)).await?;
418 let signature =
419 combine_approvals(account, ¤t, inner, vec![PrimitiveSignature::Secp256k1(approval)])?;
420 let raw =
421 TempoTxEnvelope::AA(unsigned.into_signed(TempoSignature::ConfigurableAccount(signature)))
422 .encoded_2718();
423
424 let send_opts = SendOptions::new(&send_tx, &config);
425 let (tx_hash, receipt) = cast_send_raw(&provider, &raw, send_tx.sync).await?;
426 send_opts.print_send_result(&provider, tx_hash, receipt).await?;
427 Ok(())
428}
429
430#[derive(Debug, Parser)]
432pub struct UpgradeArgs {
433 #[arg(long = "owner", value_name = "OWNER", value_parser = parse_owner)]
436 owners: Vec<ConfigurableAccountOwner>,
437
438 #[arg(long, default_value_t = 1)]
440 threshold: u8,
441
442 #[arg(long)]
444 force: bool,
445
446 #[command(flatten)]
447 tx: TransactionOpts,
448
449 #[command(flatten)]
450 send_tx: SendTxOpts,
451}
452
453impl UpgradeArgs {
454 pub async fn run(self) -> Result<()> {
455 let Self { mut owners, threshold, force, tx, send_tx } = self;
456 eyre::ensure!(
457 tx.tempo.session_id()?.is_none(),
458 "the upgrade needs the account's own key; Tempo Accounts sessions cannot sign it"
459 );
460 let signer = send_tx.eth.wallet.signer().await?;
461 let account = signer.address();
462 if let Some(from) = send_tx.eth.wallet.from {
463 eyre::ensure!(
464 from == account,
465 "--from {from} does not match the signer {account}; the upgrade converts the \
466 signer's account"
467 );
468 }
469 if owners.is_empty() {
470 owners.push(ConfigurableAccountOwner { owner: account, weight: 1 });
471 }
472 owners.sort_by_key(|owner| owner.owner);
473 let config = ConfigurableAccountConfig {
474 salt: keccak256([CONFIGURABLE_ACCOUNT_UPGRADE_DOMAIN, account.as_slice()].concat()),
475 version: 1,
476 threshold,
477 owners,
478 };
479 config.validate().map_err(|err| eyre::eyre!("invalid configuration: {err}"))?;
480
481 let (_, provider) = tempo_provider(&send_tx.eth)?;
482 if current_config(&provider, account, &[]).await?.is_some() {
483 eyre::bail!("{account} is already a configurable account");
484 }
485
486 sh_status!("Upgrading {account} to a configurable account:")?;
487 sh_status!(" Threshold: {}", config.threshold)?;
488 for owner in &config.owners {
489 sh_status!(" Owner: {} (weight {})", owner.owner, owner.weight)?;
490 }
491 sh_warn!(
492 "The upgrade is irreversible: the key of {account} can no longer sign for it, only \
493 its owners can. The account can also no longer act as an MPP voucher signer: \
494 opening or topping up payment channels reverts with RootKeyRetired. Keep an EOA for \
495 MPP."
496 )?;
497 if !force {
498 if shell::is_quiet() {
499 eyre::bail!("the upgrade requires confirmation; pass `--force` with `--quiet`");
500 }
501 if !confirm_continue()? {
502 return Ok(());
503 }
504 }
505
506 let calldata = IConfigurableAccount::upgradeAccountCall {
507 threshold: config.threshold,
508 owners: abi_owners(&config),
509 }
510 .abi_encode();
511 send_precompile_tx_with_root_signer(
512 CONFIGURABLE_ACCOUNT_ADDRESS,
513 calldata,
514 tx,
515 &send_tx,
516 KeychainRootSigner::Wallet(Box::new(signer)),
517 force,
518 || Ok(()),
519 )
520 .await?;
521 Ok(())
522 }
523}
524
525#[derive(Debug, Parser)]
527pub struct AssembleArgs {
528 unsigned_tx: String,
530
531 #[arg(required = true, value_name = "SIGNATURE")]
540 signatures: Vec<String>,
541
542 #[arg(long, value_name = "ACCOUNT")]
544 from: Address,
545
546 #[command(flatten)]
547 rpc: RpcOpts,
548}
549
550impl AssembleArgs {
551 pub async fn run(self) -> Result<()> {
552 let Self { unsigned_tx, signatures, from: account, rpc } = self;
553 let tx = decode_unsigned_tx(
554 &hex::decode(unsigned_tx.trim()).wrap_err("invalid hex transaction")?,
555 )?;
556 let approvals = signatures
557 .iter()
558 .enumerate()
559 .map(|(index, value)| {
560 parse_owner_signature(value)
561 .wrap_err_with(|| format!("invalid signature {}", index + 1))
562 })
563 .collect::<Result<Vec<_>>>()?;
564
565 let inner = tx.signature_hash();
567 let initial_digest = configurable_account_digest(inner, account, 0);
568 let keys = approvals
569 .iter()
570 .filter_map(|approval| approval.recover_signer(&initial_digest).ok())
571 .collect::<Vec<_>>();
572 let (_, provider) = tempo_provider(&rpc)?;
573 let config = current_config(&provider, account, &keys).await?.ok_or_else(|| {
574 eyre::eyre!(
575 "{account} is not a registered configurable account, and no approval derives it"
576 )
577 })?;
578
579 let signature = combine_approvals(account, &config, inner, approvals)?;
580 let raw =
581 TempoTxEnvelope::AA(tx.into_signed(TempoSignature::ConfigurableAccount(signature)))
582 .encoded_2718();
583 TempoTxEnvelope::decode_2718_exact(&raw)?;
585 crate::cmd::print_result_line(hex::encode_prefixed(raw))
586 }
587}
588
589pub(crate) async fn digest_context(
595 eth: &impl LoadConfig,
596 account: Address,
597 gas_limit: bool,
598) -> Result<(u64, Option<ConfigurableAccountSimulationSpec>)> {
599 let (_, provider) = tempo_provider(eth)?;
600 match current_config(&provider, account, &[]).await? {
601 Some(config) => Ok((config.version, Some(simulation_spec(account, &config, &[])))),
602 None => {
603 eyre::ensure!(
604 provider.get_transaction_count(account).await? == 0,
605 "{account} is not a configurable account"
606 );
607 eyre::ensure!(
608 gas_limit,
609 "{account} is not registered yet, so its owners and the gas of its registration \
610 are unknown. Send its first transaction with `cast wallet owners`, or pass \
611 --gas-limit"
612 );
613 sh_warn!("{account} is not registered yet: the digest is for configuration version 0")?;
614 Ok((0, None))
615 }
616 }
617}