Skip to main content

forge_script/
build.rs

1use crate::{
2    ScriptArgs, ScriptConfig,
3    broadcast::{
4        BundledState, refused_after_revert, remaining_operation_indices,
5        remaining_unsigned_transactions_for_recovery,
6    },
7    execute::LinkedState,
8    multi_sequence::MultiChainSequence,
9    progress::ScriptProgress,
10    receipts::is_mined_receipt_for,
11    recovery::recovery_exists,
12    sequence::{DelegatedResolution, ScriptSequenceKind, blocked_pending},
13    session::{SignerScope, script_session_expected_sender_if_configured},
14};
15use alloy_network::{AnyNetwork, ReceiptResponse};
16use alloy_primitives::{Address, B256, map::AddressHashSet};
17use alloy_provider::Provider;
18use alloy_rpc_types::BlockId;
19use alloy_signer::Signer;
20use eyre::{ContextCompat, OptionExt, Result};
21use forge_script_sequence::ScriptSequence;
22use foundry_cheatcodes::Wallets;
23use foundry_cli::opts::TempoOpts;
24use foundry_common::{
25    ContractData, ContractsByArtifact, ContractsByArtifactBuilder,
26    compile::ProjectCompiler,
27    external_compiler::is_builtin_compiler_source,
28    fs::canonicalize_path,
29    namespaced_storage,
30    provider::ProviderBuilder,
31    tempo::configurable_account::{
32        detect_configurable_account, parse_config, reaches_threshold, stored_owner_keys,
33    },
34};
35use foundry_compilers::{
36    ArtifactId, ProjectCompileOutput,
37    artifacts::{BytecodeObject, Libraries},
38    compilers::{Language, multi::MultiCompilerLanguage},
39    info::ContractInfo,
40    utils::source_files_iter,
41};
42use foundry_evm::{
43    core::evm::FoundryEvmNetwork,
44    traces::{CallTraceDecoder, debug::ContractSources},
45};
46use foundry_linking::Linker;
47use foundry_wallets::{MultiWalletOpts, wallet_browser::signer::BrowserSigner};
48use itertools::Itertools;
49use std::{
50    path::{Path, PathBuf},
51    str::FromStr,
52    sync::Arc,
53};
54use tempo_alloy::TempoNetwork;
55
56/// Container for the compiled contracts.
57#[derive(Clone, Debug)]
58pub struct BuildData {
59    /// Root of the project.
60    pub project_root: PathBuf,
61    /// The compiler output.
62    pub output: ProjectCompileOutput,
63    /// ID of target contract artifact.
64    pub target: ArtifactId,
65}
66
67impl BuildData {
68    pub fn get_linker(&self) -> Linker<'_> {
69        Linker::new(self.project_root.clone(), self.output.artifact_ids().collect())
70    }
71
72    /// Links contracts. Uses CREATE2 linking when possible, otherwise falls back to
73    /// default linking with sender nonce and address.
74    pub async fn link<FEN: FoundryEvmNetwork>(
75        self,
76        script_config: &ScriptConfig<FEN>,
77    ) -> Result<LinkedBuildData> {
78        let create2_deployer = script_config.evm_opts.create2_deployer;
79        let can_use_create2 = script_config
80            .backend
81            .can_use_create2_deployer(script_config.evm_opts.create2_deployer)
82            .await?;
83
84        let known_libraries = script_config.config.libraries_with_remappings()?;
85
86        let maybe_create2_link_output = can_use_create2
87            .then(|| {
88                self.get_linker()
89                    .link_with_create2_detailed(
90                        known_libraries.clone(),
91                        create2_deployer,
92                        script_config.config.create2_library_salt,
93                        [&self.target],
94                    )
95                    .ok()
96            })
97            .flatten();
98
99        let (libraries, predeploy_libs) = if let Some(output) = maybe_create2_link_output {
100            (
101                output.output.libraries,
102                ScriptPredeployLibraries::Create2 {
103                    onchain: output.linked_libraries,
104                    salt: script_config.config.create2_library_salt,
105                    local: Vec::new(),
106                },
107            )
108        } else {
109            let output = self.get_linker().link_with_nonce_or_address_detailed(
110                known_libraries,
111                script_config.evm_opts.sender,
112                script_config.sender_nonce,
113                [&self.target],
114            )?;
115
116            (
117                output.output.libraries,
118                ScriptPredeployLibraries::Default {
119                    onchain: output.linked_libraries,
120                    local: Vec::new(),
121                },
122            )
123        };
124
125        LinkedBuildData::new(libraries, predeploy_libs, self)
126    }
127
128    /// Links the build data with the given libraries. Expects supplied libraries set being enough
129    /// to fully link target contract.
130    pub fn link_with_libraries(self, libraries: Libraries) -> Result<LinkedBuildData> {
131        LinkedBuildData::new(
132            libraries,
133            ScriptPredeployLibraries::Default { onchain: Vec::new(), local: Vec::new() },
134            self,
135        )
136    }
137}
138
139#[derive(Clone, Debug)]
140pub enum ScriptPredeployLibraries {
141    Default {
142        onchain: Vec<foundry_linking::LinkedLibrary>,
143        local: Vec<foundry_linking::LinkedLibrary>,
144    },
145    Create2 {
146        onchain: Vec<foundry_linking::LinkedLibrary>,
147        salt: B256,
148        local: Vec<foundry_linking::LinkedLibrary>,
149    },
150}
151
152impl ScriptPredeployLibraries {
153    pub const fn libraries_count(&self) -> usize {
154        match self {
155            Self::Default { onchain, .. } => onchain.len(),
156            Self::Create2 { onchain, .. } => onchain.len(),
157        }
158    }
159}
160
161/// Container for the linked contracts and their dependencies
162#[derive(Clone, Debug)]
163pub struct LinkedBuildData {
164    /// Original build data, might be used to relink this object with different libraries.
165    pub build_data: BuildData,
166    /// Known fully linked contracts.
167    pub known_contracts: ContractsByArtifact,
168    /// Libraries used to link the contracts.
169    pub libraries: Libraries,
170    /// Libraries that need to be deployed by sender before script execution.
171    pub predeploy_libraries: ScriptPredeployLibraries,
172    /// Source files of the contracts. Used by debugger.
173    pub sources: ContractSources,
174}
175
176impl LinkedBuildData {
177    pub fn new(
178        libraries: Libraries,
179        predeploy_libraries: ScriptPredeployLibraries,
180        mut build_data: BuildData,
181    ) -> Result<Self> {
182        let sources = ContractSources::from_project_output(
183            &build_data.output,
184            &build_data.project_root,
185            Some(&libraries),
186        )?;
187
188        let storage_layouts = namespaced_storage::project_storage_layouts(
189            &mut build_data.output,
190            &build_data.project_root,
191        );
192        let linked_contracts = build_data.get_linker().get_linked_artifacts(&libraries)?;
193        let known_contracts = ContractsByArtifactBuilder::new(
194            linked_contracts.iter().map(|(id, artifact)| (id.clone(), artifact.into())),
195        )
196        .with_storage_layouts(storage_layouts)
197        .build();
198
199        Ok(Self { build_data, known_contracts, libraries, predeploy_libraries, sources })
200    }
201
202    /// Fetches target bytecode from linked contracts.
203    pub fn get_target_contract(&self) -> Result<&ContractData> {
204        self.known_contracts
205            .get(&self.build_data.target)
206            .ok_or_eyre("target not found in linked artifacts")
207    }
208}
209
210/// First state basically containing only inputs of the user.
211pub struct PreprocessedState<FEN: FoundryEvmNetwork> {
212    pub args: ScriptArgs,
213    pub script_config: ScriptConfig<FEN>,
214    pub script_wallets: Wallets,
215    pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
216}
217
218impl<FEN: FoundryEvmNetwork> PreprocessedState<FEN> {
219    /// Parses user input and compiles the contracts depending on script target.
220    /// After compilation, finds exact [ArtifactId] of the target contract.
221    pub fn compile(self) -> Result<CompiledState<FEN>> {
222        let Self { args, script_config, script_wallets, browser_wallet } = self;
223        let project = script_config.config.project()?;
224
225        let mut target_name = args.target_contract.clone();
226
227        // If we've received correct path, use it as target_path
228        // Otherwise, parse input as <path>:<name> and use the path from the contract info, if
229        // present.
230        let target_path = if let Ok(path) = canonicalize_path(&args.path) {
231            path
232        } else {
233            let contract = ContractInfo::from_str(&args.path)?;
234            target_name = Some(contract.name.clone());
235            if let Some(path) = contract.path {
236                canonicalize_path(path)?
237            } else {
238                project.find_contract_path(contract.name.as_str())?
239            }
240        };
241
242        let sources_to_compile = source_files_iter(
243            project.paths.sources.as_path(),
244            MultiCompilerLanguage::FILE_EXTENSIONS,
245        );
246
247        let compiler = ProjectCompiler::new()
248            .allow_linked_libraries(script_config.config.allow_linked_libraries)
249            .external_compilers(&script_config.config)
250            .files(sources_to_compile)
251            .dynamic_test_linking(script_config.config.dynamic_test_linking);
252        let compiler = if is_builtin_compiler_source(&target_path) {
253            compiler.files([target_path.clone()])
254        } else {
255            compiler.target_files([target_path.clone()])
256        };
257        let output = compiler.compile(&project)?;
258
259        let mut target_id: Option<ArtifactId> = None;
260
261        // Find target artifact id by name and path in compilation artifacts.
262        for (id, contract) in output.artifact_ids().filter(|(id, _)| id.source == target_path) {
263            if let Some(name) = &target_name {
264                if id.name != *name {
265                    continue;
266                }
267            } else if contract.abi.as_ref().is_none_or(|abi| abi.is_empty())
268                || contract.bytecode.as_ref().is_none_or(|b| match &b.object {
269                    BytecodeObject::Bytecode(b) => b.is_empty(),
270                    BytecodeObject::Unlinked(_) => false,
271                })
272            {
273                // Ignore contracts with empty abi or linked bytecode of length 0 which are
274                // interfaces/abstract contracts/libraries.
275                continue;
276            }
277
278            if let Some(target) = target_id {
279                // We might have multiple artifacts for the same contract but with different
280                // solc versions. Their names will have form of {name}.0.X.Y, so we are
281                // stripping versions off before comparing them.
282                let target_name = target.name.split('.').next().unwrap();
283                let id_name = id.name.split('.').next().unwrap();
284                if target_name != id_name {
285                    eyre::bail!(
286                        "Multiple contracts in the target path. Please specify the contract name with `--tc ContractName`"
287                    );
288                }
289            }
290            target_id = Some(id);
291        }
292
293        let target = target_id.ok_or_eyre("Could not find target contract")?;
294
295        Ok(CompiledState {
296            args,
297            script_config,
298            script_wallets,
299            browser_wallet,
300            build_data: BuildData { output, target, project_root: project.root().to_path_buf() },
301        })
302    }
303}
304
305/// State after we have determined and compiled target contract to be executed.
306pub struct CompiledState<FEN: FoundryEvmNetwork> {
307    pub args: ScriptArgs,
308    pub script_config: ScriptConfig<FEN>,
309    pub script_wallets: Wallets,
310    pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
311    pub build_data: BuildData,
312}
313
314impl<FEN: FoundryEvmNetwork> CompiledState<FEN> {
315    /// Uses provided sender address to compute library addresses and link contracts with them.
316    pub async fn link(self) -> Result<LinkedState<FEN>> {
317        let Self { args, script_config, script_wallets, browser_wallet, build_data } = self;
318
319        let build_data = build_data.link(&script_config).await?;
320
321        Ok(LinkedState { args, script_config, script_wallets, browser_wallet, build_data })
322    }
323
324    /// Tries loading the resumed state from the cache files, skipping simulation stage.
325    pub async fn resume(mut self) -> Result<BundledState<FEN>> {
326        let endpoint = if self.args.multi {
327            if self.args.evm.rpc.rpc_url.is_some() {
328                sh_warn!(
329                    "Multichain resume submits and checks transactions through the RPC endpoints saved by the original run; `--rpc-url` is not used for that."
330                )?;
331            }
332            None
333        } else {
334            let fork_url = self.script_config.evm_opts.fork_url.clone().ok_or_eyre("Missing --fork-url field, if you were trying to broadcast a multi-chain sequence, please use --multi flag")?;
335            let provider = Arc::new(ProviderBuilder::<AnyNetwork>::new(&fork_url).build()?);
336            let chain = provider.get_chain_id().await?;
337            Some((fork_url, chain))
338        };
339        let chain = endpoint.as_ref().map(|(_, chain)| *chain);
340
341        let mut sequence = if self.sequence_exists(chain, false)? {
342            self.try_load_sequence(chain, false)?
343        } else {
344            // If the script was simulated, but there was no attempt to broadcast yet,
345            // read the script sequence from the `dry-run/` folder.
346            let mut sequence = self.try_load_sequence(chain, true)?;
347
348            // Promote the complete dry-run sequence before broadcasting it.
349            sequence.promote_to_broadcasted(
350                &self.script_config.config,
351                &self.args.sig,
352                &self.build_data.target,
353            )?;
354            sequence
355        };
356
357        // A single-chain resume reaches the chain through an explicit `--rpc-url` instead of the
358        // saved endpoint. A configured RPC only selects the chain.
359        if let Some((fork_url, chain)) = endpoint
360            && self.args.evm.rpc.rpc_url.is_some()
361        {
362            let saved = sequence.sequences()[0].chain;
363            if saved != chain {
364                eyre::bail!(
365                    "saved sequence is for chain {saved}, but `--rpc-url` is on chain {chain}"
366                );
367            }
368            sequence.set_rpc_override(fork_url);
369        }
370
371        let resolution = sequence.restore_delegated_pending(DelegatedResolution::new(
372            self.args.resume_attempt,
373            self.args.resume_tx_hash,
374            self.args.resume_retry,
375        )?)?;
376        if !self.args.batch {
377            if let Some((sequence_index, _, attempt_id, hash)) = resolution {
378                let provider = ProviderBuilder::<FEN::Network>::from_config_with_url(
379                    &self.script_config.config,
380                    sequence.rpc_url(sequence_index),
381                )?
382                .build()?;
383                let transaction = provider
384                    .get_transaction_by_hash(hash)
385                    .await?
386                    .context("resolved transaction is not available from the recovery endpoint")?;
387                sequence.resolve_delegated_hash(attempt_id, hash, &transaction)?;
388            }
389            let progress = ScriptProgress::default();
390            // Every sequence is reconciled even after one fails, so a failing chain does not leave
391            // the receipts of later chains unrecorded.
392            let mut errors = Vec::new();
393            for index in 0..sequence.sequences().len() {
394                // Returns the result of waiting for receipts, if anything is pending.
395                let waited = async {
396                    let provider = ProviderBuilder::<FEN::Network>::from_config_with_url(
397                        &self.script_config.config,
398                        sequence.rpc_url(index),
399                    )?
400                    .build()?;
401                    // A saved signed attempt whose response was lost before its hash was recorded
402                    // is reconciled before requesting signers when its receipt shows it was mined.
403                    for operation in 0..sequence.sequences()[index].transactions.len() {
404                        let deployment = &sequence.sequences()[index];
405                        if let Some(hash) =
406                            sequence.signed_payload(index, operation).map(|s| s.hash)
407                            && !deployment.pending.contains(&hash)
408                            && !deployment.reverted.contains(&hash)
409                            && !deployment.receipts.iter().any(|r| r.transaction_hash() == hash)
410                            && let Some(receipt) = provider.get_transaction_receipt(hash).await?
411                            && is_mined_receipt_for(&receipt, hash)
412                        {
413                            sequence.sequences_mut()[index].add_pending(operation, hash);
414                        }
415                    }
416                    if sequence.sequences()[index].pending.is_empty() {
417                        return Ok(None);
418                    }
419                    let (durable_hashes, replayable_hashes) = sequence.submission_hashes(index);
420                    let blocked = blocked_pending(sequence.sequences(), index);
421                    Ok::<_, eyre::Report>(Some(
422                        progress
423                            .wait_for_pending(
424                                index,
425                                &mut sequence.sequences_mut()[index],
426                                &provider,
427                                self.script_config.config.transaction_timeout,
428                                self.args.confirmations,
429                                (&durable_hashes, &replayable_hashes),
430                                &blocked,
431                            )
432                            .await,
433                    ))
434                }
435                .await;
436                let result = match waited {
437                    Ok(Some(result)) => {
438                        sequence.save(true, false)?;
439                        result.and_then(|()| sequence.ensure_delegated_outcomes_known(index))
440                    }
441                    Ok(None) => Ok(()),
442                    Err(err) => Err(err),
443                };
444                if let Err(err) = result {
445                    errors.push(sequence.label_error(index, err));
446                }
447            }
448            match errors.len() {
449                0 => {}
450                1 => return Err(errors.remove(0)),
451                _ => eyre::bail!("{}", errors.iter().format("\n")),
452            }
453        }
454        // Resume refuses new operations after a recorded revert. Saved attempts after it are still
455        // recovered, so it refuses here only once nothing is left to recover, and otherwise after
456        // the broadcast.
457        if let Some(err) = refused_after_revert(&sequence)
458            && (0..sequence.sequences().len())
459                .all(|index| remaining_operation_indices(&sequence, index).is_empty())
460        {
461            return Err(err);
462        }
463        for deployment in sequence.sequences() {
464            for hash in &deployment.reverted {
465                sh_warn!(
466                    "Transaction {hash} on chain {} reverted; resume will not resubmit it.",
467                    deployment.chain
468                )?;
469            }
470        }
471
472        // The local owners of transactions saved for owners on other machines approve them again
473        // when their approvals are void.
474        if !self.args.unlocked
475            && (!remaining_unsigned_transactions_for_recovery(&sequence).is_empty()
476                || sequence
477                    .sequences()
478                    .iter()
479                    .any(|deployment| !deployment.awaiting_owners.is_empty()))
480        {
481            self.script_wallets =
482                Wallets::new(self.args.wallets.get_multi_wallet().await?, self.args.evm.sender);
483            self.browser_wallet = self.args.wallets.browser_signer::<FEN::Network>().await?;
484
485            if self.args.evm.sender.is_none() {
486                let addresses = self.script_wallets.addresses();
487                let sender = self
488                    .args
489                    .maybe_load_private_key()?
490                    .or_else(|| (addresses.len() == 1).then(|| addresses[0]))
491                    .or_else(|| self.browser_wallet.as_ref().map(|wallet| wallet.address()));
492                if let Some(sender) = sender {
493                    self.script_config.update_sender(sender).await?;
494                }
495            }
496        }
497
498        let (args, build_data, script_wallets, browser_wallet, script_config, resume_script_error) =
499            if self.args.unlocked {
500                (
501                    self.args,
502                    self.build_data,
503                    self.script_wallets,
504                    self.browser_wallet,
505                    self.script_config,
506                    None,
507                )
508            } else {
509                let remaining_transactions =
510                    remaining_unsigned_transactions_for_recovery(&sequence);
511                let remaining_froms =
512                    remaining_transactions.iter().map(|tx| tx.sender).collect::<AddressHashSet>();
513                let expected_session_sender = script_session_expected_sender_if_configured(
514                    &self.script_config.tempo,
515                    &remaining_froms,
516                )?;
517                let session_scope = script_session_scope(
518                    &self.script_config.tempo,
519                    &self.args.wallets,
520                    expected_session_sender,
521                    &remaining_transactions,
522                )?;
523                let has_available_signers = has_available_script_signers(
524                    &self.script_wallets,
525                    session_scope,
526                    &remaining_transactions,
527                )?;
528                let has_available_signers = configurable_account_signers_available(
529                    &self.script_config,
530                    &sequence,
531                    &self.script_wallets,
532                    &remaining_transactions,
533                    session_scope,
534                    has_available_signers,
535                )
536                .await?;
537
538                if has_available_signers {
539                    (
540                        self.args,
541                        self.build_data,
542                        self.script_wallets,
543                        self.browser_wallet,
544                        self.script_config,
545                        None,
546                    )
547                } else {
548                    // IF we are missing required signers, execute script as we might need to
549                    // collect private keys from the execution.
550                    let mut state = self;
551                    state
552                        .script_config
553                        .update_tempo_session_sender(&state.args.wallets, state.args.evm.sender)
554                        .await?;
555                    let executed = state.link().await?.prepare_execution().await?.execute().await?;
556                    // A failed run may still have collected every signer, so broadcast decides
557                    // whether this error is fatal.
558                    let resume_script_error = (!executed.execution_result.success).then(|| {
559                        CallTraceDecoder::new()
560                            .revert_decoder
561                            .clone()
562                            .with_abis(executed.build_data.known_contracts.values().map(|c| &c.abi))
563                            .decode(
564                                &executed.execution_result.returned,
565                                executed.execution_result.exit_reason,
566                            )
567                    });
568                    (
569                        executed.args,
570                        executed.build_data.build_data,
571                        executed.script_wallets,
572                        executed.browser_wallet,
573                        executed.script_config,
574                        resume_script_error,
575                    )
576                }
577            };
578
579        // Collect libraries from sequence and link contracts with them.
580        let libraries = if sequence.is_multi() {
581            // Library linking is not supported for multi-chain sequences.
582            Libraries::default()
583        } else {
584            Libraries::parse(&sequence.sequences()[0].libraries)?
585        };
586
587        let linked_build_data = build_data.link_with_libraries(libraries)?;
588
589        Ok(BundledState {
590            args,
591            script_config,
592            script_wallets,
593            browser_wallet,
594            build_data: linked_build_data,
595            sequence,
596            resume_script_error,
597        })
598    }
599
600    fn try_load_sequence(
601        &self,
602        chain: Option<u64>,
603        dry_run: bool,
604    ) -> Result<ScriptSequenceKind<FEN::Network>> {
605        if let Some(chain) = chain {
606            ScriptSequenceKind::load_single(
607                &self.script_config.config,
608                &self.args.sig,
609                &self.build_data.target,
610                chain,
611                dry_run,
612                self.args.batch,
613            )
614        } else {
615            ScriptSequenceKind::load_multi(
616                &self.script_config.config,
617                &self.args.sig,
618                &self.build_data.target,
619                dry_run,
620                self.args.batch,
621            )
622        }
623    }
624
625    fn sequence_exists(&self, chain: Option<u64>, dry_run: bool) -> Result<bool> {
626        let paths = if let Some(chain) = chain {
627            ScriptSequence::<FEN::Network>::get_paths(
628                &self.script_config.config,
629                &self.args.sig,
630                &self.build_data.target,
631                chain,
632                dry_run,
633            )?
634        } else {
635            MultiChainSequence::<FEN::Network>::get_paths(
636                &self.script_config.config,
637                &self.args.sig,
638                &self.build_data.target,
639                dry_run,
640            )?
641        };
642        Ok(compatibility_progress_exists(&paths) || recovery_exists(&paths)?)
643    }
644}
645
646fn compatibility_progress_exists(paths: &(PathBuf, PathBuf)) -> bool {
647    [&paths.0, &paths.1].into_iter().any(|path| progress_exists(path))
648}
649
650fn progress_exists(path: &Path) -> bool {
651    path.exists() || path.with_extension("previous").exists()
652}
653
654/// Returns the sender and chain that the selected Tempo session signs for, if any. The session is
655/// not resolved when no transaction remains.
656///
657/// `Wallets` only tracks signers collected from CLI options and script cheatcodes. A Tempo
658/// session signer lives in the Accounts store instead, so resume treats the session root account
659/// as available only on the chain covered by the session.
660fn script_session_scope(
661    tempo: &TempoOpts,
662    wallets: &MultiWalletOpts,
663    expected_sender: Option<Address>,
664    remaining: &[SignerScope],
665) -> Result<Option<SignerScope>> {
666    if remaining.is_empty() {
667        return Ok(None);
668    }
669    Ok(tempo
670        .session_signer_for_multi_wallet_any_chain(wallets, expected_sender)?
671        .map(|s| SignerScope::new(s.session.chain_id, s.access_key.account())))
672}
673
674/// Returns whether every scoped signer needed for resume is already available: a wallet of the
675/// sender, or the session in `session_scope`.
676fn has_available_script_signers(
677    script_wallets: &Wallets,
678    session_scope: Option<SignerScope>,
679    remaining: &[SignerScope],
680) -> Result<bool> {
681    let signers = script_wallets
682        .signers()
683        .map_err(|e| eyre::eyre!("Failed to get available signers: {}", e))?;
684    if remaining.is_empty() {
685        return Ok(true);
686    }
687
688    Ok(remaining.iter().all(|tx| signers.contains(&tx.sender) || session_scope == Some(*tx)))
689}
690
691/// Returns whether broadcast can sign every remaining transaction without running the script,
692/// given whether the wallets, sessions and access keys cover every sender (`available`).
693///
694/// The session in `session_scope` signs for its sender before any owner keys do, as broadcast
695/// selects it first, even for an upgraded account. On Tempo, any other sender that the chain
696/// reports as a configurable account signs with its owners, even when its own key is among the
697/// wallets, as the retired root key of an upgraded EOA is. It is ready only when its owner keys
698/// among the wallets, `--tempo.owner` and the Tempo Accounts store reach its threshold. Resume
699/// only publishes the saved transactions, so it runs the script again only to collect signers,
700/// such as keys from `vm.rememberKey`. When detection fails, resume runs the script as before.
701async fn configurable_account_signers_available<FEN: FoundryEvmNetwork>(
702    script_config: &ScriptConfig<FEN>,
703    sequence: &ScriptSequenceKind<FEN::Network>,
704    script_wallets: &Wallets,
705    remaining: &[SignerScope],
706    session_scope: Option<SignerScope>,
707    available: bool,
708) -> Result<bool> {
709    let tempo = &script_config.tempo;
710    if !script_config.evm_opts.networks.is_tempo() || tempo.eoa || remaining.is_empty() {
711        return Ok(available);
712    }
713    let signers = script_wallets
714        .signers()
715        .map_err(|e| eyre::eyre!("Failed to get available signers: {}", e))?;
716    let config = tempo.configurable_account_config.as_deref().map(parse_config).transpose()?;
717    // Broadcast also signs with the `--tempo.owner` keys.
718    let Ok(owners) = tempo.owner_signers().await else { return Ok(false) };
719    let keys =
720        signers.iter().copied().chain(owners.iter().map(Signer::address)).collect::<Vec<_>>();
721    let mut scopes = remaining.to_vec();
722    scopes.sort_unstable_by_key(|scope| (scope.chain, scope.sender));
723    scopes.dedup();
724    scopes.retain(|scope| session_scope != Some(*scope));
725    for scope in scopes {
726        let own_key = signers.contains(&scope.sender);
727        // As in broadcast, the configurable account options describe the account they name.
728        let explicit = !own_key || tempo.configurable_account == Some(scope.sender);
729        if !own_key && tempo.configurable_account.is_some_and(|account| account != scope.sender) {
730            return Ok(false);
731        }
732        // The endpoint broadcast uses, which honours `--rpc-url` on a single-chain resume.
733        let Some(rpc_url) = (0..sequence.sequences().len())
734            .find(|&i| sequence.sequences()[i].chain == scope.chain)
735            .map(|i| sequence.rpc_url(i))
736        else {
737            return Ok(false);
738        };
739        let provider =
740            ProviderBuilder::<TempoNetwork>::from_config_with_url(&script_config.config, rpc_url)?
741                .build()?;
742        let detected = detect_configurable_account(
743            &provider,
744            scope.sender,
745            &keys,
746            if explicit { config.clone() } else { None },
747            false,
748            BlockId::latest(),
749        )
750        .await;
751        match detected {
752            Ok(Some(config)) => {
753                let keys = keys
754                    .iter()
755                    .copied()
756                    .chain(stored_owner_keys(scope.chain, &config).iter().map(|key| key.address()))
757                    .collect::<Vec<_>>();
758                if !reaches_threshold(&config, &keys) {
759                    return Ok(false);
760                }
761            }
762            // Not a configurable account: its own key, a session or an access key signs.
763            Ok(None) if own_key || available => {}
764            _ => return Ok(false),
765        }
766    }
767    Ok(true)
768}
769
770#[cfg(test)]
771mod tests {
772    use super::*;
773
774    #[test]
775    fn backup_counts_as_recoverable_progress() {
776        let dir = tempfile::tempdir().unwrap();
777        let path = dir.path().join("run-latest.json");
778        std::fs::write(path.with_extension("previous"), b"{}").unwrap();
779
780        assert!(progress_exists(&path));
781    }
782
783    #[test]
784    fn sensitive_export_counts_as_recoverable_progress() {
785        let dir = tempfile::tempdir().unwrap();
786        let paths = (dir.path().join("run-latest.json"), dir.path().join("run-latest-cache.json"));
787        std::fs::write(&paths.1, b"{}").unwrap();
788
789        assert!(compatibility_progress_exists(&paths));
790    }
791
792    #[test]
793    fn script_session_scope_skips_session_resolution_when_remaining_empty() {
794        let scope = script_session_scope(
795            &TempoOpts { session: Some(B256::repeat_byte(0x99)), ..Default::default() },
796            &MultiWalletOpts::default(),
797            None,
798            &[],
799        )
800        .unwrap();
801
802        assert_eq!(scope, None);
803        assert!(
804            has_available_script_signers(&Wallets::new(Default::default(), None), scope, &[])
805                .unwrap()
806        );
807    }
808}