Repository navigation
Expand file tree
/
Copy pathbroadcast.rs
More file actions
2253 lines (2058 loc) · 91.4 KB
/
Copy pathbroadcast.rs
File metadata and controls
2253 lines (2058 loc) · 91.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{cmp::Ordering, num::NonZeroU64, sync::Arc, time::Duration};
use crate::{
ScriptArgs, ScriptConfig,
build::LinkedBuildData,
progress::ScriptProgress,
recovery::{AttemptKind, DelegatedStatus},
sequence::{ScriptSequenceKind, completed_transaction_prefix},
session::{
RemainingScriptTransaction, SignerScope,
insert_session_access_key_for_remaining_transactions,
script_session_expected_sender_if_configured,
},
verify::BroadcastedState,
};
use alloy_chains::{Chain, NamedChain};
use alloy_consensus::{SignableTransaction, Signed, transaction::SignerRecoverable};
use alloy_eips::eip2718::{Decodable2718, Encodable2718};
use alloy_network::{
EthereumWallet, Network, NetworkTransactionBuilder, ReceiptResponse, TransactionBuilder,
TransactionResponse,
};
use alloy_primitives::{
Address, Bytes, TxHash, TxKind, U256, keccak256,
map::{AddressHashMap, AddressHashSet, HashMap},
utils::format_units,
};
use alloy_provider::{
Provider, RootProvider,
transport::{RpcError, TransportError},
utils::Eip1559Estimation,
};
use alloy_rpc_types::TransactionRequest;
use alloy_signer::Signature;
use eyre::{Context, ContextCompat, Result, bail};
use forge_script_sequence::ScriptSequence;
use foundry_cheatcodes::Wallets;
use foundry_cli::utils::{has_batch_support, has_different_gas_calc};
use foundry_common::{
FoundryTransactionBuilder, TransactionMaybeSigned,
provider::{
ProviderBuilder,
fee::{estimate_eip1559_fees, resolve_broadcast_eip1559_fees},
},
shell,
tempo::{TempoSponsor, maybe_print_fee_token, resolve_and_set_fee_token},
};
use foundry_config::Config;
use foundry_evm::core::{
constants::DEFAULT_CREATE2_DEPLOYER_CODEHASH,
evm::{FoundryEvmNetwork, TempoEvmNetwork},
fork::ResolvedFork,
opts::EvmOpts,
};
use foundry_wallets::{
TempoAccountsWallet,
wallet_browser::{error::BrowserWalletError, signer::BrowserSigner},
};
use futures::{FutureExt, StreamExt, future::join_all, stream::FuturesUnordered};
use itertools::Itertools;
use revm_inspectors::tracing::types::CallKind;
use tempo_alloy::{
TempoNetwork,
rpc::{TempoTransactionReceipt, TempoTransactionRequest},
};
use tempo_primitives::transaction::{Call, TempoTxEnvelope};
/// Represents how to send a single transaction.
#[derive(Clone)]
pub enum SendTransactionKind<'a, N: Network> {
Unlocked(N::TransactionRequest),
Raw(N::TransactionRequest, &'a EthereumWallet),
Browser(N::TransactionRequest, &'a BrowserSigner<N>),
Signed(N::TxEnvelope),
AccessKey(N::TransactionRequest, Box<TempoAccountsWallet>),
PreparedRaw(Bytes, TxHash),
}
impl<'a, N: Network> SendTransactionKind<'a, N>
where
N::TxEnvelope: From<Signed<N::UnsignedTx>>,
N::UnsignedTx: SignableTransaction<Signature>,
N::TransactionRequest: FoundryTransactionBuilder<N>,
{
const fn delegated_request(&self) -> Option<&N::TransactionRequest> {
match self {
Self::Unlocked(request) | Self::Browser(request, _) => Some(request),
_ => None,
}
}
fn validate_delegated_submission(&self) -> Result<()> {
let Self::Browser(request, signer) = self else { return Ok(()) };
if request.from().is_some_and(|from| from != signer.address()) {
bail!("Transaction `from` address does not match connected wallet address");
}
if request.chain_id().is_some_and(|chain_id| chain_id != signer.chain_id()) {
bail!("Transaction `chainId` does not match connected wallet chain ID");
}
Ok(())
}
fn is_definite_non_submission(&self, error: &eyre::Report) -> bool {
match self {
Self::Browser(..) => is_definite_browser_non_submission(error),
Self::Unlocked(_) => is_definite_unlocked_non_submission(error),
_ => false,
}
}
/// Prepares the transaction for broadcasting by synchronizing nonce and estimating gas.
///
/// This method performs two key operations:
/// 1. Nonce synchronization: Waits for the provider's nonce to catch up to the expected
/// transaction nonce when doing sequential broadcast
/// 2. Gas estimation: Re-estimates gas right before broadcasting for chains that require it
#[allow(clippy::too_many_arguments)]
pub async fn prepare(
&mut self,
provider: &RootProvider<N>,
sequential_broadcast: bool,
is_fixed_gas_limit: bool,
estimate_via_rpc: bool,
estimate_multiplier: u64,
tempo_sponsor: Option<&TempoSponsor>,
chain: Option<Chain>,
) -> Result<()> {
let tempo_browser = matches!(self, Self::Browser(..)) && chain.is_some_and(Chain::is_tempo);
let (tx, tempo_wallet) = match self {
Self::Raw(tx, _) | Self::Unlocked(tx) | Self::Browser(tx, _) => (tx, None),
Self::AccessKey(tx, wallet) => (tx, Some(wallet)),
Self::Signed(_) | Self::PreparedRaw(..) => return Ok(()),
};
reject_access_key_create::<N>(tx, tempo_wallet.is_some())?;
if sequential_broadcast {
let from = tx.from().expect("no sender");
let tx_nonce = tx.nonce().expect("no nonce");
for attempt in 0..5 {
let nonce = provider.get_transaction_count(from).await?;
match nonce.cmp(&tx_nonce) {
Ordering::Greater => {
bail!(
"EOA nonce changed unexpectedly while sending transactions. Expected {tx_nonce} got {nonce} from provider."
);
}
Ordering::Less => {
if attempt == 4 {
bail!(
"After 5 attempts, provider nonce ({nonce}) is still behind expected nonce ({tx_nonce})."
);
}
warn!(
"Expected nonce ({tx_nonce}) is ahead of provider nonce ({nonce}). Retrying in 1 second..."
);
tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
}
Ordering::Equal => {
// Nonces are equal, we can proceed.
break;
}
}
}
}
if let Some(wallet) = tempo_wallet {
**wallet = tx.prepare_with_tempo_wallet(provider, wallet).await?;
}
let fee_token = if let Some(sponsor) = tempo_sponsor {
sponsor.resolve_and_set_fee_token(Some(provider), chain, tx).await?;
None
} else {
resolve_and_set_fee_token(Some(provider), chain, tx, tx.from()).await?
};
// A fee token, sponsor, validity window, or other Tempo field selects
// the AA transaction type. AA requests carry CREATE as their first
// call rather than as the Ethereum transaction `to` field.
convert_tempo_aa_create::<N>(tx);
// Chains which use `eth_estimateGas` are being sent sequentially and require their
// gas to be re-estimated right before broadcasting.
if !is_fixed_gas_limit && estimate_via_rpc {
estimate_gas(tx, provider, estimate_multiplier, tempo_browser).await?;
}
if let Some(sponsor) = tempo_sponsor {
let from = tx.from().expect("no sender");
sponsor.attach_and_print::<N>(tx, from).await?;
} else {
maybe_print_fee_token(Some(provider), fee_token).await?;
}
Ok(())
}
/// Sends the transaction to the network.
///
/// Depending on the transaction kind, this will either:
/// - Submit via `eth_sendTransaction` for unlocked accounts
/// - Sign and submit via `eth_sendRawTransaction` for raw transactions
/// - Submit pre-signed transaction via `eth_sendRawTransaction`
pub async fn send(self, provider: Arc<RootProvider<N>>) -> Result<TxHash> {
match self {
Self::Unlocked(tx) => {
debug!("sending transaction from unlocked account {:?}", tx);
// Submit the transaction
let pending = provider.send_transaction(tx).await?;
Ok(*pending.tx_hash())
}
Self::Raw(tx, signer) => {
debug!("sending transaction: {:?}", tx);
let signed = tx.build(signer).await?;
// Submit the raw transaction
let pending = provider.send_raw_transaction(signed.encoded_2718().as_ref()).await?;
Ok(*pending.tx_hash())
}
Self::Signed(tx) => {
debug!("sending transaction: {:?}", tx);
let pending = provider.send_raw_transaction(tx.encoded_2718().as_ref()).await?;
Ok(*pending.tx_hash())
}
Self::Browser(tx, signer) => {
debug!("sending transaction: {:?}", tx);
// Sign and send the transaction via the browser wallet
Ok(signer.send_transaction_via_browser(tx).await?)
}
Self::AccessKey(tx, wallet) => {
debug!("sending transaction via tempo access key: {:?}", tx);
let raw_tx = tx.sign_with_tempo_wallet(&wallet).await?;
let pending = provider.send_raw_transaction(&raw_tx).await?;
Ok(*pending.tx_hash())
}
Self::PreparedRaw(payload, _) => {
let pending = provider.send_raw_transaction(&payload).await?;
Ok(*pending.tx_hash())
}
}
}
#[allow(clippy::too_many_arguments)]
async fn prepare_for_durable_send(
mut self,
provider: &RootProvider<N>,
sequential_broadcast: bool,
is_fixed_gas_limit: bool,
estimate_via_rpc: bool,
estimate_multiplier: u64,
tempo_sponsor: Option<&TempoSponsor>,
chain: Option<Chain>,
) -> Result<Self> {
self.prepare(
provider,
sequential_broadcast,
is_fixed_gas_limit,
estimate_via_rpc,
estimate_multiplier,
tempo_sponsor,
chain,
)
.await?;
if let Self::Unlocked(tx) = &mut self {
tx.prep_for_submission();
}
Ok(match self {
Self::Raw(tx, signer) => {
let signed = tx.build(signer).await?;
Self::PreparedRaw(Bytes::from(signed.encoded_2718()), signed.trie_hash())
}
Self::Signed(tx) => {
let hash = tx.trie_hash();
Self::PreparedRaw(Bytes::from(tx.encoded_2718()), hash)
}
Self::AccessKey(tx, wallet) => {
let payload = Bytes::from(tx.sign_with_tempo_wallet(&wallet).await?);
let envelope = N::TxEnvelope::decode_2718_exact(&payload)?;
Self::PreparedRaw(payload, envelope.trie_hash())
}
kind => kind,
})
}
}
fn is_definite_browser_non_submission(error: &eyre::Report) -> bool {
let Some(alloy_signer::Error::Other(error)) = error.downcast_ref::<alloy_signer::Error>()
else {
return false;
};
matches!(
error.downcast_ref::<BrowserWalletError>(),
Some(BrowserWalletError::Rejected { .. } | BrowserWalletError::NotConnected)
)
}
fn is_definite_unlocked_non_submission(error: &eyre::Report) -> bool {
matches!(
error.downcast_ref::<TransportError>(),
Some(RpcError::ErrorResp(error))
if is_unlocked_non_submission(error.code, &error.message)
)
}
fn is_unlocked_non_submission(code: i64, message: &str) -> bool {
code == -32602 && message == "No Signer available"
}
fn tempo_batch_calls(
sequence: &ScriptSequence<TempoNetwork>,
first_operation: usize,
) -> Result<Vec<Call>> {
sequence
.transactions()
.skip(first_operation)
.enumerate()
.map(|(call_index, tx)| {
if tx.authorization_list().is_some_and(|list| !list.is_empty()) {
bail!(
"--batch does not support EIP-7702 authorization lists \
(found at transaction {}); use regular broadcast instead.",
call_index + first_operation + 1
);
}
if let TransactionMaybeSigned::Unsigned(inner) = tx
&& inner.blob_sidecar().is_some()
{
bail!(
"--batch does not support blob (EIP-4844) transactions \
(found at transaction {}); use regular broadcast instead.",
call_index + first_operation + 1
);
}
let to = tx.to().map(TxKind::Call).ok_or_else(|| {
eyre::eyre!(
"Unexpected raw CREATE in --batch mode at position {} — \
this is a bug; CREATEs should have been rewritten by the inspector.",
call_index + first_operation + 1
)
})?;
Ok(Call {
to,
value: tx.value().unwrap_or(U256::ZERO),
input: tx.input().cloned().unwrap_or_default(),
})
})
.collect()
}
fn validate_tempo_batch_request(
request: &TempoTransactionRequest,
sender: Address,
chain: u64,
calls: &[Call],
) -> Result<()> {
if request.inner.from != Some(sender) {
bail!("batch request does not match its planned sender");
}
let expected = request
.clone()
.build_aa()
.map_err(|error| eyre::eyre!("invalid persisted batch request: {error}"))?;
if expected.chain_id != chain || expected.calls != calls {
bail!("batch request does not match its planned operations");
}
Ok(())
}
fn validate_tempo_batch_payload(
request: &TempoTransactionRequest,
payload: &[u8],
sender: Address,
chain: u64,
calls: &[Call],
) -> Result<TxHash> {
validate_tempo_batch_request(request, sender, chain, calls)?;
let expected = request
.clone()
.build_aa()
.map_err(|error| eyre::eyre!("invalid persisted batch request: {error}"))?;
let envelope = TempoTxEnvelope::decode_2718_exact(payload)
.wrap_err("recovery plan contains an invalid signed batch payload")?;
validate_tempo_batch_envelope(&envelope, sender, chain, calls)?;
let TempoTxEnvelope::AA(signed) = &envelope else {
unreachable!();
};
if signed.tx() != &expected {
bail!("signed batch payload does not match its persisted request");
}
Ok(envelope.trie_hash())
}
fn validate_tempo_batch_envelope(
envelope: &TempoTxEnvelope,
sender: Address,
chain: u64,
calls: &[Call],
) -> Result<()> {
let TempoTxEnvelope::AA(signed) = envelope else {
bail!("recovered batch transaction is not a Tempo transaction");
};
if signed.recover_signer().wrap_err("recovered batch transaction has an invalid signature")?
!= sender
{
bail!("recovered batch transaction does not match its planned sender");
}
if signed.tx().chain_id != chain || signed.tx().calls != calls {
bail!("recovered batch transaction does not match its planned operations");
}
Ok(())
}
pub(crate) fn remaining_unsigned_transactions_for_recovery<N: Network>(
sequence: &ScriptSequenceKind<N>,
) -> Vec<RemainingScriptTransaction>
where
N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
{
sequence
.sequences()
.iter()
.enumerate()
.filter(|(sequence_index, _)| sequence.batch_attempt(*sequence_index).is_none())
.flat_map(|(sequence_index, deployment)| {
remaining_operation_indices(sequence, sequence_index).into_iter().filter_map(
move |index| {
let tx = deployment.transactions[index].tx();
(tx.is_unsigned() && sequence.signed_payload(sequence_index, index).is_none())
.then(|| RemainingScriptTransaction {
chain: deployment.chain,
from: tx.from().expect("missing from"),
})
},
)
})
.collect()
}
fn remaining_operation_indices<N: Network>(
sequence: &ScriptSequenceKind<N>,
sequence_index: usize,
) -> Vec<usize>
where
N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
{
let deployment = &sequence.sequences()[sequence_index];
deployment
.transactions
.iter()
.enumerate()
.filter_map(|(index, transaction)| {
let hash = sequence
.signed_payload(sequence_index, index)
.map(|signed| signed.hash)
.or_else(|| match sequence.delegated_status(sequence_index, index) {
Some(DelegatedStatus::Pending { hash }) => Some(hash),
_ => None,
})
.or(transaction.hash)
.or_else(|| match transaction.tx() {
TransactionMaybeSigned::Signed { tx, .. } => Some(tx.trie_hash()),
TransactionMaybeSigned::Unsigned(_) => None,
});
let completed = hash.is_some_and(|hash| {
deployment.receipts.iter().any(|receipt| receipt.transaction_hash() == hash)
});
(!completed).then_some(index)
})
.collect()
}
fn remaining_sender_addresses<N: Network>(sequence: &ScriptSequenceKind<N>) -> AddressHashSet
where
N::TxEnvelope: for<'de> serde::Deserialize<'de> + serde::Serialize,
{
sequence
.sequences()
.iter()
.enumerate()
.flat_map(|(sequence_index, deployment)| {
remaining_operation_indices(sequence, sequence_index)
.into_iter()
.filter_map(|index| deployment.transactions[index].tx().from())
})
.collect()
}
const fn should_broadcast_sequentially(
estimate_via_rpc: bool,
slow: bool,
required_signers: usize,
ordering_senders: usize,
batch_supported: bool,
) -> bool {
estimate_via_rpc || slow || required_signers == 0 || ordering_senders != 1 || !batch_supported
}
/// Represents how to send _all_ transactions
pub enum SendTransactionsKind<N: Network> {
/// Send via `eth_sendTransaction` and rely on the `from` address being unlocked.
Unlocked(AddressHashSet),
/// Send a signed transaction via `eth_sendRawTransaction`, or via browser
Raw {
eth_wallets: AddressHashMap<EthereumWallet>,
browser: Option<BrowserSigner<N>>,
access_keys: HashMap<SignerScope, TempoAccountsWallet>,
},
}
impl<N: Network> SendTransactionsKind<N> {
/// Returns the [`SendTransactionKind`] for the given address
///
/// Returns an error if no matching signer is found or the address is not unlocked
pub fn for_sender(
&self,
chain: u64,
addr: &Address,
tx: N::TransactionRequest,
) -> Result<SendTransactionKind<'_, N>> {
match self {
Self::Unlocked(unlocked) => {
if !unlocked.contains(addr) {
bail!("Sender address {:?} is not unlocked", addr);
}
Ok(SendTransactionKind::Unlocked(tx))
}
Self::Raw { eth_wallets, browser, access_keys } => {
if let Some(wallet) = access_keys.get(&SignerScope::new(chain, *addr)) {
Ok(SendTransactionKind::AccessKey(tx, Box::new(wallet.clone())))
} else if let Some(wallet) = eth_wallets.get(addr) {
Ok(SendTransactionKind::Raw(tx, wallet))
} else if let Some(b) = browser
&& b.address() == *addr
{
Ok(SendTransactionKind::Browser(tx, b))
} else {
bail!("No matching signer for {:?} found", addr);
}
}
}
}
}
/// State after we have bundled all
/// [`TransactionWithMetadata`](forge_script_sequence::TransactionWithMetadata) objects into a
/// single [`ScriptSequenceKind`] object containing one or more script sequences.
pub struct BundledState<FEN: FoundryEvmNetwork> {
pub args: ScriptArgs,
pub script_config: ScriptConfig<FEN>,
pub script_wallets: Wallets,
pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
pub build_data: LinkedBuildData,
pub sequence: ScriptSequenceKind<FEN::Network>,
}
impl<FEN: FoundryEvmNetwork> BundledState<FEN> {
pub async fn wait_for_pending(mut self) -> Result<Self> {
let progress = ScriptProgress::default();
let progress_ref = &progress;
let config = &self.script_config.config;
let submission_hashes = (0..self.sequence.sequences().len())
.map(|sequence| self.sequence.submission_hashes(sequence))
.collect::<Vec<_>>();
let futs = self
.sequence
.sequences_mut()
.iter_mut()
.zip(submission_hashes)
.enumerate()
.map(|(sequence_idx, (sequence, (durable_hashes, replayable_hashes)))| async move {
let rpc_url = sequence.rpc_url();
let provider =
Arc::new(ProviderBuilder::from_config_with_url(config, rpc_url)?.build()?);
progress_ref
.wait_for_pending(
sequence_idx,
sequence,
&provider,
self.script_config.config.transaction_timeout,
self.args.confirmations,
(&durable_hashes, &replayable_hashes),
)
.await
})
.collect::<Vec<_>>();
let errors = join_all(futs).await.into_iter().filter_map(Result::err).collect::<Vec<_>>();
self.sequence.save(true, false)?;
if !errors.is_empty() {
return Err(eyre::eyre!("{}", errors.iter().format("\n")));
}
Ok(self)
}
/// Broadcasts transactions from all sequences.
pub async fn broadcast(mut self) -> Result<BroadcastedState<FEN>> {
let remaining_transactions = remaining_unsigned_transactions_for_recovery(&self.sequence);
let ordering_addresses = remaining_sender_addresses(&self.sequence);
let has_unprepared_transactions =
self.sequence.sequences().iter().enumerate().any(|(sequence_index, _)| {
remaining_operation_indices(&self.sequence, sequence_index)
.into_iter()
.any(|index| self.sequence.signed_payload(sequence_index, index).is_none())
});
let required_addresses =
remaining_transactions.iter().map(|tx| tx.from).collect::<AddressHashSet>();
if required_addresses.contains(&Config::DEFAULT_SENDER) {
eyre::bail!(
"You seem to be using Foundry's default sender. Be sure to set your own --sender."
);
}
let send_kind = if required_addresses.is_empty() {
SendTransactionsKind::Raw {
eth_wallets: AddressHashMap::default(),
browser: None,
access_keys: HashMap::default(),
}
} else if self.args.unlocked {
SendTransactionsKind::Unlocked(required_addresses.clone())
} else {
let expected_session_sender = script_session_expected_sender_if_configured(
&self.script_config.tempo,
&required_addresses,
)?;
// For addresses without an explicit signer, try the Tempo Accounts store.
let mut access_keys: HashMap<SignerScope, TempoAccountsWallet> = HashMap::default();
if let Some(expected_session_sender) = expected_session_sender
&& let Some(session) =
self.script_config.tempo.session_signer_for_multi_wallet_any_chain(
&self.args.wallets,
Some(expected_session_sender),
)?
{
insert_session_access_key_for_remaining_transactions(
&mut access_keys,
session,
&remaining_transactions,
)?;
}
let signers: Vec<Address> = self
.script_wallets
.signers()
.map_err(|e| eyre::eyre!("{e}"))?
.into_iter()
.chain(self.browser_wallet.as_ref().map(|b| b.address()))
.collect();
let mut missing_addresses = Vec::new();
let accounts_wallet = self
.script_config
.evm_opts
.networks
.is_tempo()
.then(TempoAccountsWallet::try_from_default_store)
.transpose()?
.flatten();
for tx in &remaining_transactions {
let scope = tx.scope();
if !signers.contains(&tx.from) && !access_keys.contains_key(&scope) {
if let Some(wallet) = accounts_wallet.as_ref()
&& wallet.has_account(tx.from)?
{
access_keys.insert(scope, wallet.clone().with_chain_id(tx.chain));
} else {
missing_addresses.push(tx.from);
}
}
}
missing_addresses.sort_unstable();
missing_addresses.dedup();
if !missing_addresses.is_empty() {
eyre::bail!(
"No associated wallet for addresses: {:?}. Unlocked wallets: {:?}",
missing_addresses,
signers
);
}
let signers = self.script_wallets.into_multi_wallet().into_signers()?;
let eth_wallets: AddressHashMap<EthereumWallet> =
signers.into_iter().map(|(addr, signer)| (addr, signer.into())).collect();
SendTransactionsKind::Raw { eth_wallets, browser: self.browser_wallet, access_keys }
};
let tempo_sponsor = if has_unprepared_transactions {
self.script_config.tempo.sponsor_config().await?.map(Arc::new)
} else {
None
};
if tempo_sponsor.is_some()
&& self.script_config.tempo.sponsor_sig.is_some()
&& remaining_transactions.len() > 1
{
eyre::bail!(
"--tempo.sponsor-sig can only sponsor one remaining script transaction; use --tempo.sponsor-signer for multi-transaction scripts"
);
}
let progress = ScriptProgress::default();
for i in 0..self.sequence.sequences().len() {
let remaining_indices = remaining_operation_indices(&self.sequence, i);
let signed_payloads = (0..self.sequence.sequences()[i].transactions.len())
.map(|index| {
self.sequence
.signed_payload(i, index)
.map(|signed| (signed.payload.clone(), signed.hash))
})
.collect::<Vec<_>>();
let mut sequence = self.sequence.sequences_mut().get_mut(i).unwrap();
let provider = Arc::new(
ProviderBuilder::from_config_with_url(
&self.script_config.config,
sequence.rpc_url(),
)?
.build()?,
);
let unlocked_submission_provider = Arc::new(
ProviderBuilder::from_config_with_url(
&self.script_config.config,
sequence.rpc_url(),
)?
.max_retry(0)
.build()?,
);
let seq_progress = progress.get_sequence_progress(i, sequence);
if !remaining_indices.is_empty() {
let is_legacy = Chain::from(sequence.chain).is_legacy() || self.args.legacy;
// Make a one-time gas price estimation
let all_signed =
remaining_indices.iter().all(|index| signed_payloads[*index].is_some());
let (gas_price, eip1559_fees) = match (
all_signed,
is_legacy,
self.args.with_gas_price,
self.args.priority_gas_price,
) {
(true, _, _, _) => (None, None),
(false, true, Some(gas_price), _) => (Some(gas_price.to()), None),
(false, true, None, _) => (Some(provider.get_gas_price().await?), None),
(false, false, Some(max_fee_per_gas), Some(max_priority_fee_per_gas)) => {
let max_fee: u128 = max_fee_per_gas.to();
let max_priority: u128 = max_priority_fee_per_gas.to();
if max_priority > max_fee {
eyre::bail!(
"--priority-gas-price ({max_priority}) cannot be higher than --with-gas-price ({max_fee})"
);
}
(
None,
Some(Eip1559Estimation {
max_fee_per_gas: max_fee,
max_priority_fee_per_gas: max_priority,
}),
)
}
(false, false, _, _) => {
let fees = estimate_eip1559_fees(
&provider,
self.script_config.config.eip1559_fee_estimate,
)
.await
.wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?;
// Browser wallets may suggest their own tip; query it best-effort.
let browser_suggested_tip = if matches!(
&send_kind,
SendTransactionsKind::Raw { browser: Some(_), .. }
) {
provider.get_max_priority_fee_per_gas().await.ok()
} else {
None
};
let fees = resolve_broadcast_eip1559_fees(
fees,
self.args.with_gas_price.map(|p| p.to()),
self.args.priority_gas_price.map(|p| p.to()),
browser_suggested_tip,
)?;
(None, Some(fees.estimation()))
}
};
// Iterate through transactions, matching the `from` field with the associated
// wallet. Then send the transaction. Panics if we find a unknown `from`
let sequence_chain = sequence.chain;
let mut transactions = Vec::with_capacity(remaining_indices.len());
for index in remaining_indices {
let tx_with_metadata = &sequence.transactions[index];
let is_fixed_gas_limit = tx_with_metadata.is_fixed_gas_limit;
let kind = match (&signed_payloads[index], tx_with_metadata.tx().clone()) {
(Some((payload, hash)), _) => {
SendTransactionKind::PreparedRaw(payload.clone(), *hash)
}
(None, TransactionMaybeSigned::Signed { tx, .. }) => {
if tempo_sponsor.is_some() {
eyre::bail!(
"cannot attach Tempo sponsor signature to an already signed script transaction"
);
}
SendTransactionKind::Signed(tx)
}
(None, TransactionMaybeSigned::Unsigned(mut tx)) => {
let from = tx.from().expect("No sender for onchain transaction!");
tx.set_chain_id(sequence_chain);
// Set TxKind::Create explicitly to satisfy `check_reqd_fields` in
// alloy
if tx.kind().is_none() {
tx.set_create();
}
if let Some(gas_price) = gas_price {
tx.set_gas_price(gas_price);
} else {
let eip1559_fees = eip1559_fees.expect("was set above");
tx.set_max_priority_fee_per_gas(
eip1559_fees.max_priority_fee_per_gas,
);
tx.set_max_fee_per_gas(eip1559_fees.max_fee_per_gas);
}
self.script_config.tempo.apply::<FEN::Network>(&mut tx, None);
send_kind.for_sender(sequence_chain, &from, tx)?
}
};
transactions.push((kind, is_fixed_gas_limit, index));
}
let estimate_via_rpc = has_different_gas_calc(sequence.chain)
|| self.script_config.evm_opts.networks.is_tempo()
|| self.args.skip_simulation;
// We only wait for a transaction receipt before sending the next transaction, if
// there is more than one signer. There would be no way of assuring
// their order otherwise.
// Or if the chain does not support batched transactions (eg. Arbitrum).
// Or if we need to invoke eth_estimateGas before sending transactions.
let sequential_broadcast = should_broadcast_sequentially(
estimate_via_rpc,
self.args.slow,
required_addresses.len(),
ordering_addresses.len(),
has_batch_support(sequence.chain),
) || transactions.iter().any(|(kind, _, _)| {
matches!(
kind,
SendTransactionKind::Browser(..) | SendTransactionKind::Unlocked(..)
)
});
// We send transactions and wait for receipts in batches of 100, since some networks
// cannot handle more than that.
let batch_size = if sequential_broadcast { 1 } else { 100 };
let sequence_chain = sequence.chain;
for (batch_number, batch) in transactions.chunks(batch_size).enumerate() {
seq_progress.inner.write().set_status(&format!(
"Sending transactions [{} - {}]",
batch_number * batch_size,
batch_number * batch_size + std::cmp::min(batch_size, batch.len()) - 1
));
if !batch.is_empty() {
let mut prepared = Vec::with_capacity(batch.len());
for (kind, is_fixed_gas_limit, index) in batch {
let mut kind = kind
.clone()
.prepare_for_durable_send(
&provider,
sequential_broadcast,
*is_fixed_gas_limit,
estimate_via_rpc,
self.args.gas_estimate_multiplier,
tempo_sponsor.as_deref(),
Some(sequence_chain.into()),
)
.await?;
if let SendTransactionKind::PreparedRaw(payload, hash) = &mut kind {
*hash = self.sequence.persist_signed_payload(
i,
*index,
payload.clone(),
)?;
}
prepared.push((kind, *is_fixed_gas_limit, *index));
}
let mut buffer = FuturesUnordered::new();
for (kind, is_fixed_gas_limit, index) in prepared {
if let Some(request) = kind.delegated_request() {
kind.validate_delegated_submission()?;
self.sequence.persist_delegated_request(
i,
index,
request.clone(),
)?;
}
let provider = if matches!(kind, SendTransactionKind::Unlocked(_)) {
unlocked_submission_provider.clone()
} else {
provider.clone()
};
let mut pending = async move {
let res = kind.clone().send(provider).await;
(res, kind, is_fixed_gas_limit, 0, None, index)
}
.boxed();
if let Some(result) = pending.as_mut().now_or_never() {
buffer.push(futures::future::ready(result).boxed());
} else {
buffer.push(pending);
}
}
'send: while let Some((
mut res,
kind,
is_fixed_gas_limit,
attempt,
original_res,
index,
)) = buffer.next().await
{
if res.is_err()
&& let SendTransactionKind::PreparedRaw(_, hash) = kind
&& provider
.get_transaction_by_hash(hash)
.await
.is_ok_and(|transaction| transaction.is_some())
{
res = Ok(hash);
}
if kind.delegated_request().is_some()
&& let Err(error) = res
{
if kind.is_definite_non_submission(&error) {
self.sequence.clear_delegated_request(i, index)?;
return Err(error);
}
self.sequence.persist_delegated_status(
i,
index,
DelegatedStatus::OutcomeUnknown,
)?;
bail!(
"submission outcome for delegated operation {index} is unknown; refusing to risk a duplicate transaction"
);
}
if res.is_err()
&& self.script_config.tempo.sponsor_sig.is_some()
&& !matches!(kind, SendTransactionKind::PreparedRaw(..))
&& attempt == 0
{
debug!(
"not retrying transaction because --tempo.sponsor-sig is a static signature"
);
} else if res.is_err() && attempt <= 3 {
// Try to resubmit the transaction
let provider = provider.clone();
let progress = seq_progress.inner.clone();
buffer.push(Box::pin(async move {
debug!(err=?res, ?attempt, "retrying transaction ");
let attempt = attempt + 1;
progress.write().set_status(&format!(
"retrying transaction {res:?} (attempt {attempt})"
));
tokio::time::sleep(Duration::from_millis(1000 * attempt)).await;
let r = kind.clone().send(provider).await;
(
r,
kind,
is_fixed_gas_limit,
attempt,
original_res.or(Some(res)),