Skip to main content

forge_script/
owner_approvals.rs

1//! Tempo configurable account senders whose owners approve on separate machines.
2//!
3//! When the local owner keys of a configurable account sender do not reach its threshold,
4//! `--broadcast` first simulates the remaining operations in order up to the account's last
5//! transaction and fixes the gas limit of each of the account's transactions. It then sends the
6//! operations before the account's first transaction, approves the account's remaining
7//! transactions with the local owners and saves them as [`AwaitingOwners`] in the sequence
8//! instead of sending them. The other owners sign the printed digests elsewhere. `--resume` adds
9//! the approvals given with `--tempo.owner-signature` and, once every saved transaction reaches
10//! the threshold, the broadcast sends them in order with `0x05` signatures built from the
11//! approvals.
12
13use crate::{
14    broadcast::{
15        SendTransactionKind, convert_tempo_aa_create, estimate_gas, remaining_operation_indices,
16    },
17    sequence::ScriptSequenceKind,
18};
19use alloy_consensus::{BlockHeader, SignableTransaction};
20use alloy_eips::{
21    BlockNumberOrTag,
22    eip2718::{Decodable2718, Encodable2718},
23};
24use alloy_network::{BlockResponse, Network, NetworkTransactionBuilder, TransactionBuilder};
25use alloy_primitives::{Address, B256, Bytes, TxHash, map::HashMap};
26use alloy_provider::{Provider, RootProvider};
27use alloy_rpc_types::simulate::{SimBlock, SimCallResult, SimulatePayload, SimulatedBlock};
28use alloy_signer::Signature;
29use eyre::{Context, ContextCompat, Result, bail};
30use forge_script_sequence::{AwaitingOwners, ScriptSequence};
31use foundry_cli::utils::apply_gas_estimate_multiplier;
32use foundry_common::{
33    FoundryTransactionBuilder,
34    provider::ProviderBuilder,
35    shell,
36    tempo::{
37        configurable_account::{
38            ConfigurableAccountOwnerKey, combine_approvals, decode_unsigned_tx, has_config,
39            parse_owner_signature, prepare_request, reaches_threshold, simulation_spec,
40            updates_config,
41        },
42        resolve_and_set_fee_token,
43    },
44};
45use foundry_config::Config;
46use itertools::Itertools;
47use serde_json::Value;
48use std::collections::{BTreeMap, BTreeSet};
49use tempo_alloy::TempoNetwork;
50use tempo_primitives::{
51    TempoTxEnvelope,
52    transaction::{
53        ConfigurableAccountConfig, PrimitiveSignature, TempoSignature, TempoTransaction,
54        configurable_account_digest,
55    },
56};
57
58/// The most blocks a node simulates in one `eth_simulateV1` request.
59const MAX_SIMULATED_BLOCKS: usize = 256;
60
61/// How to raise a node's limits on one `eth_simulateV1` request.
62const GAS_CAP_HINT: &str = "the node may cap the gas of a whole simulation request, such as \
63     reth's --rpc.gascap (50,000,000 by default), or its number of simulated blocks; raise them \
64     or use an RPC without these limits";
65
66/// A configurable account sender whose local owner keys do not form a quorum that Tempo accepts,
67/// so that the other owners approve its transactions elsewhere.
68#[derive(Clone, Debug)]
69pub struct OfflineOwners {
70    pub(crate) account: Address,
71    pub(crate) config: ConfigurableAccountConfig,
72    /// The local owner keys, which approve when the transactions are saved.
73    pub(crate) keys: Vec<ConfigurableAccountOwnerKey>,
74}
75
76impl OfflineOwners {
77    /// Makes `tx` a Tempo transaction from the account. The owners that will approve are not
78    /// known yet, so its gas models the largest quorum.
79    fn prepare_request<N: Network>(&self, tx: &mut N::TransactionRequest)
80    where
81        N::TransactionRequest: FoundryTransactionBuilder<N>,
82    {
83        prepare_request::<N>(tx, self.account, simulation_spec(self.account, &self.config, &[]));
84    }
85}
86
87/// Tells whether a saved transaction's approvals do not reach its threshold yet.
88pub(crate) fn awaits_approvals<N: Network>(sequence: &ScriptSequenceKind<N>) -> bool
89where
90    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
91{
92    // An entry that does not decode fails when it is sent.
93    sequence.sequences().iter().flat_map(|deployment| &deployment.awaiting_owners).any(|entry| {
94        decode_entry(entry).is_ok_and(|(_, config, _, approvals)| {
95            !reaches_threshold(&config, &approvals.into_keys().collect::<Vec<_>>())
96        })
97    })
98}
99
100/// Returns the payload of operation `index` of `deployment` signed with its owners' approvals,
101/// and its hash, when it was saved for its owners. The signature is rebuilt from the saved
102/// approvals, as [`combine_approvals`] selects them the same way every time.
103pub(crate) fn approved_payload<N: Network>(
104    deployment: &ScriptSequence<N>,
105    index: usize,
106) -> Result<Option<(Bytes, TxHash)>> {
107    let Some(entry) = deployment.awaiting_owners.iter().find(|entry| entry.index == index) else {
108        return Ok(None);
109    };
110    let (tx, config, _, approvals) = decode_entry(entry)?;
111    let signature = combine_approvals(
112        entry.account,
113        &config,
114        tx.signature_hash(),
115        approvals.into_values().collect(),
116    )?;
117    let payload = Bytes::from(
118        TempoTxEnvelope::AA(tx.into_signed(TempoSignature::ConfigurableAccount(signature)))
119            .encoded_2718(),
120    );
121    let hash = N::TxEnvelope::decode_2718_exact(&payload)
122        .wrap_err("invalid transaction signed with owner approvals")?
123        .trie_hash();
124    Ok(Some((payload, hash)))
125}
126
127/// A transaction of a configurable account with offline owners whose gas limit is fixed, to be
128/// saved for its owners once the operations before it are sent.
129pub(crate) struct Awaiting<'a, N: Network> {
130    request: N::TransactionRequest,
131    index: usize,
132    owners: &'a OfflineOwners,
133}
134
135/// Fixes the gas limits of the transactions of configurable accounts with offline owners, before
136/// anything is sent.
137///
138/// `transactions` are the remaining operations of sequence `sequence_index`, in order. They are
139/// simulated in order up to the last one with offline owners, in one block or else one per block,
140/// so that each gas limit succeeds after the operations before it, which are not sent yet. Fails
141/// when one of them fails, when they fit neither in one block nor in as many blocks as a node
142/// simulates, when one would change its account's configuration before another transaction of
143/// the account, or when an account already sent the nonce planned for its first transaction.
144pub(crate) async fn prepare<'a, N: Network>(
145    sequence: &ScriptSequenceKind<N>,
146    sequence_index: usize,
147    provider: &RootProvider<N>,
148    transactions: &[(SendTransactionKind<'a, N>, bool, usize)],
149    gas_estimate_multiplier: u64,
150) -> Result<Vec<Awaiting<'a, N>>>
151where
152    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
153    N::TransactionRequest: FoundryTransactionBuilder<N> + serde::Serialize,
154{
155    let offline = |kind: &SendTransactionKind<'a, N>| match kind {
156        SendTransactionKind::OfflineOwners(_, owners) => Some(*owners),
157        _ => None,
158    };
159    let Some(last) = transactions.iter().rposition(|(kind, ..)| offline(kind).is_some()) else {
160        return Ok(Vec::new());
161    };
162    let transactions = &transactions[..=last];
163
164    let mut requests = Vec::with_capacity(transactions.len());
165    let mut accounts = BTreeSet::new();
166    for (position, (kind, is_fixed_gas_limit, index)) in transactions.iter().enumerate() {
167        let planned = &sequence.sequences()[sequence_index].transactions[*index];
168        let mut request = match kind {
169            SendTransactionKind::OfflineOwners(tx, owners) => {
170                let mut tx = tx.clone();
171                owners.prepare_request::<N>(&mut tx);
172                // The account's transactions sent before its first one here have lower nonces, so
173                // a next nonce above the planned one means the account spent it elsewhere.
174                // `export` checks that it is equal once they are sent.
175                if accounts.insert(owners.account) {
176                    let nonce = tx.nonce().context("transaction is missing its planned nonce")?;
177                    let next = provider.get_transaction_count(owners.account).await?;
178                    if nonce < next {
179                        bail!(
180                            "transaction {index} of {} was planned with nonce {nonce}, but the \
181                             account already sent nonce {nonce}, as its next nonce is {next}; \
182                             broadcast the script anew with --start-fresh",
183                            owners.account
184                        );
185                    }
186                }
187                // The owners approve with the account's current configuration, which this
188                // transaction would change for the ones after it.
189                if updates_config(tx.to(), tx.input())
190                    && transactions[position + 1..].iter().any(|(kind, ..)| {
191                        offline(kind).is_some_and(|other| other.account == owners.account)
192                    })
193                {
194                    bail!(
195                        "transaction {index} changes the configuration of {}, whose owners \
196                         approve on other machines, before its other transactions: their \
197                         approvals would be void once it is sent, so it must be the account's \
198                         last transaction in the script",
199                        owners.account
200                    );
201                }
202                tx
203            }
204            SendTransactionKind::ConfigurableAccount(tx, account) => {
205                let mut tx = tx.clone();
206                account.prepare_request::<N>(&mut tx);
207                tx
208            }
209            SendTransactionKind::Raw(tx, _)
210            | SendTransactionKind::Unlocked(tx)
211            | SendTransactionKind::Browser(tx, _)
212            | SendTransactionKind::AccessKey(tx, _) => tx.clone(),
213            SendTransactionKind::Signed(tx) => tx.clone().into(),
214            SendTransactionKind::PreparedRaw(payload, _) => {
215                N::TxEnvelope::decode_2718_exact(payload)?.into()
216            }
217        };
218        if let Some(from) = planned.tx().from() {
219            request.set_from(from);
220        }
221        let from = request.from();
222        resolve_and_set_fee_token(Some(provider), &mut request, from).await?;
223        convert_tempo_aa_create::<N>(&mut request);
224        if !is_fixed_gas_limit {
225            request.reset_gas_limit();
226        }
227        requests.push(request);
228    }
229    // The gas limits that the owners approve, which are fixed here.
230    let adjusted = transactions
231        .iter()
232        .map(|(kind, is_fixed_gas_limit, _)| offline(kind).is_some() && !is_fixed_gas_limit)
233        .collect::<Vec<_>>();
234
235    // Every simulation runs on the same block, so that the limits fixed stay valid.
236    let latest = provider
237        .get_block_by_number(BlockNumberOrTag::Latest)
238        .await?
239        .context("the latest block is missing")?;
240    let (block, block_gas_limit) = (latest.header().number(), latest.header().gas_limit());
241    for (position, request) in requests.iter().enumerate() {
242        if offline(&transactions[position].0).is_some()
243            && let Some(valid_before) = request.valid_before()
244            && latest.header().timestamp() >= valid_before.get()
245        {
246            bail!(
247                "transaction {} would be saved for owners to approve with the deadline \
248                 {valid_before}, which has passed",
249                transactions[position].2
250            );
251        }
252    }
253    // All of them run in one block, as they fit in one on a node with a large block gas limit.
254    // When they do not, each runs in a block of its own, as a node simulates at most
255    // `MAX_SIMULATED_BLOCKS` blocks.
256    let mut per_call = false;
257    let calls = match simulate(provider, &requests, block, false).await {
258        Ok(calls) if calls.iter().all(|call| call.status) => Ok(calls),
259        _ if requests.len() > 1 && requests.len() <= MAX_SIMULATED_BLOCKS => {
260            per_call = true;
261            simulate(provider, &requests, block, true).await
262        }
263        Err(error) if requests.len() > MAX_SIMULATED_BLOCKS => Err(error.wrap_err(format!(
264            "the {} transactions do not fit in one simulated block, and a node simulates at \
265             most {MAX_SIMULATED_BLOCKS} blocks; split the script so that at most \
266             {MAX_SIMULATED_BLOCKS} operations run up to the last transaction of a configurable \
267             account with offline owners",
268            requests.len()
269        ))),
270        single => single,
271    };
272    let calls = match calls {
273        Ok(calls) => calls,
274        // A single transaction does not depend on unsent ones, so it can be estimated without
275        // `eth_simulateV1`.
276        Err(_) if requests.len() == 1 => {
277            if adjusted[0] {
278                estimate_gas(&mut requests[0], provider, gas_estimate_multiplier, false, false)
279                    .await?;
280            }
281            return Ok(awaiting(transactions, requests));
282        }
283        Err(error) => bail!(
284            "cannot simulate the transactions in order to fix the gas limits of the ones \
285             awaiting owner approvals, so no more transactions are sent: {error}"
286        ),
287    };
288    // The first call that fails, as an error.
289    let fails = |calls: &[SimCallResult]| {
290        calls.iter().position(|call| !call.status).map(|position| {
291            let message = calls[position].error.as_ref().map_or("reverted", |e| e.message.as_str());
292            // A node can lower the gas limits to its cap for the whole request.
293            let hint = if message.to_lowercase().contains("out of gas") {
294                format!("; {GAS_CAP_HINT}")
295            } else {
296                String::new()
297            };
298            let error = eyre::eyre!(
299                "transaction {} fails when simulated after the transactions before it, so no \
300                 more transactions are sent or saved for owners to approve: {message}{hint}",
301                transactions[position].2
302            );
303            (position, error)
304        })
305    };
306    if let Some((_, error)) = fails(&calls) {
307        return Err(error);
308    }
309
310    // Gas used is not the gas a call needs to start with, as calls keep back 1/64 of their gas,
311    // so the limits are checked together, and the first one that fails is raised to the least
312    // that succeeds until they all do.
313    // The gas a call can be given: in one block, what the calls before it leave of it.
314    let room = |calls: &[SimCallResult], position: usize| {
315        let used =
316            if per_call { 0 } else { calls[..position].iter().map(|call| call.gas_used).sum() };
317        block_gas_limit.saturating_sub(used)
318    };
319    for (position, call) in calls.iter().enumerate() {
320        if adjusted[position] {
321            let used = call.max_used_gas.unwrap_or_default().max(call.gas_used);
322            let gas_limit = apply_gas_estimate_multiplier(used, Some(gas_estimate_multiplier))?;
323            requests[position].set_gas_limit(gas_limit.min(room(&calls, position)));
324        }
325    }
326    // Each fixed limit succeeds after the ones before it, so the first failure moves forward.
327    let mut fixed = None;
328    loop {
329        let calls = simulate(provider, &requests, block, per_call).await?;
330        let Some((position, error)) = fails(&calls) else { break };
331        let index = transactions[position].2;
332        if !adjusted[position] || fixed.is_some_and(|fixed| position <= fixed) {
333            return Err(error);
334        }
335        let gas_limit = least_gas_limit(
336            provider,
337            &mut requests[..=position],
338            block,
339            per_call,
340            room(&calls, position),
341            gas_estimate_multiplier,
342        )
343        .await
344        .wrap_err_with(|| format!("cannot fix the gas limit of transaction {index}"))?;
345        requests[position].set_gas_limit(gas_limit);
346        fixed = Some(position);
347    }
348    Ok(awaiting(transactions, requests))
349}
350
351/// The transactions with offline owners among `transactions`, with their prepared requests.
352fn awaiting<'a, N: Network>(
353    transactions: &[(SendTransactionKind<'a, N>, bool, usize)],
354    requests: Vec<N::TransactionRequest>,
355) -> Vec<Awaiting<'a, N>> {
356    transactions
357        .iter()
358        .zip(requests)
359        .filter_map(|((kind, _, index), request)| match kind {
360            SendTransactionKind::OfflineOwners(_, owners) => {
361                Some(Awaiting { request, index: *index, owners })
362            }
363            _ => None,
364        })
365        .collect()
366}
367
368/// Saves the transactions of configurable accounts with offline owners that [`prepare`] fixed,
369/// approved by their local owners, for the other owners to approve instead of sending them.
370/// Other operations are left for `--resume`.
371pub(crate) async fn export<N: Network>(
372    sequence: &mut ScriptSequenceKind<N>,
373    sequence_index: usize,
374    provider: &RootProvider<N>,
375    awaiting: Vec<Awaiting<'_, N>>,
376) -> Result<()>
377where
378    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
379    N::TransactionRequest: FoundryTransactionBuilder<N>,
380    N::UnsignedTx: SignableTransaction<Signature>,
381{
382    let mut next_nonces = HashMap::<Address, u64>::default();
383    let mut saved = Vec::with_capacity(awaiting.len());
384    for Awaiting { request, index, owners } in awaiting {
385        let account = owners.account;
386        // The operations before it are sent by now.
387        let nonce = request.nonce().context("transaction is missing its planned nonce")?;
388        let expected = match next_nonces.get(&account) {
389            Some(nonce) => *nonce,
390            None => provider.get_transaction_count(account).await?,
391        };
392        if nonce != expected {
393            bail!(
394                "transaction {index} of {account} was planned with nonce {nonce}, but the \
395                 account's next nonce is {expected}"
396            );
397        }
398        next_nonces.insert(account, nonce + 1);
399
400        let unsigned = request.build_unsigned().map_err(|error| eyre::eyre!("{}", error.error))?;
401        let unsigned_tx = unsigned.encoded_for_signing();
402        let digest =
403            configurable_account_digest(unsigned.signature_hash(), account, owners.config.version);
404        // A `0x05` signature only signs Tempo (`0x76`) transactions.
405        decode_unsigned_tx(&unsigned_tx)?;
406        let mut approvals = Vec::with_capacity(owners.keys.len());
407        for key in &owners.keys {
408            let approval = key.sign(&digest).await.wrap_err_with(|| {
409                format!("owner {} failed to approve transaction {index}", key.address())
410            })?;
411            approvals.push(approval.to_bytes());
412        }
413        saved.push(AwaitingOwners {
414            index,
415            account,
416            config: (&owners.config).into(),
417            unsigned_tx: unsigned_tx.into(),
418            digest,
419            approvals,
420        });
421    }
422
423    sequence.sequences_mut()[sequence_index].awaiting_owners.extend(saved);
424    sequence.save(true, false)?;
425    report(sequence)
426}
427
428/// Simulates `requests` in order on top of `block`, so that each runs on the state the ones
429/// before it leave: all in one block, or each in a block of its own when `per_call` is set.
430async fn simulate<N: Network>(
431    provider: &RootProvider<N>,
432    requests: &[N::TransactionRequest],
433    block: u64,
434    per_call: bool,
435) -> Result<Vec<SimCallResult>>
436where
437    N::TransactionRequest: FoundryTransactionBuilder<N> + serde::Serialize,
438{
439    let block_state_calls = if per_call {
440        requests
441            .iter()
442            .map(|request| SimBlock { calls: vec![request.clone()], ..Default::default() })
443            .collect()
444    } else {
445        vec![SimBlock { calls: requests.to_vec(), ..Default::default() }]
446    };
447    let payload = SimulatePayload { block_state_calls, ..Default::default() };
448    let calls = provider
449        .raw_request::<_, Vec<SimulatedBlock<Value>>>(
450            "eth_simulateV1".into(),
451            (payload, BlockNumberOrTag::Number(block)),
452        )
453        .await
454        .map_err(|error| match error.as_error_resp() {
455            Some(response) if response.code == -38026 => eyre::eyre!(
456                "eth_simulateV1 failed with -38026 ({}): the transactions use more gas or \
457                 blocks than the RPC allows in one request; {GAS_CAP_HINT}",
458                response.message
459            ),
460            _ => error.into(),
461        })?
462        .into_iter()
463        .flat_map(|block| block.calls)
464        .collect::<Vec<_>>();
465    if calls.len() != requests.len() {
466        bail!("eth_simulateV1 returned an unexpected number of results");
467    }
468    Ok(calls)
469}
470
471/// Returns the least gas limit with which the last of `requests` succeeds after the ones before
472/// it, found as `eth_estimateGas` does and raised by `multiplier` percent, up to `cap`. The last
473/// request fails with its current gas limit.
474async fn least_gas_limit<N: Network>(
475    provider: &RootProvider<N>,
476    requests: &mut [N::TransactionRequest],
477    block: u64,
478    per_call: bool,
479    cap: u64,
480    multiplier: u64,
481) -> Result<u64>
482where
483    N::TransactionRequest: FoundryTransactionBuilder<N> + serde::Serialize,
484{
485    let succeeds = async |requests: &mut [N::TransactionRequest], gas: u64| -> Result<bool> {
486        requests.last_mut().expect("a request").set_gas_limit(gas);
487        Ok(simulate(provider, requests, block, per_call).await?.last().expect("a result").status)
488    };
489    let mut low = requests.last().and_then(|request| request.gas_limit()).unwrap_or_default();
490    if low >= cap || !succeeds(requests, cap).await? {
491        bail!(
492            "it fails after the transactions before it even with gas limit {cap}, the gas left \
493             in the block; \
494             {GAS_CAP_HINT}"
495        );
496    }
497    let mut high = cap;
498    // Within 1% of the least gas limit, as `eth_estimateGas` does.
499    while high - low > (low / 100).max(1) {
500        let middle = low + (high - low) / 2;
501        if succeeds(requests, middle).await? {
502            high = middle;
503        } else {
504            low = middle;
505        }
506    }
507    Ok(apply_gas_estimate_multiplier(high, Some(multiplier))?.max(high).min(cap))
508}
509
510/// Adds the owner approvals in `signatures` to the transactions awaiting their owners, and checks
511/// that every one of them that was not sent yet reaches its threshold and can still be sent. The
512/// broadcast then sends them in order, signed with the approvals, recording each as a submission
513/// attempt only then.
514///
515/// The valid approvals are saved first, so that they can be collected over several runs, and the
516/// same signatures can be given again. Fails before anything is sent when a signature approves
517/// none of the transactions, when one of them lacks approvals, or when the account spent a planned
518/// nonce. When the account's configuration changed, a deadline passed, or the base fee rose above
519/// the fee the owners approved, the unsent transactions of that sequence are dropped, so that the
520/// broadcast saves them again for the owners to approve with new digests.
521pub(crate) async fn assemble<N: Network>(
522    sequence: &mut ScriptSequenceKind<N>,
523    signatures: &[String],
524    config: &Config,
525) -> Result<()>
526where
527    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
528{
529    if sequence.sequences().iter().all(|deployment| deployment.awaiting_owners.is_empty()) {
530        if !signatures.is_empty() {
531            bail!("--tempo.owner-signature is given, but no transaction awaits owner approvals");
532        }
533        return Ok(());
534    }
535    let signatures = signatures
536        .iter()
537        .enumerate()
538        .map(|(position, value)| {
539            parse_owner_signature(value)
540                .wrap_err_with(|| format!("invalid --tempo.owner-signature {}", position + 1))
541        })
542        .collect::<Result<Vec<_>>>()?;
543
544    let mut used = vec![false; signatures.len()];
545    for deployment in sequence.sequences_mut() {
546        for entry in &mut deployment.awaiting_owners {
547            let (_, owners_config, digest, mut approvals) = decode_entry(entry)?;
548            for (signature, used) in signatures.iter().zip(&mut used) {
549                if let Ok(owner) = signature.recover_signer(&digest)
550                    && owners_config.owner_weight(owner).is_some()
551                {
552                    approvals.insert(owner, signature.clone());
553                    *used = true;
554                }
555            }
556            entry.approvals = approvals.values().map(PrimitiveSignature::to_bytes).collect();
557        }
558    }
559    sequence.save(true, false)?;
560    if let Some(position) = used.iter().position(|used| !used) {
561        bail!(
562            "--tempo.owner-signature {} is not an owner's approval of any transaction awaiting \
563             owner approvals: it must sign one of their digests with an owner key\n{}",
564            position + 1,
565            describe(sequence)?
566        );
567    }
568
569    // Every transaction left to send is checked, as its account may have sent others since. One
570    // with a recorded submission attempt is recovered like any other sent transaction.
571    for sequence_index in 0..sequence.sequences().len() {
572        let remaining = remaining_operation_indices(sequence, sequence_index);
573        let unsent = sequence.sequences()[sequence_index]
574            .awaiting_owners
575            .iter()
576            .map(|entry| entry.index)
577            .filter(|&index| {
578                remaining.contains(&index)
579                    && sequence.signed_payload(sequence_index, index).is_none()
580            })
581            .collect::<BTreeSet<_>>();
582        if unsent.is_empty() {
583            continue;
584        }
585        let provider = ProviderBuilder::<TempoNetwork>::from_config_with_url(
586            config,
587            sequence.rpc_url(sequence_index),
588        )?
589        .build()?;
590        let entries = || {
591            sequence.sequences()[sequence_index]
592                .awaiting_owners
593                .iter()
594                .filter(|entry| unsent.contains(&entry.index))
595        };
596        // The next nonce of each account, or `None` when its configuration changed. The unsent
597        // transactions of an account share one configuration, as one export saved them together
598        // and a void drops all of them, so it is read once per account.
599        let mut next_nonces = HashMap::<_, _>::default();
600        for entry in entries() {
601            if next_nonces.contains_key(&entry.account) {
602                continue;
603            }
604            let (_, owners_config, ..) = decode_entry(entry)?;
605            let next_nonce = if has_config(&provider, entry.account, &owners_config).await? {
606                Some(provider.get_transaction_count(entry.account).await?)
607            } else {
608                None
609            };
610            next_nonces.insert(entry.account, next_nonce);
611        }
612        // Read after the accounts, so that a deadline that passes meanwhile is not missed.
613        let latest = provider
614            .get_block_by_number(BlockNumberOrTag::Latest)
615            .await?
616            .context("the latest block is missing")?;
617        for entry in entries() {
618            if let Some(reason) = void_reason(entry, next_nonces[&entry.account], latest.header())?
619            {
620                sh_warn!(
621                    "{reason} after transaction {} was saved for the owners of {}, so their \
622                     approvals are void; the unsent transactions are saved again for the owners \
623                     to approve, with new digests, when --resume is given the local owner keys \
624                     and Tempo options of the original --broadcast",
625                    entry.index,
626                    entry.account
627                )?;
628                sequence.sequences_mut()[sequence_index]
629                    .awaiting_owners
630                    .retain(|entry| !unsent.contains(&entry.index));
631                sequence.save(true, false)?;
632                break;
633            }
634        }
635    }
636
637    if awaits_approvals(sequence) {
638        bail!(
639            "transactions await more owner approvals, so nothing was sent\n{}",
640            describe(sequence)?
641        );
642    }
643    Ok(())
644}
645
646/// Tells why a saved transaction can no longer be sent with its owners' approvals: its
647/// account's configuration or nonce, its deadline or the base fee changed on chain.
648/// `next_nonce` is the account's next nonce, or `None` when its configuration changed, and
649/// `latest` the latest block, read after them.
650///
651/// The account's planned nonces cannot change, so a spent nonce fails here.
652fn void_reason(
653    entry: &AwaitingOwners,
654    next_nonce: Option<u64>,
655    latest: &impl BlockHeader,
656) -> Result<Option<String>> {
657    let (tx, ..) = decode_entry(entry)?;
658    let account = entry.account;
659    let Some(next_nonce) = next_nonce else {
660        return Ok(Some(format!("the configuration of {account} changed")));
661    };
662    if next_nonce > tx.nonce {
663        bail!(
664            "{account} sent nonce {} after transaction {} was saved for its owners, so their \
665             approvals are void, and the remaining transactions cannot be sent with the nonces \
666             the script planned; broadcast the script anew with --start-fresh",
667            tx.nonce,
668            entry.index
669        );
670    }
671    if let Some(valid_before) = tx.valid_before
672        && latest.timestamp() >= valid_before.get()
673    {
674        return Ok(Some(format!("its deadline {valid_before} passed")));
675    }
676    if let Some(base_fee) = latest.base_fee_per_gas()
677        && u128::from(base_fee) > tx.max_fee_per_gas
678    {
679        return Ok(Some(format!(
680            "the base fee rose to {base_fee}, above its max fee per gas {}",
681            tx.max_fee_per_gas
682        )));
683    }
684    Ok(None)
685}
686
687/// Decodes a saved transaction, its configuration and the owners' approvals, and checks its
688/// digest.
689fn decode_entry(
690    entry: &AwaitingOwners,
691) -> Result<(
692    TempoTransaction,
693    ConfigurableAccountConfig,
694    B256,
695    BTreeMap<Address, PrimitiveSignature>,
696)> {
697    let tx = decode_unsigned_tx(&entry.unsigned_tx)?;
698    let config = ConfigurableAccountConfig::try_from(entry.config.clone())?;
699    let digest = configurable_account_digest(tx.signature_hash(), entry.account, config.version);
700    if digest != entry.digest {
701        bail!("the saved digest of transaction {} does not match its transaction", entry.index);
702    }
703    let mut approvals = BTreeMap::new();
704    for approval in &entry.approvals {
705        let approval = PrimitiveSignature::from_bytes(approval)
706            .map_err(|error| eyre::eyre!("invalid saved approval: {error}"))?;
707        let owner = approval.recover_signer(&digest).map_err(|_| {
708            eyre::eyre!("a saved approval of transaction {} is invalid", entry.index)
709        })?;
710        approvals.insert(owner, approval);
711    }
712    Ok((tx, config, digest, approvals))
713}
714
715/// Prints the transactions awaiting owner approvals and how to approve and send them.
716fn report<N: Network>(sequence: &ScriptSequenceKind<N>) -> Result<()>
717where
718    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
719{
720    if shell::is_json() {
721        let transactions = sequence
722            .sequences()
723            .iter()
724            .flat_map(|deployment| {
725                deployment.awaiting_owners.iter().map(
726                    |entry| serde_json::json!({ "chain": deployment.chain, "transaction": entry }),
727                )
728            })
729            .collect::<Vec<_>>();
730        sh_println!(
731            "{}",
732            serde_json::json!({ "status": "awaiting_owner_approvals", "transactions": transactions })
733        )?;
734        return Ok(());
735    }
736    sh_println!("\n{}", describe(sequence)?)?;
737    Ok(())
738}
739
740/// Describes the transactions awaiting owner approvals: for each, its digest and the owners that
741/// approved it, then how the other owners sign and how to send the transactions.
742fn describe<N: Network>(sequence: &ScriptSequenceKind<N>) -> Result<String>
743where
744    N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
745{
746    let mut lines = vec!["==========================".to_string()];
747    // For each account, its configuration and the owners missing from any of its transactions.
748    let mut accounts = BTreeMap::<Address, (ConfigurableAccountConfig, Vec<Address>)>::new();
749    for (sequence_index, deployment) in sequence.sequences().iter().enumerate() {
750        let remaining = remaining_operation_indices(sequence, sequence_index);
751        for entry in
752            deployment.awaiting_owners.iter().filter(|entry| remaining.contains(&entry.index))
753        {
754            let (tx, config, digest, approvals) = decode_entry(entry)?;
755            let approved = approvals.into_keys().collect::<Vec<_>>();
756            if !accounts.contains_key(&entry.account) {
757                lines.push(format!(
758                "\nTransactions of the Tempo configurable account {} on chain {} await approvals \
759                 from its owners, with threshold {}:",
760                entry.account, deployment.chain, config.threshold
761            ));
762            }
763            let (_, missing) =
764                accounts.entry(entry.account).or_insert_with(|| (config.clone(), Vec::new()));
765            missing.extend(
766                config
767                    .owners
768                    .iter()
769                    .map(|owner| owner.owner)
770                    .filter(|owner| !approved.contains(owner)),
771            );
772            let weight = approved
773                .iter()
774                .unique()
775                .filter_map(|owner| config.owner_weight(*owner))
776                .map(u16::from)
777                .sum::<u16>();
778            let approved = if approved.is_empty() {
779                "no approvals yet".to_string()
780            } else {
781                format!("approved by {}", approved.iter().join(", "))
782            };
783            lines.push(format!(
784                "  transaction {} (nonce {}, gas limit {}): digest {digest}, {approved} (weight \
785             {weight} of {})",
786                entry.index, tx.nonce, tx.gas_limit, config.threshold
787            ));
788        }
789    }
790    for (account, (config, missing)) in accounts {
791        let missing = missing
792            .into_iter()
793            .unique()
794            .map(|owner| format!("{owner} (weight {})", config.owner_weight(owner).unwrap_or(0)))
795            .join(", ");
796        lines.push(format!(
797            "\nOwners of {account} that have not approved every transaction: {missing}"
798        ));
799    }
800    lines.push(
801        "\nEach owner signs every digest without hashing it again, with `cast wallet sign \
802         --no-hash <DIGEST>` and their wallet options (`--p256 --private-key <KEY>` for a raw \
803         P-256 owner), or with a passkey: a WebAuthn assertion whose challenge is the digest, \
804         saved as JSON with the credential's public key. Then send \
805         the transactions by running the same command with `--resume` instead of `--broadcast`, \
806         adding `--tempo.owner-signature <SIGNATURE>` for each approval. Approvals are kept once \
807         given, so they can be collected over several runs."
808            .to_string(),
809    );
810    Ok(lines.join("\n"))
811}