quantus-cli 1.3.2

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
//! `quantus storage` subcommand - storage operations

use crate::{
	chain::{client::ChainConfig, quantus_subxt},
	cli::address_format::QuantusSS58,
	error::QuantusError,
	log_error, log_print, log_success, log_verbose,
};
use clap::Subcommand;
use codec::Decode;
use colored::Colorize;
use serde::Deserialize;
use sp_core::{crypto::AccountId32, twox_128};
use std::{collections::BTreeMap, str::FromStr};
use subxt::OnlineClient;

/// The `AccountData` struct, used in `AccountInfo`.
#[derive(Decode, Debug, Deserialize, Clone, PartialEq, Eq)]
pub struct AccountData {
	pub free: u128,
	pub reserved: u128,
	pub frozen: u128,
	pub flags: u128,
}

/// The `AccountInfo` struct, reflecting the chain's state.
#[derive(Decode, Debug, Deserialize, Clone, PartialEq, Eq)]
pub struct AccountInfo {
	pub nonce: u32,
	pub consumers: u32,
	pub providers: u32,
	pub sufficients: u32,
	pub data: AccountData,
}

/// Validate that a pallet exists in the chain metadata
fn validate_pallet_exists(
	client: &OnlineClient<ChainConfig>,
	pallet_name: &str,
) -> crate::error::Result<()> {
	let metadata = client.metadata();
	metadata.pallet_by_name(pallet_name).ok_or_else(|| {
		QuantusError::Generic(format!(
			"Pallet '{}' not found in chain metadata. Available pallets: {}",
			pallet_name,
			quantus_subxt::api::PALLETS.join(", ")
		))
	})?;
	Ok(())
}

/// Direct interaction with chain storage (read-only)
#[derive(Subcommand, Debug)]
pub enum StorageCommands {
	/// Get a storage value from a pallet.
	///
	/// This command constructs a storage key from the pallet and item names,
	/// fetches the raw value from the chain state, and prints it as a hex string.
	/// If --block is specified, queries storage at that specific block instead of latest.
	/// If no --key is provided, automatically counts all entries in the storage map.
	Get {
		/// The name of the pallet (e.g., "System").
		#[arg(long, required_unless_present = "storage_key")]
		pallet: Option<String>,

		/// The name of the storage item (e.g., "Account").
		#[arg(long, required_unless_present = "storage_key")]
		name: Option<String>,

		/// Block number to query at a specific state.
		#[arg(long)]
		block: Option<String>,

		/// Attempt to decode the value as a specific type (e.g., "u64", "accoundid",
		/// "accountinfo").
		#[arg(long)]
		decode_as: Option<String>,

		/// Storage key parameter (e.g., AccountId for System::Account)
		#[arg(long, conflicts_with = "storage_key")]
		key: Option<String>,

		/// Type of the key component (e.g., "accountid", "u64").
		#[arg(long, requires("key"))]
		key_type: Option<String>,

		/// Force counting all entries even when --key is provided (useful for debugging)
		#[arg(long, conflicts_with = "storage_key")]
		count: bool,

		/// The full, final, hex-encoded storage key, as returned by `iterate` etc
		#[arg(long, conflicts_with_all = &["pallet", "name", "key", "count"])]
		storage_key: Option<String>,
	},
	/// List all storage items in a pallet.
	///
	/// Shows all available storage items with their metadata.
	List {
		/// The name of the pallet (e.g., "System")
		#[arg(long)]
		pallet: String,

		/// Show only storage item names (no documentation)
		#[arg(long)]
		names_only: bool,
	},
	/// List all pallets that have storage items.
	///
	/// Shows all pallets with storage and optionally counts.
	ListPallets {
		/// Show counts of storage items per pallet
		#[arg(long)]
		with_counts: bool,
	},
	/// Show storage statistics and count information.
	///
	/// Displays statistics about storage usage.
	Stats {
		/// The name of the pallet (optional, shows all if not specified)
		#[arg(long)]
		pallet: Option<String>,

		/// Show detailed statistics
		#[arg(long)]
		detailed: bool,
	},
	/// Iterate through storage map entries.
	///
	/// Useful for exploring storage maps and their contents.
	Iterate {
		/// The name of the pallet (e.g., "System")
		#[arg(long)]
		pallet: String,

		/// The name of the storage item (e.g., "Account")
		#[arg(long)]
		name: String,

		/// Maximum number of entries to show (use 0 to just count)
		#[arg(long, default_value = "10")]
		limit: u32,

		/// Attempt to decode values as a specific type
		#[arg(long)]
		decode_as: Option<String>,

		/// Block number or hash to query (optional, uses latest)
		#[arg(long)]
		block: Option<String>,
	},
}

/// Get block hash from block number or parse existing hash
pub async fn resolve_block_hash(
	quantus_client: &crate::chain::client::QuantusClient,
	block_identifier: &str,
) -> crate::error::Result<subxt::utils::H256> {
	if block_identifier.starts_with("0x") {
		// It's already a hash, parse it
		subxt::utils::H256::from_str(block_identifier)
			.map_err(|e| QuantusError::Generic(format!("Invalid block hash format: {e}")))
	} else {
		// It's a block number, convert to hash
		let block_number = block_identifier.parse::<u32>().map_err(|e| {
			QuantusError::Generic(format!("Invalid block number '{block_identifier}': {e}"))
		})?;

		log_verbose!("🔍 Converting block number {} to hash...", block_number);

		use jsonrpsee::core::client::ClientT;
		let block_hash: subxt::utils::H256 = quantus_client
			.rpc_client()
			.request::<subxt::utils::H256, [u32; 1]>("chain_getBlockHash", [block_number])
			.await
			.map_err(|e| {
				QuantusError::NetworkError(format!(
					"Failed to fetch block hash for block {block_number}: {e:?}"
				))
			})?;

		log_verbose!("📦 Block {} hash: {:?}", block_number, block_hash);
		Ok(block_hash)
	}
}

/// Get raw storage value by key
pub async fn get_storage_raw(
	quantus_client: &crate::chain::client::QuantusClient,
	key: Vec<u8>,
) -> crate::error::Result<Option<Vec<u8>>> {
	// Get the latest block hash to read from the latest state (not finalized)
	let latest_block_hash = quantus_client.get_latest_block().await?;

	let storage_at = quantus_client.client().storage().at(latest_block_hash);

	let result = storage_at.fetch_raw(key).await?;

	Ok(result)
}

/// Get raw storage value by key at specific block
pub async fn get_storage_raw_at_block(
	quantus_client: &crate::chain::client::QuantusClient,
	key: Vec<u8>,
	block_hash: subxt::utils::H256,
) -> crate::error::Result<Option<Vec<u8>>> {
	log_verbose!("🔍 Querying storage at block: {:?}", block_hash);

	let storage_at = quantus_client.client().storage().at(block_hash);

	let result = storage_at.fetch_raw(key).await?;

	Ok(result)
}

/// List all storage items in a pallet
pub async fn list_storage_items(
	quantus_client: &crate::chain::client::QuantusClient,
	pallet_name: &str,
	names_only: bool,
) -> crate::error::Result<()> {
	log_print!("📋 Listing storage items for pallet: {}", pallet_name.bright_green());

	// Validate pallet exists
	validate_pallet_exists(quantus_client.client(), pallet_name)?;

	let metadata = quantus_client.client().metadata();
	let pallet = metadata.pallet_by_name(pallet_name).unwrap();

	if let Some(storage_metadata) = pallet.storage() {
		let entries = storage_metadata.entries();
		log_print!("Found {} storage items: \n", entries.len());

		for (index, entry) in entries.iter().enumerate() {
			log_print!(
				"{}. {}",
				(index + 1).to_string().bright_yellow(),
				entry.name().bright_cyan()
			);

			if !names_only {
				log_print!("   Type: {:?}", entry.entry_type());
				if !entry.docs().is_empty() {
					log_print!("   Docs: {}", entry.docs().join(" ").dimmed());
				}
				log_print!("");
			}
		}
	} else {
		log_print!("❌ Pallet '{}' has no storage items.", pallet_name.bright_red());
	}

	Ok(())
}

/// List all pallets with storage
pub async fn list_pallets_with_storage(
	quantus_client: &crate::chain::client::QuantusClient,
	with_counts: bool,
) -> crate::error::Result<()> {
	log_print!("🏛️  Listing all pallets with storage:");
	log_print!("");

	let metadata = quantus_client.client().metadata();
	let pallets: Vec<_> = metadata.pallets().collect();

	let mut storage_pallets = BTreeMap::new();

	for pallet in pallets {
		if let Some(storage_metadata) = pallet.storage() {
			let entry_count = storage_metadata.entries().len();
			storage_pallets.insert(pallet.name(), entry_count);
		}
	}

	if storage_pallets.is_empty() {
		log_print!("❌ No pallets with storage found.");
		return Ok(());
	}

	for (index, (pallet_name, count)) in storage_pallets.iter().enumerate() {
		if with_counts {
			log_print!(
				"{}. {} ({} items)",
				(index + 1).to_string().bright_yellow(),
				pallet_name.bright_green(),
				count.to_string().bright_blue()
			);
		} else {
			log_print!(
				"{}. {}",
				(index + 1).to_string().bright_yellow(),
				pallet_name.bright_green()
			);
		}
	}

	log_print!("");
	log_print!("Total: {} pallets with storage", storage_pallets.len().to_string().bright_green());

	Ok(())
}

/// Show storage statistics
pub async fn show_storage_stats(
	quantus_client: &crate::chain::client::QuantusClient,
	pallet_name: Option<String>,
	detailed: bool,
) -> crate::error::Result<()> {
	log_print!("📊 Storage size statistics: \n");

	let metadata = quantus_client.client().metadata();

	if let Some(pallet) = pallet_name {
		// Show stats for specific pallet
		validate_pallet_exists(quantus_client.client(), &pallet)?;
		let pallet_meta = metadata.pallet_by_name(&pallet).unwrap();

		if let Some(storage_metadata) = pallet_meta.storage() {
			let entries = storage_metadata.entries();
			log_print!("Pallet: {}", pallet.bright_green());
			log_print!("Storage items: {}", entries.len().to_string().bright_blue());

			if detailed {
				log_print!("");
				log_print!("Items:");
				for (index, entry) in entries.iter().enumerate() {
					log_print!(
						"  {}. {} - {:?}",
						(index + 1).to_string().dimmed(),
						entry.name().bright_cyan(),
						entry.entry_type()
					);
				}
			}
		} else {
			log_print!("❌ Pallet '{}' has no storage items.", pallet.bright_red());
		}
	} else {
		// Show global stats
		let pallets: Vec<_> = metadata.pallets().collect();
		let mut total_storage_items = 0;
		let mut pallets_with_storage = 0;

		let mut pallet_stats = Vec::new();

		for pallet in pallets {
			if let Some(storage_metadata) = pallet.storage() {
				let entry_count = storage_metadata.entries().len();
				total_storage_items += entry_count;
				pallets_with_storage += 1;
				pallet_stats.push((pallet.name(), entry_count));
			}
		}

		log_print!("Total pallets: {}", metadata.pallets().len().to_string().bright_blue());
		log_print!("Pallets with storage: {}", pallets_with_storage.to_string().bright_green());
		log_print!("Total storage items: {}", total_storage_items.to_string().bright_yellow());

		if detailed && !pallet_stats.is_empty() {
			log_print!("");
			log_print!("Per-pallet breakdown:");

			// Sort by storage count (descending)
			pallet_stats.sort_by_key(|k| std::cmp::Reverse(k.1));

			for (pallet_name, count) in pallet_stats {
				log_print!(
					"  {} - {} items",
					pallet_name.bright_cyan(),
					count.to_string().bright_blue()
				);
			}
		}
	}

	Ok(())
}

/// Count storage entries using RPC calls with pagination
pub async fn count_storage_entries(
	quantus_client: &crate::chain::client::QuantusClient,
	pallet_name: &str,
	storage_name: &str,
	block_hash: subxt::utils::H256,
) -> crate::error::Result<u32> {
	// Construct storage key prefix for the storage item
	let mut prefix = twox_128(pallet_name.as_bytes()).to_vec();
	prefix.extend(&twox_128(storage_name.as_bytes()));

	log_verbose!("🔑 Storage prefix for counting: 0x{}", hex::encode(&prefix));

	use jsonrpsee::core::client::ClientT;

	let block_hash_str = format!("{block_hash:#x}");
	let prefix_hex = format!("0x{}", hex::encode(&prefix));
	let page_size = 1000u32; // Max allowed per request
	let mut total_count = 0u32;
	let mut start_key: Option<String> = None;

	loop {
		// Use state_getKeysPaged RPC call to get keys with the prefix
		let keys: Vec<String> = quantus_client
			.rpc_client()
			.request::<Vec<String>, (String, u32, Option<String>, Option<String>)>(
				"state_getKeysPaged",
				(
					prefix_hex.clone(),           // prefix
					page_size,                    // count
					start_key.clone(),            // start_key for pagination
					Some(block_hash_str.clone()), // at block
				),
			)
			.await
			.map_err(|e| {
				QuantusError::NetworkError(format!(
					"Failed to fetch storage keys at block {block_hash:?}: {e:?}"
				))
			})?;

		let keys_count = keys.len() as u32;
		total_count += keys_count;

		log_verbose!("📊 Fetched {} keys (total: {})", keys_count, total_count);

		// If we got less than page_size keys, we're done
		if keys_count < page_size {
			break;
		}

		// Set start_key to the last key for next iteration
		start_key = keys.last().cloned();
		if start_key.is_none() {
			break;
		}
	}

	Ok(total_count)
}

/// Iterate through storage map entries with real RPC calls
pub async fn iterate_storage_entries(
	quantus_client: &crate::chain::client::QuantusClient,
	pallet_name: &str,
	storage_name: &str,
	limit: u32,
	decode_as: Option<String>,
	block_identifier: Option<String>,
) -> crate::error::Result<()> {
	log_print!(
		"🔄 Iterating storage {}::{} (limit: {})",
		pallet_name.bright_green(),
		storage_name.bright_cyan(),
		limit.to_string().bright_yellow()
	);

	// Validate pallet exists
	validate_pallet_exists(quantus_client.client(), pallet_name)?;

	// Determine block hash to use
	let block_hash = if let Some(block_id) = block_identifier {
		resolve_block_hash(quantus_client, &block_id).await?
	} else {
		quantus_client.get_latest_block().await?
	};

	log_verbose!("📦 Using block: {:?}", block_hash);

	// Try to get storage metadata to show what type of storage this is
	let metadata = quantus_client.client().metadata();
	let pallet = metadata.pallet_by_name(pallet_name).unwrap();

	if let Some(storage_metadata) = pallet.storage() {
		if let Some(entry) = storage_metadata.entry_by_name(storage_name) {
			log_print!("📝 Storage type: {:?}", entry.entry_type());
			if !entry.docs().is_empty() {
				log_print!("📖 Docs: {}", entry.docs().join(" ").dimmed());
			}
		}
	}

	// Count total entries
	log_print!("🔢 Counting storage entries...");
	let total_count =
		count_storage_entries(quantus_client, pallet_name, storage_name, block_hash).await?;

	log_success!(
		"📊 Total entries in {}::{}: {}",
		pallet_name.bright_green(),
		storage_name.bright_cyan(),
		total_count.to_string().bright_yellow()
	);

	// If limit is 0, just show count
	if limit == 0 {
		return Ok(());
	}

	// Construct storage key prefix for the storage item
	let mut prefix = twox_128(pallet_name.as_bytes()).to_vec();
	prefix.extend(&twox_128(storage_name.as_bytes()));

	log_verbose!("🔑 Storage prefix: 0x{}", hex::encode(&prefix));

	// Use RPC to get keys with pagination
	use jsonrpsee::core::client::ClientT;

	let block_hash_str = format!("{block_hash:#x}");
	let keys: Vec<String> = quantus_client
		.rpc_client()
		.request::<Vec<String>, (String, u32, Option<String>, Option<String>)>(
			"state_getKeysPaged",
			(
				format!("0x{}", hex::encode(&prefix)),
				limit,                // limit entries
				None,                 // start_key
				Some(block_hash_str), // at block
			),
		)
		.await
		.map_err(|e| {
			QuantusError::NetworkError(format!(
				"Failed to fetch storage keys at block {block_hash:?}: {e:?}"
			))
		})?;

	if keys.is_empty() {
		log_print!("❌ No entries found.");
		return Ok(());
	}

	log_print!("📋 First {} entries:", keys.len().min(limit as usize));
	log_print!("");

	// Show first few keys and optionally their values
	for (index, key) in keys.iter().take(limit as usize).enumerate() {
		log_print!("{}. Key: {}", (index + 1).to_string().bright_yellow(), key.dimmed());

		// Optionally fetch and decode values (only for first few to avoid spam)
		if index < 3 && decode_as.is_some() {
			if let Ok(key_bytes) = hex::decode(key.strip_prefix("0x").unwrap_or(key)) {
				if let Ok(Some(value_bytes)) =
					get_storage_raw_at_block(quantus_client, key_bytes, block_hash).await
				{
					if let Some(ref decode_type) = decode_as {
						match decode_storage_value(&value_bytes, decode_type) {
							Ok(decoded_value) => {
								log_print!("   Value: {}", decoded_value.bright_green())
							},
							Err(_) => log_print!(
								"   Value: 0x{} (raw)",
								hex::encode(&value_bytes).dimmed()
							),
						}
					}
				}
			}
		}
	}

	if total_count > limit {
		log_print!("");
		log_print!(
			"... and {} more entries (use --limit 0 to just count)",
			(total_count - limit).to_string().bright_blue()
		);
	}

	Ok(())
}

/// Decode storage value based on type
fn decode_storage_value(value_bytes: &[u8], type_str: &str) -> crate::error::Result<String> {
	match type_str.to_lowercase().as_str() {
		"u32" => match u32::decode(&mut &value_bytes[..]) {
			Ok(decoded_value) => Ok(decoded_value.to_string()),
			Err(e) => Err(QuantusError::Generic(format!("Failed to decode as u32: {e}"))),
		},
		"u64" | "moment" => match u64::decode(&mut &value_bytes[..]) {
			Ok(decoded_value) => Ok(decoded_value.to_string()),
			Err(e) => Err(QuantusError::Generic(format!("Failed to decode as u64: {e}"))),
		},
		"u128" | "balance" => match u128::decode(&mut &value_bytes[..]) {
			Ok(decoded_value) => Ok(decoded_value.to_string()),
			Err(e) => Err(QuantusError::Generic(format!("Failed to decode as u128: {e}"))),
		},
		"accountid" | "accountid32" => match AccountId32::decode(&mut &value_bytes[..]) {
			Ok(account_id) => Ok(account_id.to_quantus_ss58()),
			Err(e) => Err(QuantusError::Generic(format!("Failed to decode as AccountId32: {e}"))),
		},
		"accountinfo" => match AccountInfo::decode(&mut &value_bytes[..]) {
			Ok(account_info) => Ok(format!("{account_info:#?}")),
			Err(e) => Err(QuantusError::Generic(format!("Failed to decode as AccountInfo: {e}"))),
		},
		_ => Err(QuantusError::Generic(format!(
			"Unsupported type for decoding: {type_str}. Supported types: u32, u64, moment, u128, balance, accountid, accountinfo"
		))),
	}
}

/// Get storage by a full, hex-encoded storage key.
async fn get_storage_by_storage_key(
	quantus_client: &crate::chain::client::QuantusClient,
	storage_key: String,
	block: Option<String>,
	decode_as: Option<String>,
) -> crate::error::Result<()> {
	log_print!("🗄️  Storage");

	let encoded_storage_key = encode_storage_key(&storage_key, "raw")?;

	let result = if let Some(block_id) = block {
		let block_hash = resolve_block_hash(quantus_client, &block_id).await?;
		get_storage_raw_at_block(quantus_client, encoded_storage_key, block_hash).await?
	} else {
		get_storage_raw(quantus_client, encoded_storage_key).await?
	};

	if let Some(value_bytes) = result {
		log_success!("Raw Value: 0x{}", hex::encode(&value_bytes).bright_yellow());
		if let Some(type_str) = decode_as {
			log_print!("Attempting to decode as {}...", type_str.bright_cyan());
			match decode_storage_value(&value_bytes, &type_str) {
				Ok(decoded_value) => {
					log_success!("Decoded Value: {}", decoded_value.bright_green())
				},
				Err(e) => log_error!("{}", e),
			}
		}
	} else {
		log_print!("{}", "No value found at this storage location.".dimmed());
	}

	Ok(())
}

/// Get storage by providing its pallet, name, and optional key component.
async fn get_storage_by_parts(
	quantus_client: &crate::chain::client::QuantusClient,
	pallet: String,
	name: String,
	key: Option<String>,
	key_type: Option<String>,
	block: Option<String>,
	decode_as: Option<String>,
	count: bool,
) -> crate::error::Result<()> {
	if let Some(block_value) = &block {
		log_print!(
			"🔎 Getting storage for {}::{} at block {}",
			pallet.bright_green(),
			name.bright_cyan(),
			block_value.bright_yellow()
		);
	} else {
		log_print!(
			"🔎 Getting storage for {}::{} (latest block)",
			pallet.bright_green(),
			name.bright_cyan()
		);
	}

	if let Some(key_value) = &key {
		log_print!("🔑 With key: {}", key_value.bright_yellow());
	}

	validate_pallet_exists(quantus_client.client(), &pallet)?;

	let block_hash = if let Some(block_id) = &block {
		resolve_block_hash(quantus_client, block_id).await?
	} else {
		quantus_client.get_latest_block().await?
	};

	let entry_count = count_storage_entries(quantus_client, &pallet, &name, block_hash).await?;
	let is_storage_value = entry_count == 1;

	let should_count = count || (key.is_none() && !is_storage_value);

	if should_count {
		log_print!("🔢 Counting all entries in {}::{}", pallet.bright_green(), name.bright_cyan());

		let block_display = if let Some(ref block_id) = block {
			format!(" at block {}", block_id.bright_yellow())
		} else {
			" (latest)".to_string()
		};

		log_success!(
			"👥 Total entries{}: {}",
			block_display,
			entry_count.to_string().bright_green().bold()
		);
	} else {
		let mut storage_key = twox_128(pallet.as_bytes()).to_vec();
		storage_key.extend(&twox_128(name.as_bytes()));

		if let Some(key_value) = &key {
			if let Some(key_type_str) = &key_type {
				let key_bytes = encode_storage_key(key_value, key_type_str)?;
				storage_key.extend(key_bytes);
			} else {
				log_error!("Key type (--key-type) is required when using --key parameter");
				return Ok(());
			}
		} else if !is_storage_value {
			log_print!("🔢 This is a storage map with {} entries. Use --key to get a specific value or omit --key to count all entries.", entry_count);
			return Ok(());
		}

		let result = get_storage_raw_at_block(quantus_client, storage_key, block_hash).await?;

		if let Some(value_bytes) = result {
			log_success!("Raw Value: 0x{}", hex::encode(&value_bytes).bright_yellow());

			if let Some(type_str) = decode_as {
				log_print!("Attempting to decode as {}...", type_str.bright_cyan());
				match decode_storage_value(&value_bytes, &type_str) {
					Ok(decoded_value) => {
						log_success!("Decoded Value: {}", decoded_value.bright_green())
					},
					Err(e) => log_error!("{}", e),
				}
			}
		} else {
			log_print!("{}", "No value found at this storage location.".dimmed());
		}
	}

	Ok(())
}

/// Handle storage subxt commands
pub async fn handle_storage_command(
	command: StorageCommands,
	node_url: &str,
	_execution_mode: crate::cli::common::ExecutionMode,
) -> crate::error::Result<()> {
	log_print!("🗄️  Storage");

	let quantus_client = crate::chain::client::QuantusClient::new(node_url).await?;

	match command {
		StorageCommands::Get {
			pallet,
			name,
			block,
			decode_as,
			key,
			key_type,
			count,
			storage_key,
		} => {
			if let Some(s_key) = storage_key {
				get_storage_by_storage_key(&quantus_client, s_key, block, decode_as).await
			} else {
				// Clap ensures that pallet and name are present if `storage_key` is None
				get_storage_by_parts(
					&quantus_client,
					pallet.unwrap(),
					name.unwrap(),
					key,
					key_type,
					block,
					decode_as,
					count,
				)
				.await
			}
		},
		StorageCommands::List { pallet, names_only } =>
			list_storage_items(&quantus_client, &pallet, names_only).await,
		StorageCommands::ListPallets { with_counts } =>
			list_pallets_with_storage(&quantus_client, with_counts).await,
		StorageCommands::Stats { pallet, detailed } =>
			show_storage_stats(&quantus_client, pallet, detailed).await,
		StorageCommands::Iterate { pallet, name, limit, decode_as, block } =>
			iterate_storage_entries(&quantus_client, &pallet, &name, limit, decode_as, block).await,
	}
}

/// Encode storage key parameter based on type
fn encode_storage_key(key_value: &str, key_type: &str) -> crate::error::Result<Vec<u8>> {
	use codec::Encode;
	use sp_core::crypto::{AccountId32 as SpAccountId32, Ss58Codec};

	match key_type.to_lowercase().as_str() {
		"accountid" | "accountid32" => {
			let account_id = SpAccountId32::from_ss58check(key_value).map_err(|e| {
				crate::error::QuantusError::Generic(format!("Invalid AccountId: {e:?}"))
			})?;
			Ok(account_id.encode())
		},
		"u64" => {
			let value = key_value
				.parse::<u64>()
				.map_err(|e| crate::error::QuantusError::Generic(format!("Invalid u64: {e}")))?;
			Ok(value.encode())
		},
		"u128" => {
			let value = key_value
				.parse::<u128>()
				.map_err(|e| crate::error::QuantusError::Generic(format!("Invalid u128: {e}")))?;
			Ok(value.encode())
		},
		"u32" => {
			let value = key_value
				.parse::<u32>()
				.map_err(|e| crate::error::QuantusError::Generic(format!("Invalid u32: {e}")))?;
			Ok(value.encode())
		},
		"hex" | "raw" => {
			// For hex/raw keys, decode the hex string directly
			let value_hex = key_value.strip_prefix("0x").unwrap_or(key_value);
			hex::decode(value_hex)
				.map_err(|e| crate::error::QuantusError::Generic(format!("Invalid hex value: {e}")))
		},
		_ => Err(crate::error::QuantusError::Generic(format!(
			"Unsupported key type: {key_type}. Supported types: accountid, u64, u128, u32, hex, raw"
		))),
	}
}