quantus-cli 2.1.1

Command line interface and library for interacting with the Quantus Network
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
//! Common SubXT utilities and functions shared across CLI commands
use crate::{chain::client::ChainConfig, error::Result, log_error, log_verbose};
use colored::Colorize;
use hex;
use sp_core::crypto::{AccountId32, Ss58Codec};
use subxt::{
	tx::{TxProgress, TxStatus},
	OnlineClient,
};

pub type SubxtAccountId32 = subxt::ext::subxt_core::utils::AccountId32;

const MILLIS_PER_SECOND: u64 = 1_000;
/// Pre-inclusion inactivity window. The status stream is legitimately silent
/// between Broadcasted and InBestBlock for a full PoW block interval, and block
/// intervals are roughly exponential around the ~10s target: a 30s window
/// aborted ~1 in 20 valid transactions (e^-3), inviting duplicate-submission
/// retries. Twelve target intervals make a spurious abort negligible (~e^-12)
/// while still catching genuinely dead streams well inside the overall deadline.
const TX_STATUS_INACTIVITY_TIMEOUT_SECS: u64 = 120;
const TX_STATUS_INCLUDED_TIMEOUT_SECS: u64 = 5 * 60;
pub(crate) const TX_STATUS_FINALIZED_TIMEOUT_SECS: u64 = 30 * 60;

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ExecutionMode {
	pub finalized: bool,
	pub wait_for_transaction: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransactionStage {
	Submitted,
	Included,
	Finalized,
}

impl ExecutionMode {
	pub fn transaction_stage(self) -> TransactionStage {
		if self.finalized {
			TransactionStage::Finalized
		} else if self.wait_for_transaction {
			TransactionStage::Included
		} else {
			TransactionStage::Submitted
		}
	}

	pub fn should_watch_transaction(self) -> bool {
		self.transaction_stage() != TransactionStage::Submitted
	}
}

impl TransactionStage {
	pub fn status_label(self) -> &'static str {
		match self {
			Self::Submitted => "submitted",
			Self::Included => "included",
			Self::Finalized => "finalized",
		}
	}

	pub fn success_detail(self) -> &'static str {
		match self {
			Self::Submitted => "accepted by the node",
			Self::Included => "included in a best block",
			Self::Finalized => "finalized in a block",
		}
	}
}

pub(crate) fn delay_blocks_to_u32(blocks: u64) -> Result<u32> {
	u32::try_from(blocks).map_err(|_| {
		crate::error::QuantusError::Generic(format!(
			"Delay in blocks ({blocks}) exceeds the maximum supported block delay ({})",
			u32::MAX
		))
	})
}

pub(crate) fn delay_seconds_to_millis(seconds: u64) -> Result<u64> {
	seconds.checked_mul(MILLIS_PER_SECOND).ok_or_else(|| {
		crate::error::QuantusError::Generic(format!(
			"Delay in seconds ({seconds}) exceeds the maximum supported timestamp delay ({})",
			u64::MAX / MILLIS_PER_SECOND
		))
	})
}

fn tx_status_watch_timeout_secs(target_stage: TransactionStage) -> u64 {
	match target_stage {
		TransactionStage::Submitted => 0,
		TransactionStage::Included => TX_STATUS_INCLUDED_TIMEOUT_SECS,
		TransactionStage::Finalized => TX_STATUS_FINALIZED_TIMEOUT_SECS,
	}
}

/// How long to wait for the next status update.
///
/// A short inactivity timeout detects stalled streams before inclusion. After a
/// transaction is in a best block and we are waiting for PoW finalization, silent
/// gaps can exceed that inactivity window, so only the overall watch deadline applies.
fn next_status_wait_secs(remaining_watch_secs: u64, apply_inactivity_timeout: bool) -> u64 {
	if remaining_watch_secs == 0 {
		return 0;
	}
	if apply_inactivity_timeout {
		remaining_watch_secs.min(TX_STATUS_INACTIVITY_TIMEOUT_SECS)
	} else {
		remaining_watch_secs
	}
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum WatchedTxEvent {
	Validated,
	Broadcasted,
	NoLongerInBestBlock,
	InBestBlock,
	InFinalizedBlock,
	Error(String),
	Invalid(String),
	Dropped(String),
	StreamError(String),
	StreamEnded,
	/// No status updates within the short inactivity window.
	InactivityTimedOut {
		timeout_secs: u64,
	},
	/// Overall inclusion/finalization deadline elapsed.
	WatchDeadlineTimedOut {
		elapsed_secs: u64,
	},
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WatchDecision {
	Continue,
	WaitForFinalization,
	Success,
}

fn describe_watched_tx_event(
	event: WatchedTxEvent,
	target_stage: TransactionStage,
) -> Result<WatchDecision> {
	match event {
		WatchedTxEvent::Validated |
		WatchedTxEvent::Broadcasted |
		WatchedTxEvent::NoLongerInBestBlock => Ok(WatchDecision::Continue),
		WatchedTxEvent::InBestBlock =>
			if target_stage == TransactionStage::Finalized {
				Ok(WatchDecision::WaitForFinalization)
			} else {
				Ok(WatchDecision::Success)
			},
		WatchedTxEvent::InFinalizedBlock => Ok(WatchDecision::Success),
		WatchedTxEvent::Error(message) =>
			Err(crate::error::QuantusError::NetworkError(format!("Transaction error: {message}"))),
		WatchedTxEvent::Invalid(message) =>
			Err(crate::error::QuantusError::NetworkError(format!("Transaction invalid: {message}"))),
		WatchedTxEvent::Dropped(message) =>
			Err(crate::error::QuantusError::NetworkError(format!("Transaction dropped: {message}"))),
		WatchedTxEvent::StreamError(message) => Err(crate::error::QuantusError::NetworkError(
			format!("Transaction status stream error: {message}"),
		)),
		WatchedTxEvent::StreamEnded => Err(crate::error::QuantusError::NetworkError(format!(
			"Transaction status stream ended before the transaction was {}",
			target_stage.status_label()
		))),
		WatchedTxEvent::InactivityTimedOut { timeout_secs } =>
			Err(crate::error::QuantusError::NetworkError(format!(
				"Transaction status stream timed out after {timeout_secs} seconds without updates before the transaction was {}. The transaction may still be in the pool and execute later; verify its status on chain before resubmitting, or you may duplicate it",
				target_stage.status_label()
			))),
		WatchedTxEvent::WatchDeadlineTimedOut { elapsed_secs } =>
			Err(crate::error::QuantusError::NetworkError(format!(
				"Timed out after waiting {elapsed_secs} seconds for the transaction to be {}. The transaction may still be in the pool and execute later; verify its status on chain before resubmitting, or you may duplicate it",
				target_stage.status_label()
			))),
	}
}

fn should_check_execution_success(
	block_hash: &subxt::utils::H256,
	already_checked_for: Option<&subxt::utils::H256>,
) -> bool {
	already_checked_for != Some(block_hash)
}

/// Require the watched extrinsic to be present in the reported block.
/// Returns its index for event scanning, or an error if the hash is absent.
fn require_extrinsic_index(our_extrinsic_index: Option<usize>) -> Result<usize> {
	our_extrinsic_index.ok_or_else(|| {
		crate::error::QuantusError::NetworkError(
			"Extrinsic hash not found in reported block".to_string(),
		)
	})
}

/// `Break` carries the outcome of the watch: the hash of the block in which the
/// transaction reached the target stage, or the terminal error.
type TxWatchFlow = std::ops::ControlFlow<Result<subxt::utils::H256>, ()>;

fn update_waiting_spinner(
	spinner: Option<&indicatif::ProgressBar>,
	target_stage: TransactionStage,
	elapsed_secs: u64,
) {
	if let Some(pb) = spinner {
		if target_stage == TransactionStage::Finalized {
			pb.set_message(format!("Waiting for finalized block... ({}s)", elapsed_secs));
		} else {
			pb.set_message(format!("Waiting for block inclusion... ({}s)", elapsed_secs));
		}
	}
}

fn finish_failed_execution(
	spinner: Option<&indicatif::ProgressBar>,
	message: &str,
	elapsed_secs: u64,
) {
	if let Some(pb) = spinner {
		pb.finish_with_message(format!("{message} ({}s)", elapsed_secs));
	}
}

async fn ensure_execution_success_for_block(
	client: &OnlineClient<ChainConfig>,
	block_hash: &subxt::utils::H256,
	tx_hash: &subxt::utils::H256,
	execution_success_checked_for: &mut Option<subxt::utils::H256>,
) -> Result<()> {
	if should_check_execution_success(block_hash, execution_success_checked_for.as_ref()) {
		check_execution_success(client, block_hash, tx_hash).await?;
		*execution_success_checked_for = Some(*block_hash);
	}
	Ok(())
}

async fn handle_in_best_block(
	client: &OnlineClient<ChainConfig>,
	tx_hash: &subxt::utils::H256,
	block_hash: subxt::utils::H256,
	target_stage: TransactionStage,
	execution_success_checked_for: &mut Option<subxt::utils::H256>,
	spinner: Option<&indicatif::ProgressBar>,
	elapsed_secs: u64,
) -> TxWatchFlow {
	crate::log_verbose!("   Transaction included in block: {:?}", block_hash);
	if let Err(err) = ensure_execution_success_for_block(
		client,
		&block_hash,
		tx_hash,
		execution_success_checked_for,
	)
	.await
	{
		finish_failed_execution(spinner, "❌ Transaction failed in block", elapsed_secs);
		return std::ops::ControlFlow::Break(Err(err));
	}

	match describe_watched_tx_event(WatchedTxEvent::InBestBlock, target_stage) {
		Ok(WatchDecision::WaitForFinalization) => {
			if let Some(pb) = spinner {
				pb.set_message(format!(
					"In best block, waiting for finalization... ({}s)",
					elapsed_secs
				));
			}
			std::ops::ControlFlow::Continue(())
		},
		Ok(WatchDecision::Success) => {
			if let Some(pb) = spinner {
				pb.finish_with_message(format!(
					"✅ Transaction included in block! ({}s)",
					elapsed_secs
				));
			}
			std::ops::ControlFlow::Break(Ok(block_hash))
		},
		Ok(WatchDecision::Continue) => std::ops::ControlFlow::Continue(()),
		Err(err) => std::ops::ControlFlow::Break(Err(err)),
	}
}

async fn handle_in_finalized_block(
	client: &OnlineClient<ChainConfig>,
	tx_hash: &subxt::utils::H256,
	block_hash: subxt::utils::H256,
	target_stage: TransactionStage,
	execution_success_checked_for: &mut Option<subxt::utils::H256>,
	spinner: Option<&indicatif::ProgressBar>,
	elapsed_secs: u64,
) -> TxWatchFlow {
	crate::log_verbose!("   Transaction finalized in block: {:?}", block_hash);
	if let Err(err) = ensure_execution_success_for_block(
		client,
		&block_hash,
		tx_hash,
		execution_success_checked_for,
	)
	.await
	{
		finish_failed_execution(spinner, "❌ Transaction failed in finalized block", elapsed_secs);
		return std::ops::ControlFlow::Break(Err(err));
	}

	match describe_watched_tx_event(WatchedTxEvent::InFinalizedBlock, target_stage) {
		Ok(WatchDecision::Success) => {
			if let Some(pb) = spinner {
				pb.finish_with_message(format!("✅ Transaction finalized! ({}s)", elapsed_secs));
			}
			std::ops::ControlFlow::Break(Ok(block_hash))
		},
		Ok(WatchDecision::Continue) | Ok(WatchDecision::WaitForFinalization) =>
			std::ops::ControlFlow::Continue(()),
		Err(err) => std::ops::ControlFlow::Break(Err(err)),
	}
}

/// Resolve address - if it's a wallet name, return the wallet's address
/// If it's already an SS58 address, return it as is
pub fn resolve_address(address_or_wallet_name: &str) -> Result<String> {
	// First, try to parse as SS58 address
	if AccountId32::from_ss58check_with_version(address_or_wallet_name).is_ok() {
		// It's a valid SS58 address, return as is
		return Ok(address_or_wallet_name.to_string());
	}

	// If not a valid SS58 address, try to find it as a wallet name
	let wallet_manager = crate::wallet::WalletManager::new()?;
	match wallet_manager.find_wallet_address(address_or_wallet_name)? {
		crate::wallet::WalletAddressLookup::Address(wallet_address) => {
			log_verbose!(
				"🔍 Found wallet '{}' with address: {}",
				address_or_wallet_name.bright_cyan(),
				wallet_address.bright_green()
			);
			Ok(wallet_address)
		},
		crate::wallet::WalletAddressLookup::Protected =>
			resolve_protected_wallet_address(&wallet_manager, address_or_wallet_name),
		crate::wallet::WalletAddressLookup::NotFound => Err(crate::error::QuantusError::Generic(
			format!(
				"Invalid destination: '{address_or_wallet_name}' is neither a valid SS58 address nor a known wallet name"
			),
		)),
	}
}

/// Unlock path for resolving a password-protected wallet's address by name.
///
/// Uses the wallet's environment-variable password when set (works in
/// scripts), prompts when running on a terminal, and otherwise fails with an
/// error naming the wallet instead of pretending it does not exist.
fn resolve_protected_wallet_address(
	wallet_manager: &crate::wallet::WalletManager,
	wallet_name: &str,
) -> Result<String> {
	use std::io::IsTerminal;

	let password = if let Some(env_password) =
		crate::wallet::password::env_wallet_password(wallet_name)
	{
		env_password
	} else if std::io::stdin().is_terminal() {
		crate::log_print!(
			"🔒 Wallet '{}' is password-protected; enter its password to resolve its address",
			wallet_name.bright_cyan()
		);
		crate::wallet::password::get_password_from_user(&format!(
			"Enter password for wallet '{wallet_name}'"
		))?
	} else {
		return Err(crate::error::QuantusError::Generic(format!(
			"Wallet '{wallet_name}' exists but is password-protected and no password source is available non-interactively. Pass the SS58 address directly, or set QUANTUS_WALLET_PASSWORD_{} to unlock it",
			wallet_name.to_uppercase()
		)));
	};

	let wallet_data = wallet_manager.load_wallet(wallet_name, &password)?;
	let address = wallet_data.keypair.try_to_account_id_ss58check()?;
	log_verbose!(
		"🔍 Unlocked wallet '{}' with address: {}",
		wallet_name.bright_cyan(),
		address.bright_green()
	);
	Ok(address)
}

/// Resolve a wallet name or SS58 address and convert it into the AccountId32 type used by SubXT.
pub fn resolve_to_subxt_account_id(address_or_wallet_name: &str) -> Result<SubxtAccountId32> {
	let (_, account_id) = resolve_address_with_subxt_account_id(address_or_wallet_name)?;
	Ok(account_id)
}

/// Resolve a wallet name or SS58 address and return both the SS58 string and SubXT account id.
pub fn resolve_address_with_subxt_account_id(
	address_or_wallet_name: &str,
) -> Result<(String, SubxtAccountId32)> {
	let resolved_address = resolve_address(address_or_wallet_name)?;
	let (account_id_sp, _) =
		AccountId32::from_ss58check_with_version(&resolved_address).map_err(|e| {
			crate::error::QuantusError::NetworkError(format!(
				"Invalid destination address {resolved_address}: {e:?}"
			))
		})?;
	let account_id_bytes: [u8; 32] = *account_id_sp.as_ref();
	Ok((resolved_address, SubxtAccountId32::from(account_id_bytes)))
}

/// Get fresh nonce for account from the latest block using existing QuantusClient
/// This function ensures we always get the most current nonce from the chain
/// to avoid "Transaction is outdated" errors
pub async fn get_fresh_nonce_with_client(
	quantus_client: &crate::chain::client::QuantusClient,
	from_keypair: &crate::wallet::QuantumKeyPair,
) -> Result<u64> {
	let from_account_id = from_keypair.try_to_account_id_32().map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Invalid from keypair public key: {e}"))
	})?;

	// Get nonce from the latest block (best block)
	let latest_nonce = quantus_client
		.get_account_nonce_from_best_block(&from_account_id)
		.await
		.map_err(|e| {
			crate::error::QuantusError::NetworkError(format!(
				"Failed to get account nonce from best block: {e:?}"
			))
		})?;

	log_verbose!("🔢 Using fresh nonce from latest block: {}", latest_nonce);

	// Compare with nonce from finalized block for debugging
	let finalized_nonce = quantus_client
		.client()
		.tx()
		.account_nonce(&from_account_id)
		.await
		.map_err(|e| {
			crate::error::QuantusError::NetworkError(format!(
				"Failed to get account nonce from finalized block: {e:?}"
			))
		})?;

	if latest_nonce != finalized_nonce {
		log_verbose!(
			"⚠️  Nonce difference detected! Latest: {}, Finalized: {}",
			latest_nonce,
			finalized_nonce
		);
	}

	Ok(latest_nonce)
}

/// Submit transaction with optional finalization check
///
/// By default, returns immediately after the node accepts the transaction submission.
/// With `wait_for_transaction=true`, waits until the transaction is in a best block.
/// With `finalized=true`, waits until the transaction is in a finalized block.
pub async fn submit_transaction<Call>(
	quantus_client: &crate::chain::client::QuantusClient,
	from_keypair: &crate::wallet::QuantumKeyPair,
	call: Call,
	tip: Option<u128>,
	execution_mode: ExecutionMode,
) -> crate::error::Result<subxt::utils::H256>
where
	Call: subxt::tx::Payload,
{
	let (tx_hash, _included_in) = submit_transaction_with_inclusion_block(
		quantus_client,
		from_keypair,
		call,
		tip,
		execution_mode,
	)
	.await?;
	Ok(tx_hash)
}

/// Reject ML-DSA-65 signers on runtimes that only decode ML-DSA-87 signatures.
async fn ensure_keypair_scheme_supported(
	quantus_client: &crate::chain::client::QuantusClient,
	from_keypair: &crate::wallet::QuantumKeyPair,
) -> crate::error::Result<()> {
	if from_keypair.scheme != crate::wallet::DilithiumScheme::MlDsa65 {
		return Ok(());
	}
	let (spec_version, transaction_version) = quantus_client.get_runtime_version().await?;
	crate::config::ensure_ml_dsa_65_supported(spec_version, transaction_version)
}

/// Like [`submit_transaction`], but also returns the hash of the block in which
/// the transaction reached the requested stage (`None` when the transaction was
/// only submitted without watching).
///
/// Callers that read events for the transaction must use this block hash rather
/// than the current best/finalized tip, which may have moved past the inclusion
/// block by the time the watch returns.
pub async fn submit_transaction_with_inclusion_block<Call>(
	quantus_client: &crate::chain::client::QuantusClient,
	from_keypair: &crate::wallet::QuantumKeyPair,
	call: Call,
	tip: Option<u128>,
	execution_mode: ExecutionMode,
) -> crate::error::Result<(subxt::utils::H256, Option<subxt::utils::H256>)>
where
	Call: subxt::tx::Payload,
{
	ensure_keypair_scheme_supported(quantus_client, from_keypair).await?;

	let signer = from_keypair.to_subxt_signer().map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Failed to convert keypair: {e:?}"))
	})?;

	// Get a fresh nonce from the best block. Do not automatically resubmit the same
	// call with a different nonce after a submission error: without authoritative
	// confirmation that the prior extrinsic was rejected, doing so can duplicate
	// non-idempotent transactions.
	let nonce = get_fresh_nonce_with_client(quantus_client, from_keypair).await?;
	log_verbose!("🔢 Using fresh nonce from best block: {}", nonce);

	// Get current block for logging using latest block hash
	let latest_block_hash = quantus_client.get_latest_block().await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Failed to get latest block: {e:?}"))
	})?;

	log_verbose!("🔗 Latest block hash: {:?}", latest_block_hash);

	// Create custom params with fresh nonce and optional tip
	use subxt::config::DefaultExtrinsicParamsBuilder;
	let mut params_builder = DefaultExtrinsicParamsBuilder::new()
		.mortal(256) // Value higher than our finalization - TODO: should come from config
		.nonce(nonce);

	if let Some(tip_amount) = tip {
		params_builder = params_builder.tip(tip_amount);
		log_verbose!("💰 Using tip: {} to increase priority", tip_amount);
	} else {
		log_verbose!("💰 No tip specified");
	}

	// Try to get chain parameters from the client
	// let genesis_hash = quantus_client.get_genesis_hash().await?;
	// let (spec_version, transaction_version) = quantus_client.get_runtime_version().await?;

	// log_verbose!("🔍 Chain parameters:");
	// log_verbose!("   Genesis hash: {:?}", genesis_hash);
	// log_verbose!("   Spec version: {}", spec_version);
	// log_verbose!("   Transaction version: {}", transaction_version);

	// For now, just use the default params
	let params = params_builder.build();

	// Log transaction parameters for debugging
	log_verbose!("🔍 Transaction parameters:");
	log_verbose!("   Nonce: {}", nonce);
	log_verbose!("   Tip: {:?}", tip);
	log_verbose!("   Latest block hash: {:?}", latest_block_hash);

	// Get and log era information
	log_verbose!("   Era: Using default era from SubXT");
	log_verbose!("   Genesis hash: Using default from SubXT");
	log_verbose!("   Spec version: Using default from SubXT");

	// Log additional debugging info
	log_verbose!("🔍 Additional debugging:");
	log_verbose!("   Call type: {:?}", std::any::type_name::<Call>());

	let metadata = quantus_client.client().metadata();
	let encoded_call =
		<_ as subxt::tx::Payload>::encode_call_data(&call, &metadata).map_err(|e| {
			crate::error::QuantusError::NetworkError(format!("Failed to encode call: {:?}", e))
		})?;
	crate::log_verbose!("📝 Encoded call: 0x{}", hex::encode(&encoded_call));
	crate::log_print!("📝 Encoded call size: {} bytes", encoded_call.len());

	if execution_mode.should_watch_transaction() {
		match quantus_client
			.client()
			.tx()
			.sign_and_submit_then_watch(&call, &signer, params)
			.await
		{
			Ok(mut tx_progress) => {
				crate::log_verbose!("📋 Transaction submitted: {:?}", tx_progress);

				let tx_hash = tx_progress.extrinsic_hash();

				let included_in = wait_tx_inclusion(
					&mut tx_progress,
					quantus_client.client(),
					&tx_hash,
					execution_mode.transaction_stage(),
				)
				.await?;

				Ok((tx_hash, Some(included_in)))
			},
			Err(e) => {
				log_error!("❌ Failed to submit transaction: {e:?}");
				Err(e.into())
			},
		}
	} else {
		match quantus_client.client().tx().sign_and_submit(&call, &signer, params).await {
			Ok(tx_hash) => {
				crate::log_print!("✅ Transaction submitted: {:?}", tx_hash);
				Ok((tx_hash, None))
			},
			Err(e) => {
				log_error!("❌ Failed to submit transaction: {e:?}");
				Err(e.into())
			},
		}
	}
}

/// Submit transaction with manual nonce (no retry logic - use exact nonce provided)
pub async fn submit_transaction_with_nonce<Call>(
	quantus_client: &crate::chain::client::QuantusClient,
	from_keypair: &crate::wallet::QuantumKeyPair,
	call: Call,
	tip: Option<u128>,
	nonce: u32,
	execution_mode: ExecutionMode,
) -> crate::error::Result<subxt::utils::H256>
where
	Call: subxt::tx::Payload,
{
	ensure_keypair_scheme_supported(quantus_client, from_keypair).await?;

	let signer = from_keypair.to_subxt_signer().map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Failed to convert keypair: {e:?}"))
	})?;

	// Get current block for logging using latest block hash
	let latest_block_hash = quantus_client.get_latest_block().await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Failed to get latest block: {e:?}"))
	})?;

	log_verbose!("🔗 Latest block hash: {:?}", latest_block_hash);

	// Create custom params with manual nonce and optional tip
	use subxt::config::DefaultExtrinsicParamsBuilder;
	let mut params_builder = DefaultExtrinsicParamsBuilder::new()
		.mortal(256) // Value higher than our finalization - TODO: should come from config
		.nonce(nonce.into());

	if let Some(tip_amount) = tip {
		params_builder = params_builder.tip(tip_amount);
		log_verbose!("💰 Using tip: {}", tip_amount);
	}

	let params = params_builder.build();

	log_verbose!("🔢 Using manual nonce: {}", nonce);
	log_verbose!("📤 Submitting transaction with manual nonce...");

	// Submit the transaction with manual nonce
	if execution_mode.should_watch_transaction() {
		match quantus_client
			.client()
			.tx()
			.sign_and_submit_then_watch(&call, &signer, params)
			.await
		{
			Ok(mut tx_progress) => {
				let tx_hash = tx_progress.extrinsic_hash();
				crate::log_print!("✅ Transaction submitted: {:?}", tx_hash);
				let _included_in = wait_tx_inclusion(
					&mut tx_progress,
					quantus_client.client(),
					&tx_hash,
					execution_mode.transaction_stage(),
				)
				.await?;
				Ok(tx_hash)
			},
			Err(e) => {
				log_error!("❌ Failed to submit transaction with manual nonce {}: {e:?}", nonce);
				Err(e.into())
			},
		}
	} else {
		match quantus_client.client().tx().sign_and_submit(&call, &signer, params).await {
			Ok(tx_hash) => {
				crate::log_print!("✅ Transaction submitted: {:?}", tx_hash);
				Ok(tx_hash)
			},
			Err(e) => {
				log_error!("❌ Failed to submit transaction: {e:?}");
				Err(e.into())
			},
		}
	}
}

/// Watch transaction until it is included in the best block or finalized
///
/// Since Quantus network is PoW, we can't use default subxt's way of waiting for finalized block as
/// it may take a long time. We wait for the transaction to be included in the best block and leave
/// it up to the user to check the status of the transaction.
///
/// Returns the hash of the block in which the transaction reached the target
/// stage, so callers can read events from the actual inclusion block instead of
/// racing the moving finalized tip.
///
/// Also used by unsigned wormhole verify submitters so they share the same
/// inactivity / overall-deadline bounds as signed watches.
pub(crate) async fn wait_tx_inclusion(
	tx_progress: &mut TxProgress<ChainConfig, OnlineClient<ChainConfig>>,
	client: &OnlineClient<ChainConfig>,
	tx_hash: &subxt::utils::H256,
	target_stage: TransactionStage,
) -> Result<subxt::utils::H256> {
	use indicatif::{ProgressBar, ProgressStyle};

	let start_time = std::time::Instant::now();
	let mut execution_success_checked_for = None;

	let spinner = if !crate::log::is_verbose() && !crate::log::is_quiet() {
		let pb = ProgressBar::new_spinner();
		pb.set_style(
			ProgressStyle::default_spinner()
				.tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")
				.template("{spinner:.cyan} {msg}")
				.unwrap(),
		);

		if target_stage == TransactionStage::Finalized {
			pb.set_message("Waiting for finalized block... (0s)");
		} else {
			pb.set_message("Waiting for block inclusion... (0s)");
		}

		pb.enable_steady_tick(std::time::Duration::from_millis(500));
		Some(pb)
	} else {
		None
	};

	let watch_timeout_secs = tx_status_watch_timeout_secs(target_stage);
	// After best-block inclusion while targeting finalization, PoW can be silent for
	// longer than the inactivity window; only the overall deadline should abort then.
	let mut waiting_for_finalization = false;

	loop {
		let elapsed_before_wait = start_time.elapsed().as_secs();
		let remaining_watch_secs = watch_timeout_secs.saturating_sub(elapsed_before_wait);
		let apply_inactivity_timeout = !waiting_for_finalization;
		let wait_secs = next_status_wait_secs(remaining_watch_secs, apply_inactivity_timeout);
		let (next_event, elapsed_secs) = if wait_secs == 0 {
			(
				WatchedTxEvent::WatchDeadlineTimedOut { elapsed_secs: elapsed_before_wait },
				elapsed_before_wait,
			)
		} else {
			let next_status =
				tokio::time::timeout(std::time::Duration::from_secs(wait_secs), tx_progress.next())
					.await;
			let elapsed_secs = start_time.elapsed().as_secs();
			let next_event = match next_status {
				Ok(Some(Ok(status))) => {
					crate::log_verbose!(
						"   Transaction status: {:?} (elapsed: {}s)",
						status,
						elapsed_secs
					);

					match status {
						TxStatus::Validated => {
							if let Some(ref pb) = spinner {
								pb.set_message(format!(
									"Transaction validated ✓ ({}s)",
									elapsed_secs
								));
							}
							WatchedTxEvent::Validated
						},
						TxStatus::Broadcasted => WatchedTxEvent::Broadcasted,
						TxStatus::NoLongerInBestBlock => {
							execution_success_checked_for = None;
							// Reorged out of best block; resume inactivity protection until
							// we see inclusion again.
							waiting_for_finalization = false;
							WatchedTxEvent::NoLongerInBestBlock
						},
						TxStatus::InBestBlock(tx_in_block) => {
							let block_hash = tx_in_block.block_hash();
							match handle_in_best_block(
								client,
								tx_hash,
								block_hash,
								target_stage,
								&mut execution_success_checked_for,
								spinner.as_ref(),
								elapsed_secs,
							)
							.await
							{
								std::ops::ControlFlow::Continue(()) => {
									if target_stage == TransactionStage::Finalized {
										waiting_for_finalization = true;
									}
									continue;
								},
								std::ops::ControlFlow::Break(result) => return result,
							}
						},
						TxStatus::InFinalizedBlock(tx_in_block) => {
							let block_hash = tx_in_block.block_hash();
							match handle_in_finalized_block(
								client,
								tx_hash,
								block_hash,
								target_stage,
								&mut execution_success_checked_for,
								spinner.as_ref(),
								elapsed_secs,
							)
							.await
							{
								std::ops::ControlFlow::Continue(()) => continue,
								std::ops::ControlFlow::Break(result) => return result,
							}
						},
						TxStatus::Error { message } => WatchedTxEvent::Error(message),
						TxStatus::Invalid { message } => WatchedTxEvent::Invalid(message),
						TxStatus::Dropped { message } => WatchedTxEvent::Dropped(message),
					}
				},
				Ok(Some(Err(err))) => WatchedTxEvent::StreamError(err.to_string()),
				Ok(None) => WatchedTxEvent::StreamEnded,
				Err(_) => {
					if apply_inactivity_timeout &&
						wait_secs == TX_STATUS_INACTIVITY_TIMEOUT_SECS &&
						remaining_watch_secs > TX_STATUS_INACTIVITY_TIMEOUT_SECS
					{
						WatchedTxEvent::InactivityTimedOut {
							timeout_secs: TX_STATUS_INACTIVITY_TIMEOUT_SECS,
						}
					} else {
						WatchedTxEvent::WatchDeadlineTimedOut { elapsed_secs }
					}
				},
			};
			(next_event, elapsed_secs)
		};

		match describe_watched_tx_event(next_event, target_stage) {
			Ok(WatchDecision::Continue) | Ok(WatchDecision::WaitForFinalization) => {
				update_waiting_spinner(spinner.as_ref(), target_stage, elapsed_secs);
			},
			// In-block events are handled (and returned) above; no other event
			// reports Success, so this arm is defensively unreachable.
			Ok(WatchDecision::Success) =>
				return Err(crate::error::QuantusError::Generic(
					"transaction watcher reported success without an inclusion block".to_string(),
				)),
			Err(err) => {
				crate::log_error!("   {} (elapsed: {}s)", err, elapsed_secs);
				if let Some(pb) = spinner {
					pb.finish_with_message(format!("❌ Transaction error! ({}s)", elapsed_secs));
				}
				return Err(err);
			},
		}
	}
}

pub(crate) fn format_dispatch_error(
	error: &crate::chain::quantus_subxt::api::runtime_types::sp_runtime::DispatchError,
	metadata: &subxt::Metadata,
) -> String {
	use crate::chain::quantus_subxt::api::runtime_types::sp_runtime::DispatchError;

	match error {
		DispatchError::Module(module_error) => {
			let pallet_index = module_error.index;
			let error_index = module_error.error[0];

			// Try to get human-readable error name from metadata
			if let Some(pallet) = metadata.pallet_by_index(pallet_index) {
				let pallet_name = pallet.name();
				// Look up the error variant name from metadata
				if let Some(variant) = pallet.error_variant_by_index(error_index) {
					let error_name = &variant.name;
					let docs = variant.docs.join(" ");
					if docs.is_empty() {
						format!("{}::{}", pallet_name, error_name)
					} else {
						format!("{}::{} - {}", pallet_name, error_name, docs)
					}
				} else {
					format!("{}::Error[{}]", pallet_name, error_index)
				}
			} else {
				format!("Pallet[{}]::Error[{}]", pallet_index, error_index)
			}
		},
		DispatchError::BadOrigin => "BadOrigin".to_string(),
		DispatchError::CannotLookup => "CannotLookup".to_string(),
		DispatchError::Other => "Other".to_string(),
		_ => format!("{:?}", error),
	}
}

async fn verify_preimage_on_chain(
	quantus_client: &crate::chain::client::QuantusClient,
	expected_preimage: &[u8],
	at_block: subxt::utils::H256,
) -> Result<()> {
	use sp_runtime::traits::{BlakeTwo256, Hash};

	let preimage_hash: sp_core::H256 = BlakeTwo256::hash(expected_preimage);
	let preimage_len = u32::try_from(expected_preimage.len()).map_err(|_| {
		crate::error::QuantusError::Generic(format!(
			"Preimage is too large to address: {} bytes",
			expected_preimage.len()
		))
	})?;
	let storage_at = quantus_client.client().storage().at(at_block);
	let preimage_addr = crate::chain::quantus_subxt::api::storage()
		.preimage()
		.preimage_for((preimage_hash, preimage_len));

	match storage_at.fetch(&preimage_addr).await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!(
			"Failed to fetch preimage {:?} ({} bytes): {e:?}",
			preimage_hash, preimage_len
		))
	})? {
		Some(stored_preimage) if stored_preimage.0.as_slice() == expected_preimage => Ok(()),
		Some(stored_preimage) => Err(crate::error::QuantusError::Generic(format!(
			"On-chain preimage mismatch for {:?}: expected {} bytes, found {} bytes",
			preimage_hash,
			preimage_len,
			stored_preimage.0.len()
		))),
		None => Err(crate::error::QuantusError::Generic(format!(
			"Expected preimage {:?} ({} bytes) is not present on-chain",
			preimage_hash, preimage_len
		))),
	}
}

pub async fn submit_preimage(
	quantus_client: &crate::chain::client::QuantusClient,
	keypair: &crate::wallet::QuantumKeyPair,
	encoded_call: Vec<u8>,
	execution_mode: ExecutionMode,
) -> Result<()> {
	type PreimageBytes =
		crate::chain::quantus_subxt::api::preimage::calls::types::note_preimage::Bytes;
	let bounded_bytes: PreimageBytes = encoded_call.clone();

	crate::log_print!("📝 Submitting preimage...");
	let note_preimage_tx =
		crate::chain::quantus_subxt::api::tx().preimage().note_preimage(bounded_bytes);
	let wait_mode = ExecutionMode { wait_for_transaction: true, ..execution_mode };

	match submit_transaction_with_inclusion_block(
		quantus_client,
		keypair,
		note_preimage_tx,
		None,
		wait_mode,
	)
	.await
	{
		Ok((_, included_in)) => {
			// Verify in the inclusion block: the moving tip may not have
			// advanced past (or even reached) the inclusion block when the
			// watch returns, so reading the latest block can miss the
			// just-noted preimage.
			let at_block = match included_in {
				Some(hash) => hash,
				None => quantus_client.get_latest_block().await?,
			};
			verify_preimage_on_chain(quantus_client, &encoded_call, at_block).await?;
			crate::log_success!("Preimage submitted");
		},
		Err(e) => {
			// Do not trust formatted error substrings (e.g. "AlreadyNoted"). Only
			// continue when the expected preimage bytes are present on-chain.
			// There is no inclusion block here (the submission failed), so an
			// already-noted preimage is looked up at the current tip.
			let latest_block_hash = quantus_client.get_latest_block().await?;
			verify_preimage_on_chain(quantus_client, &encoded_call, latest_block_hash)
				.await
				.map_err(|verify_err| {
					crate::error::QuantusError::Generic(format!(
					"Preimage submission failed ({e}); on-chain verification also failed ({verify_err})"
				))
				})?;
			crate::log_print!(
				"✅ {} Expected preimage already exists on-chain, continuing",
				"OK".bright_green().bold()
			);
		},
	}
	Ok(())
}

pub(crate) async fn check_execution_success(
	client: &OnlineClient<ChainConfig>,
	block_hash: &subxt::utils::H256,
	tx_hash: &subxt::utils::H256,
) -> Result<()> {
	use crate::chain::quantus_subxt::api::system::events::ExtrinsicFailed;

	let block = client.blocks().at(*block_hash).await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Failed to get block: {e:?}"))
	})?;

	let extrinsics = block.extrinsics().await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Failed to get extrinsics: {e:?}"))
	})?;

	let our_extrinsic_index = extrinsics
		.iter()
		.enumerate()
		.find(|(_, ext)| ext.hash() == *tx_hash)
		.map(|(idx, _)| idx);

	let events = block.events().await.map_err(|e| {
		crate::error::QuantusError::NetworkError(format!("Failed to fetch events: {e:?}"))
	})?;

	let ext_idx = require_extrinsic_index(our_extrinsic_index)?;

	let metadata = client.metadata();
	for event_result in events.iter() {
		let event = event_result.map_err(|e| {
			crate::error::QuantusError::NetworkError(format!("Failed to decode event: {e:?}"))
		})?;

		if let subxt::events::Phase::ApplyExtrinsic(event_ext_idx) = event.phase() {
			if event_ext_idx == ext_idx as u32 {
				if let Ok(Some(ExtrinsicFailed { dispatch_error, .. })) =
					event.as_event::<ExtrinsicFailed>()
				{
					let error_msg = format_dispatch_error(&dispatch_error, &metadata);
					crate::log_error!("   Transaction failed: {}", error_msg);
					return Err(crate::error::QuantusError::NetworkError(format!(
						"Transaction execution failed: {}",
						error_msg
					)));
				}
			}
		}
	}

	Ok(())
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn delay_blocks_to_u32_rejects_values_above_u32_max() {
		let too_large = u32::MAX as u64 + 7200;
		let err = delay_blocks_to_u32(too_large).unwrap_err();
		assert!(
			err.to_string().contains("exceeds the maximum supported block delay"),
			"unexpected error: {err}"
		);
		assert_eq!(delay_blocks_to_u32(u32::MAX as u64).unwrap(), u32::MAX);
	}

	#[test]
	fn delay_seconds_to_millis_rejects_overflow() {
		let too_large = (u64::MAX / MILLIS_PER_SECOND) + 1;
		let err = delay_seconds_to_millis(too_large).unwrap_err();
		assert!(
			err.to_string().contains("exceeds the maximum supported timestamp delay"),
			"unexpected error: {err}"
		);
		assert_eq!(delay_seconds_to_millis(1).unwrap(), 1_000);
	}

	#[test]
	fn finalized_mode_implies_waiting_for_finalization() {
		let mode = ExecutionMode { finalized: true, wait_for_transaction: false };

		assert_eq!(mode.transaction_stage(), TransactionStage::Finalized);
		assert!(mode.should_watch_transaction());
	}

	#[test]
	fn default_mode_is_submission_only() {
		let mode = ExecutionMode::default();

		assert_eq!(mode.transaction_stage(), TransactionStage::Submitted);
		assert!(!mode.should_watch_transaction());
	}

	#[test]
	fn watched_failures_are_terminal_errors() {
		assert!(describe_watched_tx_event(
			WatchedTxEvent::Error("boom".to_string()),
			TransactionStage::Included,
		)
		.is_err());
		assert!(describe_watched_tx_event(
			WatchedTxEvent::Invalid("bad nonce".to_string()),
			TransactionStage::Included,
		)
		.is_err());
		assert!(describe_watched_tx_event(
			WatchedTxEvent::Dropped("dropped".to_string()),
			TransactionStage::Included,
		)
		.is_err());
		assert!(describe_watched_tx_event(
			WatchedTxEvent::StreamError("rpc failed".to_string()),
			TransactionStage::Included,
		)
		.is_err());
		assert!(
			describe_watched_tx_event(WatchedTxEvent::StreamEnded, TransactionStage::Included,)
				.is_err()
		);
		let inactivity_err = describe_watched_tx_event(
			WatchedTxEvent::InactivityTimedOut { timeout_secs: TX_STATUS_INACTIVITY_TIMEOUT_SECS },
			TransactionStage::Included,
		)
		.expect_err("silent subscription must time out instead of waiting forever");
		assert!(
			inactivity_err.to_string().contains("without updates") &&
				inactivity_err
					.to_string()
					.contains(&TX_STATUS_INACTIVITY_TIMEOUT_SECS.to_string()),
			"unexpected inactivity error: {inactivity_err}"
		);

		let deadline_err = describe_watched_tx_event(
			WatchedTxEvent::WatchDeadlineTimedOut {
				elapsed_secs: TX_STATUS_FINALIZED_TIMEOUT_SECS,
			},
			TransactionStage::Finalized,
		)
		.expect_err("overall finalized deadline must be an error");
		let deadline_msg = deadline_err.to_string();
		assert!(
			deadline_msg.contains("Timed out after waiting") &&
				deadline_msg.contains(&TX_STATUS_FINALIZED_TIMEOUT_SECS.to_string()) &&
				!deadline_msg.contains("without updates"),
			"overall deadline must not be reported as the inactivity window: {deadline_msg}"
		);
	}

	#[test]
	fn transaction_status_watch_deadlines_are_finite() {
		assert_eq!(tx_status_watch_timeout_secs(TransactionStage::Submitted), 0);
		assert_eq!(
			tx_status_watch_timeout_secs(TransactionStage::Included),
			TX_STATUS_INCLUDED_TIMEOUT_SECS
		);
		assert_eq!(
			tx_status_watch_timeout_secs(TransactionStage::Finalized),
			TX_STATUS_FINALIZED_TIMEOUT_SECS
		);
		const {
			assert!(TX_STATUS_INACTIVITY_TIMEOUT_SECS > 0);
			// Must cover many ~10s PoW block intervals: the stream is silent
			// between Broadcasted and InBestBlock, and aborting a valid pending
			// transaction invites duplicate-submission retries (#160612).
			assert!(TX_STATUS_INACTIVITY_TIMEOUT_SECS >= 120);
			assert!(TX_STATUS_INACTIVITY_TIMEOUT_SECS < TX_STATUS_INCLUDED_TIMEOUT_SECS);
			assert!(TX_STATUS_INCLUDED_TIMEOUT_SECS < TX_STATUS_FINALIZED_TIMEOUT_SECS);
		}
	}

	#[test]
	fn finalization_wait_does_not_use_short_inactivity_timeout() {
		// Before inclusion, keep the short inactivity cap.
		assert_eq!(
			next_status_wait_secs(TX_STATUS_FINALIZED_TIMEOUT_SECS, true),
			TX_STATUS_INACTIVITY_TIMEOUT_SECS
		);
		// After best-block inclusion while waiting for PoW finalization, allow the
		// full remaining overall deadline so silent finality gaps do not abort early.
		assert_eq!(
			next_status_wait_secs(TX_STATUS_FINALIZED_TIMEOUT_SECS, false),
			TX_STATUS_FINALIZED_TIMEOUT_SECS
		);
		assert_eq!(next_status_wait_secs(12, false), 12);
		assert_eq!(next_status_wait_secs(0, false), 0);
	}

	#[test]
	fn inclusion_and_finalization_have_distinct_success_states() {
		assert_eq!(
			describe_watched_tx_event(WatchedTxEvent::InBestBlock, TransactionStage::Included)
				.unwrap(),
			WatchDecision::Success
		);
		assert_eq!(
			describe_watched_tx_event(WatchedTxEvent::InBestBlock, TransactionStage::Finalized)
				.unwrap(),
			WatchDecision::WaitForFinalization
		);
		assert_eq!(
			describe_watched_tx_event(
				WatchedTxEvent::InFinalizedBlock,
				TransactionStage::Finalized,
			)
			.unwrap(),
			WatchDecision::Success
		);
	}

	#[test]
	fn execution_success_check_is_skipped_for_same_block() {
		let best_block_hash = subxt::utils::H256::from([7u8; 32]);
		let finalized_block_hash = subxt::utils::H256::from([8u8; 32]);

		assert!(should_check_execution_success(&best_block_hash, None));
		assert!(!should_check_execution_success(&best_block_hash, Some(&best_block_hash),));
		assert!(should_check_execution_success(&finalized_block_hash, Some(&best_block_hash),));
	}

	#[test]
	fn missing_extrinsic_hash_in_reported_block_is_error() {
		let err = require_extrinsic_index(None).expect_err("absent extrinsic must not succeed");
		match err {
			crate::error::QuantusError::NetworkError(msg) => {
				assert!(
					msg.contains("not found in reported block"),
					"unexpected error message: {msg}"
				);
			},
			other => panic!("expected NetworkError, got {other:?}"),
		}

		assert_eq!(require_extrinsic_index(Some(3)).unwrap(), 3);
	}

	#[test]
	fn submit_preimage_does_not_classify_already_noted_by_substring() {
		// #160718: control flow must not branch on the literal "AlreadyNoted" in
		// formatted errors; success after a submit failure requires on-chain
		// preimage verification instead.
		let source = include_str!("common.rs");
		assert!(
			!source.contains("contains(\"AlreadyNoted\")"),
			"submit_preimage must not accept errors based on AlreadyNoted substrings"
		);
		assert!(
			source.contains("verify_preimage_on_chain"),
			"submit_preimage must verify expected preimage bytes on-chain"
		);
	}
}