1use crate::receipts::{
2 PendingReceiptError, TxStatus, check_tx_status, check_tx_status_once, format_receipt,
3};
4use alloy_chains::Chain;
5use alloy_network::{Network, ReceiptResponse};
6use alloy_primitives::{
7 B256,
8 map::{B256HashMap, HashMap},
9};
10use alloy_provider::RootProvider;
11use eyre::Result;
12use forge_script_sequence::ScriptSequence;
13use foundry_cli::utils::init_progress;
14use foundry_common::shell;
15use futures::StreamExt;
16use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
17use parking_lot::RwLock;
18use std::{fmt::Write, sync::Arc, time::Duration};
19use yansi::Paint;
20
21#[derive(Debug)]
23pub struct SequenceProgressState {
24 top_spinner: ProgressBar,
26 txs: ProgressBar,
28 receipts: ProgressBar,
30 tx_spinners: B256HashMap<ProgressBar>,
32 multi: MultiProgress,
34}
35
36impl SequenceProgressState {
37 pub fn new<N: Network>(
38 sequence_idx: usize,
39 sequence: &ScriptSequence<N>,
40 multi: MultiProgress,
41 ) -> Self {
42 let mut state = if shell::is_quiet() || shell::is_json() {
43 let top_spinner = ProgressBar::hidden();
44 let txs = ProgressBar::hidden();
45 let receipts = ProgressBar::hidden();
46
47 Self { top_spinner, txs, receipts, tx_spinners: Default::default(), multi }
48 } else {
49 let mut template = "{spinner:.green}".to_string();
50 write!(template, " Sequence #{} on {}", sequence_idx + 1, Chain::from(sequence.chain))
51 .unwrap();
52 template.push_str("{msg}");
53
54 let top_spinner = ProgressBar::new_spinner().with_style(
55 ProgressStyle::with_template(&template).unwrap().tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈✅"),
56 );
57 let top_spinner = multi.add(top_spinner);
58
59 let txs = multi.insert_after(
60 &top_spinner,
61 init_progress(sequence.transactions.len() as u64, "txes").with_prefix(" "),
62 );
63
64 let receipts = multi.insert_after(
65 &txs,
66 init_progress(sequence.transactions.len() as u64, "receipts").with_prefix(" "),
67 );
68
69 top_spinner.enable_steady_tick(Duration::from_millis(100));
70 txs.enable_steady_tick(Duration::from_millis(1000));
71 receipts.enable_steady_tick(Duration::from_millis(1000));
72
73 txs.set_position(sequence.receipts.len() as u64);
74 receipts.set_position(sequence.receipts.len() as u64);
75
76 Self { top_spinner, txs, receipts, tx_spinners: Default::default(), multi }
77 };
78
79 for tx_hash in &sequence.pending {
80 state.tx_sent(*tx_hash);
81 }
82
83 state
84 }
85
86 pub fn tx_sent(&mut self, tx_hash: B256) {
89 if self.tx_spinners.len() < 10 {
91 let spinner = if shell::is_quiet() || shell::is_json() {
92 ProgressBar::hidden()
93 } else {
94 let spinner = ProgressBar::new_spinner()
95 .with_style(
96 ProgressStyle::with_template(" {spinner:.green} {msg}")
97 .unwrap()
98 .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈"),
99 )
100 .with_message(format!("{} {}", "[Pending]".yellow(), tx_hash));
101
102 let spinner = self.multi.insert_before(&self.txs, spinner);
103 spinner.enable_steady_tick(Duration::from_millis(100));
104 spinner
105 };
106
107 self.tx_spinners.insert(tx_hash, spinner);
108 }
109 self.txs.inc(1);
110 }
111
112 pub fn finish_tx_spinner(&mut self, tx_hash: B256) {
114 if let Some(spinner) = self.tx_spinners.remove(&tx_hash) {
115 spinner.finish_and_clear();
116 }
117 self.receipts.inc(1);
118 }
119
120 pub fn finish_tx_spinner_with_msg(&mut self, tx_hash: B256, msg: &str) -> std::io::Result<()> {
122 self.finish_tx_spinner(tx_hash);
123
124 if !(shell::is_quiet() || shell::is_json()) {
125 self.multi.println(msg)?;
126 }
127
128 Ok(())
129 }
130
131 pub fn set_status(&mut self, status: &str) {
133 self.top_spinner.set_message(format!(" | {status}"));
134 }
135
136 pub fn finish(&self) {
139 for spinner in self.tx_spinners.values() {
141 spinner.finish_and_clear();
142 }
143 self.top_spinner.finish();
144 self.txs.finish_and_clear();
145 self.receipts.finish_and_clear();
146 }
147}
148
149enum Polling<S> {
151 Waiting(S),
153 Sweeping(Vec<B256>),
156}
157
158impl<S> Polling<S> {
159 fn stop_waiting(&mut self, pending: &[B256], polled: &[B256]) {
162 if let Self::Waiting(_) = self {
163 *self = Self::Sweeping(
164 pending.iter().rev().filter(|hash| !polled.contains(hash)).copied().collect(),
165 );
166 }
167 }
168}
169
170#[derive(Debug, Clone)]
172pub struct SequenceProgress {
173 pub inner: Arc<RwLock<SequenceProgressState>>,
174}
175
176impl SequenceProgress {
177 pub fn new<N: Network>(
178 sequence_idx: usize,
179 sequence: &ScriptSequence<N>,
180 multi: MultiProgress,
181 ) -> Self {
182 Self {
183 inner: Arc::new(RwLock::new(SequenceProgressState::new(sequence_idx, sequence, multi))),
184 }
185 }
186}
187
188#[derive(Debug, Clone, Default)]
190pub struct ScriptProgress {
191 state: Arc<RwLock<HashMap<usize, SequenceProgress>>>,
192 multi: MultiProgress,
193}
194
195impl ScriptProgress {
196 pub fn get_sequence_progress<N: Network>(
199 &self,
200 sequence_idx: usize,
201 sequence: &ScriptSequence<N>,
202 ) -> SequenceProgress {
203 if let Some(progress) = self.state.read().get(&sequence_idx) {
204 return progress.clone();
205 }
206 let progress = SequenceProgress::new(sequence_idx, sequence, self.multi.clone());
207 self.state.write().insert(sequence_idx, progress.clone());
208 progress
209 }
210
211 #[allow(clippy::too_many_arguments)]
224 pub async fn wait_for_pending<N: Network>(
225 &self,
226 sequence_idx: usize,
227 deployment_sequence: &mut ScriptSequence<N>,
228 provider: &RootProvider<N>,
229 timeout: u64,
230 confirmations: u64,
231 submission_hashes: (&[B256], &[B256]),
232 blocked_hashes: &[B256],
233 ) -> Result<()> {
234 let (durable_hashes, replayable_hashes) = submission_hashes;
235 if deployment_sequence.pending.is_empty() {
236 return Ok(());
237 }
238
239 let count = deployment_sequence.pending.len();
240 let seq_progress = self.get_sequence_progress(sequence_idx, deployment_sequence);
241
242 seq_progress.inner.write().set_status("Waiting for pending transactions");
243
244 trace!("Checking status of {count} pending transactions");
245
246 let mut pending = deployment_sequence.pending.clone();
248 pending.sort_by_cached_key(|hash| {
249 deployment_sequence.transactions.iter().position(|tx| tx.hash == Some(*hash))
250 });
251
252 let futs = pending
253 .iter()
254 .filter(|hash| !blocked_hashes.contains(hash))
255 .map(|&tx| check_tx_status(provider, tx, timeout, confirmations, &self.multi));
256 let mut polling = Polling::Waiting(futures::stream::iter(futs).buffer_unordered(10));
257 let mut polled = Vec::with_capacity(count);
258
259 let mut errors: Vec<String> = vec![];
260 let mut discarded_transactions = false;
261
262 loop {
263 let (tx_hash, result) = match &mut polling {
264 Polling::Waiting(tasks) => {
265 let Some((tx_hash, result)) = tasks.next().await else {
266 polling.stop_waiting(&pending, &polled);
267 continue;
268 };
269 polled.push(tx_hash);
270 (tx_hash, result)
271 }
272 Polling::Sweeping(unpolled) => {
273 let Some(tx_hash) = unpolled.pop() else { break };
274 let Some(status) = check_tx_status_once(provider, tx_hash, confirmations).await
275 else {
276 continue;
277 };
278 (tx_hash, Ok(status))
279 }
280 };
281 match result {
282 Err(err) => {
283 if err.downcast_ref::<PendingReceiptError>().is_some() {
285 if durable_hashes.contains(&tx_hash) {
288 errors.push(format!(
289 "Durable submission {tx_hash:?} is still pending; refusing to discard its recovery identity"
290 ));
291 } else {
292 discarded_transactions = true;
293 deployment_sequence.remove_pending(tx_hash);
294 }
295 seq_progress
296 .inner
297 .write()
298 .finish_tx_spinner_with_msg(tx_hash, &err.to_string())?;
299 } else {
300 errors.push(format!(
301 "Failure on receiving a receipt for {tx_hash:?}:\n{err}"
302 ));
303 seq_progress.inner.write().finish_tx_spinner(tx_hash);
304 }
305 }
306 Ok(TxStatus::Dropped) => {
307 if replayable_hashes.contains(&tx_hash) {
308 deployment_sequence.remove_pending(tx_hash);
309 discarded_transactions = true;
310 } else if durable_hashes.contains(&tx_hash) {
311 errors.push(format!(
312 "Durable submission {tx_hash:?} is not currently visible; refusing to discard its recovery identity"
313 ));
314 } else {
315 deployment_sequence.remove_pending(tx_hash);
317 discarded_transactions = true;
318 }
319
320 let msg = format!(
321 "Transaction {tx_hash:?} is not currently visible to the RPC endpoint."
322 );
323 seq_progress.inner.write().finish_tx_spinner_with_msg(tx_hash, &msg)?;
324
325 polling.stop_waiting(&pending, &polled);
328 }
329 Ok(TxStatus::Success(receipt)) => {
330 trace!(tx_hash=?tx_hash, "received tx receipt");
331
332 let msg = format_receipt(
333 deployment_sequence.chain.into(),
334 &receipt,
335 Some(deployment_sequence),
336 );
337 seq_progress.inner.write().finish_tx_spinner_with_msg(tx_hash, &msg)?;
338
339 deployment_sequence.remove_pending(receipt.transaction_hash());
340 deployment_sequence.add_receipt(receipt);
341 }
342 Ok(TxStatus::Revert(receipt)) => {
343 warn!(tx_hash=?tx_hash, "Transaction Failure");
344 deployment_sequence.remove_pending(receipt.transaction_hash());
345 if !deployment_sequence.reverted.contains(&tx_hash) {
346 deployment_sequence.reverted.push(tx_hash);
347 }
348
349 let msg = format_receipt(
350 deployment_sequence.chain.into(),
351 &receipt,
352 Some(deployment_sequence),
353 );
354 seq_progress.inner.write().finish_tx_spinner_with_msg(tx_hash, &msg)?;
355
356 errors.push(format!("Transaction Failure: {:?}", receipt.transaction_hash()));
357 }
358 }
359 }
360
361 if !errors.is_empty() {
363 let mut error_msg = errors.join("\n");
364
365 if !deployment_sequence.pending.is_empty() || discarded_transactions {
367 error_msg += r#"
368
369Add `--resume` to your command to try and continue broadcasting the transactions. This will attempt to resend transactions that were discarded by the RPC."#;
370 }
371
372 eyre::bail!(error_msg);
373 } else if discarded_transactions {
374 sh_warn!(
376 "Some transactions were discarded by the RPC node. Use `--resume` to retry these transactions."
377 )?;
378 }
379
380 Ok(())
381 }
382}