-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommon.rs
More file actions
606 lines (540 loc) · 19.5 KB
/
common.rs
File metadata and controls
606 lines (540 loc) · 19.5 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
//! 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,
};
#[derive(Debug, Clone, Copy, Default)]
pub struct ExecutionMode {
pub finalized: bool,
pub wait_for_transaction: bool,
}
/// 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()?;
if let Some(wallet_address) = wallet_manager.find_wallet_address(address_or_wallet_name)? {
log_verbose!(
"🔍 Found wallet '{}' with address: {}",
address_or_wallet_name.bright_cyan(),
wallet_address.bright_green()
);
return Ok(wallet_address);
}
// Neither a valid SS58 address nor a wallet name
Err(crate::error::QuantusError::Generic(format!(
"Invalid destination: '{address_or_wallet_name}' is neither a valid SS58 address nor a known wallet name"
)))
}
/// 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, _version) =
AccountId32::from_ss58check_with_version(&from_keypair.to_account_id_ss58check()).map_err(
|e| crate::error::QuantusError::NetworkError(format!("Invalid from address: {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)
}
/// Get incremented nonce for retry scenarios from the latest block using existing QuantusClient
/// This is useful when a transaction fails but the chain doesn't update the nonce
pub async fn get_incremented_nonce_with_client(
quantus_client: &crate::chain::client::QuantusClient,
from_keypair: &crate::wallet::QuantumKeyPair,
base_nonce: u64,
) -> Result<u64> {
let (from_account_id, _version) =
AccountId32::from_ss58check_with_version(&from_keypair.to_account_id_ss58check()).map_err(
|e| crate::error::QuantusError::NetworkError(format!("Invalid from address: {e:?}")),
)?;
// Get current nonce from the latest block
let current_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:?}"
))
})?;
// Use the higher of current nonce or base_nonce + 1
let incremented_nonce = std::cmp::max(current_nonce, base_nonce + 1);
log_verbose!(
"🔢 Using incremented nonce: {} (base: {}, current from latest block: {})",
incremented_nonce,
base_nonce,
current_nonce
);
Ok(incremented_nonce)
}
/// Submit transaction with optional finalization check
///
/// By default (finalized=false), waits until transaction is in the best block (fast)
/// With finalized=true, waits until transaction is in a finalized block (slow in PoW chains)
/// With wait_for_transaction=false, returns immediately after submission without waiting
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 signer = from_keypair.to_subxt_signer().map_err(|e| {
crate::error::QuantusError::NetworkError(format!("Failed to convert keypair: {e:?}"))
})?;
// Retry logic with automatic nonce management
let mut attempt = 0;
let mut current_nonce = None;
loop {
attempt += 1;
// Get fresh nonce for each attempt, or increment if we have a previous nonce
let nonce = if let Some(prev_nonce) = current_nonce {
// After first failure, try with incremented nonce
let incremented_nonce =
get_incremented_nonce_with_client(quantus_client, from_keypair, prev_nonce).await?;
log_verbose!(
"🔢 Using incremented nonce from best block: {} (previous: {})",
incremented_nonce,
prev_nonce
);
incremented_nonce
} else {
// First attempt - get fresh nonce from best block
let fresh_nonce = get_fresh_nonce_with_client(quantus_client, from_keypair).await?;
log_verbose!("🔢 Using fresh nonce from best block: {}", fresh_nonce);
fresh_nonce
};
current_nonce = Some(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, using default priority");
}
// 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.wait_for_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();
if !execution_mode.wait_for_transaction {
return Ok(tx_hash);
}
wait_tx_inclusion(
&mut tx_progress,
quantus_client.client(),
&tx_hash,
execution_mode.finalized,
)
.await?;
return Ok(tx_hash);
},
Err(e) => {
let error_msg = format!("{e:?}");
// Check if it's a retryable error
let is_retryable = error_msg.contains("Priority is too low") ||
error_msg.contains("Transaction is outdated") ||
error_msg.contains("Transaction is temporarily banned") ||
error_msg.contains("Transaction has a bad signature") ||
error_msg.contains("Invalid Transaction");
if is_retryable && attempt < 5 {
log_verbose!(
"⚠️ Transaction error detected (attempt {}/5): {}",
attempt,
error_msg
);
// Exponential backoff: 2s, 4s, 8s, 16s
let delay = std::cmp::min(2u64.pow(attempt as u32), 16);
log_verbose!("⏳ Waiting {} seconds before retry...", delay);
tokio::time::sleep(tokio::time::Duration::from_secs(delay)).await;
continue;
} else {
log_verbose!("❌ Final error after {} attempts: {}", attempt, error_msg);
return Err(crate::error::QuantusError::NetworkError(format!(
"Failed to submit transaction: {e:?}"
)));
}
},
}
} else {
match quantus_client.client().tx().sign_and_submit(&call, &signer, params).await {
Ok(tx_hash) => {
crate::log_print!("✅ Transaction submitted: {:?}", tx_hash);
return Ok(tx_hash);
},
Err(e) => {
log_error!("❌ Failed to submit transaction: {e:?}");
return Err(crate::error::QuantusError::NetworkError(format!(
"Failed to submit transaction: {e:?}"
)));
},
}
}
}
}
/// 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,
{
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...");
crate::log_print!("submit with wait for transaction: {}", execution_mode.wait_for_transaction);
// Submit the transaction with manual nonce
if execution_mode.wait_for_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);
wait_tx_inclusion(
&mut tx_progress,
quantus_client.client(),
&tx_hash,
execution_mode.finalized,
)
.await?;
Ok(tx_hash)
},
Err(e) => {
log_error!("❌ Failed to submit transaction with manual nonce {}: {e:?}", nonce);
Err(crate::error::QuantusError::NetworkError(format!(
"Failed to submit transaction with nonce {nonce}: {e:?}"
)))
},
}
} 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(crate::error::QuantusError::NetworkError(format!(
"Failed to submit transaction: {e:?}"
)))
},
}
}
}
/// 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.
async fn wait_tx_inclusion(
tx_progress: &mut TxProgress<ChainConfig, OnlineClient<ChainConfig>>,
client: &OnlineClient<ChainConfig>,
tx_hash: &subxt::utils::H256,
finalized: bool,
) -> Result<()> {
use indicatif::{ProgressBar, ProgressStyle};
let start_time = std::time::Instant::now();
let spinner = if !crate::log::is_verbose() {
let pb = ProgressBar::new_spinner();
pb.set_style(
ProgressStyle::default_spinner()
.tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")
.template("{spinner:.cyan} {msg}")
.unwrap(),
);
if 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
};
while let Some(Ok(status)) = tx_progress.next().await {
let elapsed_secs = start_time.elapsed().as_secs();
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));
},
TxStatus::InBestBlock(tx_in_block) => {
let block_hash = tx_in_block.block_hash();
crate::log_verbose!(" Transaction included in block: {:?}", block_hash);
check_execution_success(client, &block_hash, tx_hash).await?;
if finalized {
if let Some(ref pb) = spinner {
pb.set_message(format!(
"In best block, waiting for finalization... ({}s)",
elapsed_secs
));
}
continue;
} else {
if let Some(pb) = spinner {
pb.finish_with_message(format!(
"✅ Transaction included in block! ({}s)",
elapsed_secs
));
}
break;
};
},
TxStatus::InFinalizedBlock(tx_in_block) => {
let block_hash = tx_in_block.block_hash();
crate::log_verbose!(" Transaction finalized in block: {:?}", block_hash);
check_execution_success(client, &block_hash, tx_hash).await?;
if let Some(pb) = spinner {
pb.finish_with_message(format!(
"✅ Transaction finalized! ({}s)",
elapsed_secs
));
}
break;
},
TxStatus::Error { message } | TxStatus::Invalid { message } => {
crate::log_error!(" Transaction error: {} (elapsed: {}s)", message, elapsed_secs);
if let Some(pb) = spinner {
pb.finish_with_message(format!("❌ Transaction error! ({}s)", elapsed_secs));
}
break;
},
_ => {
if let Some(ref pb) = spinner {
if finalized {
pb.set_message(format!(
"Waiting for finalized block... ({}s)",
elapsed_secs
));
} else {
pb.set_message(format!(
"Waiting for block inclusion... ({}s)",
elapsed_secs
));
}
}
continue;
},
}
}
Ok(())
}
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),
}
}
/// Submit a preimage, treating AlreadyNoted as success (idempotent).
/// Always waits for inclusion so subsequent txs from the same sender get a fresh nonce.
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;
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(quantus_client, keypair, note_preimage_tx, None, wait_mode).await {
Ok(_) => {
crate::log_success!("Preimage submitted");
},
Err(e) if e.to_string().contains("AlreadyNoted") => {
crate::log_print!(
"✅ {} Preimage already exists on-chain, continuing",
"OK".bright_green().bold()
);
},
Err(e) => return Err(e),
}
Ok(())
}
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 metadata = client.metadata();
if let Some(ext_idx) = our_extrinsic_index {
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(())
}