-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathrpc.rs
More file actions
2300 lines (2185 loc) · 81.1 KB
/
Copy pathrpc.rs
File metadata and controls
2300 lines (2185 loc) · 81.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Client RPC queries
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fs::File;
use std::io::{self, Write};
use std::iter::Iterator;
use std::path::PathBuf;
use std::str::FromStr;
use borsh::{BorshDeserialize, BorshSerialize};
use data_encoding::HEXLOWER;
use itertools::Either;
use masp_primitives::asset_type::AssetType;
use masp_primitives::merkle_tree::MerklePath;
use masp_primitives::sapling::{Node, ViewingKey};
use masp_primitives::zip32::ExtendedFullViewingKey;
use namada::core::types::transaction::governance::ProposalType;
use namada::ledger::events::Event;
use namada::ledger::governance::parameters::GovParams;
use namada::ledger::governance::storage as gov_storage;
use namada::ledger::masp::{
Conversions, MaspAmount, MaspChange, PinnedBalanceError, ShieldedContext,
ShieldedUtils,
};
use namada::ledger::native_vp::governance::utils::{self, Votes};
use namada::ledger::parameters::{storage as param_storage, EpochDuration};
use namada::ledger::pos::{
self, BondId, BondsAndUnbondsDetail, CommissionPair, PosParams, Slash,
};
use namada::ledger::queries::RPC;
use namada::ledger::rpc::{
enriched_bonds_and_unbonds, format_denominated_amount, query_epoch,
TxResponse,
};
use namada::ledger::storage::ConversionState;
use namada::ledger::wallet::{AddressVpType, Wallet};
use namada::proof_of_stake::types::{ValidatorState, WeightedValidator};
use namada::types::address::{masp, Address};
use namada::types::control_flow::ProceedOrElse;
use namada::types::governance::{
OfflineProposal, OfflineVote, ProposalVote, VotePower, VoteType,
};
use namada::types::hash::Hash;
use namada::types::key::*;
use namada::types::masp::{BalanceOwner, ExtendedViewingKey, PaymentAddress};
use namada::types::storage::{BlockHeight, BlockResults, Epoch, Key, KeySeg};
use namada::types::token::{Change, MaspDenom};
use namada::types::{storage, token};
use tokio::time::Instant;
use crate::cli::{self, args};
use crate::facade::tendermint::merkle::proof::Proof;
use crate::facade::tendermint_rpc::error::Error as TError;
use crate::prompt;
use crate::wallet::CliWalletUtils;
/// Query the status of a given transaction.
///
/// If a response is not delivered until `deadline`, we exit the cli with an
/// error.
pub async fn query_tx_status<C: namada::ledger::queries::Client + Sync>(
client: &C,
status: namada::ledger::rpc::TxEventQuery<'_>,
deadline: Instant,
) -> Event {
namada::ledger::rpc::query_tx_status(client, status, deadline)
.await
.proceed()
}
/// Query and print the epoch of the last committed block
pub async fn query_and_print_epoch<
C: namada::ledger::queries::Client + Sync,
>(
client: &C,
) -> Epoch {
let epoch = namada::ledger::rpc::query_epoch(client).await;
println!("Last committed epoch: {}", epoch);
epoch
}
/// Query the last committed block
pub async fn query_block<C: namada::ledger::queries::Client + Sync>(
client: &C,
) {
let block = namada::ledger::rpc::query_block(client).await;
match block {
Some(block) => {
println!(
"Last committed block ID: {}, height: {}, time: {}",
block.hash, block.height, block.time
);
}
None => {
println!("No block has been committed yet.");
}
}
}
/// Query the results of the last committed block
pub async fn query_results<C: namada::ledger::queries::Client + Sync>(
client: &C,
_args: args::Query,
) -> Vec<BlockResults> {
unwrap_client_response::<C, Vec<BlockResults>>(
RPC.shell().read_results(client).await,
)
}
/// Query the specified accepted transfers from the ledger
pub async fn query_transfers<
C: namada::ledger::queries::Client + Sync,
U: ShieldedUtils,
>(
client: &C,
wallet: &mut Wallet<CliWalletUtils>,
shielded: &mut ShieldedContext<U>,
args: args::QueryTransfers,
) {
let query_token = args.token;
let query_owner = args.owner.map_or_else(
|| Either::Right(wallet.get_addresses().into_values().collect()),
Either::Left,
);
let _ = shielded.load().await;
// Obtain the effects of all shielded and transparent transactions
let transfers = shielded
.query_tx_deltas(
client,
&query_owner,
&query_token,
&wallet.get_viewing_keys(),
)
.await;
// To facilitate lookups of human-readable token names
let vks = wallet.get_viewing_keys();
// To enable ExtendedFullViewingKeys to be displayed instead of ViewingKeys
let fvk_map: HashMap<_, _> = vks
.values()
.map(|fvk| (ExtendedFullViewingKey::from(*fvk).fvk.vk, fvk))
.collect();
// Now display historical shielded and transparent transactions
for ((height, idx), (epoch, tfer_delta, tx_delta)) in transfers {
// Check if this transfer pertains to the supplied owner
let mut relevant = match &query_owner {
Either::Left(BalanceOwner::FullViewingKey(fvk)) => tx_delta
.contains_key(&ExtendedFullViewingKey::from(*fvk).fvk.vk),
Either::Left(BalanceOwner::Address(owner)) => {
tfer_delta.contains_key(owner)
}
Either::Left(BalanceOwner::PaymentAddress(_owner)) => false,
Either::Right(_) => true,
};
// Realize and decode the shielded changes to enable relevance check
let mut shielded_accounts = HashMap::new();
for (acc, amt) in tx_delta {
// Realize the rewards that would have been attained upon the
// transaction's reception
let amt = shielded
.compute_exchanged_amount(
client,
amt,
epoch,
Conversions::new(),
)
.await
.0;
let dec = shielded.decode_amount(client, amt, epoch).await;
shielded_accounts.insert(acc, dec);
}
// Check if this transfer pertains to the supplied token
relevant &= match &query_token {
Some(token) => {
let check = |(tok, chg): (&Address, &Change)| {
tok == token && !chg.is_zero()
};
tfer_delta.values().cloned().any(
|MaspChange { ref asset, change }| check((asset, &change)),
) || shielded_accounts
.values()
.cloned()
.any(|x| x.iter().any(check))
}
None => true,
};
// Filter out those entries that do not satisfy user query
if !relevant {
continue;
}
println!("Height: {}, Index: {}, Transparent Transfer:", height, idx);
// Display the transparent changes first
for (account, MaspChange { ref asset, change }) in tfer_delta {
if account != masp() {
print!(" {}:", account);
let token_alias = wallet.lookup_alias(asset);
let sign = match change.cmp(&Change::zero()) {
Ordering::Greater => "+",
Ordering::Less => "-",
Ordering::Equal => "",
};
print!(
" {}{} {}",
sign,
format_denominated_amount(client, asset, change.into(),)
.await,
token_alias
);
}
println!();
}
// Then display the shielded changes afterwards
// TODO: turn this to a display impl
// (account, amt)
for (account, masp_change) in shielded_accounts {
if fvk_map.contains_key(&account) {
print!(" {}:", fvk_map[&account]);
for (token_addr, val) in masp_change {
let token_alias = wallet.lookup_alias(&token_addr);
let sign = match val.cmp(&Change::zero()) {
Ordering::Greater => "+",
Ordering::Less => "-",
Ordering::Equal => "",
};
print!(
" {}{} {}",
sign,
format_denominated_amount(
client,
&token_addr,
val.into(),
)
.await,
token_alias,
);
}
println!();
}
}
}
}
/// Query the raw bytes of given storage key
pub async fn query_raw_bytes<C: namada::ledger::queries::Client + Sync>(
client: &C,
args: args::QueryRawBytes,
) {
let response = unwrap_client_response::<C, _>(
RPC.shell()
.storage_value(client, None, None, false, &args.storage_key)
.await,
);
if !response.data.is_empty() {
println!("Found data: 0x{}", HEXLOWER.encode(&response.data));
} else {
println!("No data found for key {}", args.storage_key);
}
}
/// Query token balance(s)
pub async fn query_balance<
C: namada::ledger::queries::Client + Sync,
U: ShieldedUtils,
>(
client: &C,
wallet: &mut Wallet<CliWalletUtils>,
shielded: &mut ShieldedContext<U>,
args: args::QueryBalance,
) {
// Query the balances of shielded or transparent account types depending on
// the CLI arguments
match &args.owner {
Some(BalanceOwner::FullViewingKey(_viewing_key)) => {
query_shielded_balance(client, wallet, shielded, args).await
}
Some(BalanceOwner::Address(_owner)) => {
query_transparent_balance(client, wallet, args).await
}
Some(BalanceOwner::PaymentAddress(_owner)) => {
query_pinned_balance(client, wallet, shielded, args).await
}
None => {
// Print pinned balance
query_pinned_balance(client, wallet, shielded, args.clone()).await;
// Print shielded balance
query_shielded_balance(client, wallet, shielded, args.clone())
.await;
// Then print transparent balance
query_transparent_balance(client, wallet, args).await;
}
};
}
/// Query token balance(s)
pub async fn query_transparent_balance<
C: namada::ledger::queries::Client + Sync,
>(
client: &C,
wallet: &mut Wallet<CliWalletUtils>,
args: args::QueryBalance,
) {
let prefix = Key::from(
Address::Internal(namada::types::address::InternalAddress::Multitoken)
.to_db_key(),
);
let tokens = wallet.tokens_with_aliases();
match (args.token, args.owner) {
(Some(token), Some(owner)) => {
let balance_key =
token::balance_key(&token, &owner.address().unwrap());
let token_alias = wallet.lookup_alias(&token);
match query_storage_value::<C, token::Amount>(client, &balance_key)
.await
{
Some(balance) => {
let balance =
format_denominated_amount(client, &token, balance)
.await;
println!("{}: {}", token_alias, balance);
}
None => {
println!("No {} balance found for {}", token_alias, owner)
}
}
}
(None, Some(owner)) => {
let owner = owner.address().unwrap();
for (token_alias, token) in tokens {
let balance = get_token_balance(client, &token, &owner).await;
if !balance.is_zero() {
let balance =
format_denominated_amount(client, &token, balance)
.await;
println!("{}: {}", token_alias, balance);
}
}
}
(Some(token), None) => {
let prefix = token::balance_prefix(&token);
let balances =
query_storage_prefix::<C, token::Amount>(client, &prefix).await;
if let Some(balances) = balances {
print_balances(client, wallet, balances, Some(&token), None)
.await;
}
}
(None, None) => {
let balances =
query_storage_prefix::<C, token::Amount>(client, &prefix).await;
if let Some(balances) = balances {
print_balances(client, wallet, balances, None, None).await;
}
}
}
}
/// Query the token pinned balance(s)
pub async fn query_pinned_balance<
C: namada::ledger::queries::Client + Sync,
U: ShieldedUtils,
>(
client: &C,
wallet: &mut Wallet<CliWalletUtils>,
shielded: &mut ShieldedContext<U>,
args: args::QueryBalance,
) {
// Map addresses to token names
let tokens = wallet.get_addresses_with_vp_type(AddressVpType::Token);
let owners = if let Some(pa) = args.owner.and_then(|x| x.payment_address())
{
vec![pa]
} else {
wallet
.get_payment_addrs()
.into_values()
.filter(PaymentAddress::is_pinned)
.collect()
};
// Get the viewing keys with which to try note decryptions
let viewing_keys: Vec<ViewingKey> = wallet
.get_viewing_keys()
.values()
.map(|fvk| ExtendedFullViewingKey::from(*fvk).fvk.vk)
.collect();
let _ = shielded.load().await;
// Print the token balances by payment address
let pinned_error = Err(PinnedBalanceError::InvalidViewingKey);
for owner in owners {
let mut balance = pinned_error.clone();
// Find the viewing key that can recognize payments the current payment
// address
for vk in &viewing_keys {
balance = shielded
.compute_exchanged_pinned_balance(client, owner, vk)
.await;
if balance != pinned_error {
break;
}
}
// If a suitable viewing key was not found, then demand it from the user
if balance == pinned_error {
let vk_str = prompt!("Enter the viewing key for {}: ", owner);
let fvk = match ExtendedViewingKey::from_str(vk_str.trim()) {
Ok(fvk) => fvk,
_ => {
eprintln!("Invalid viewing key entered");
continue;
}
};
let vk = ExtendedFullViewingKey::from(fvk).fvk.vk;
// Use the given viewing key to decrypt pinned transaction data
balance = shielded
.compute_exchanged_pinned_balance(client, owner, &vk)
.await
}
// Now print out the received quantities according to CLI arguments
match (balance, args.token.as_ref()) {
(Err(PinnedBalanceError::InvalidViewingKey), _) => println!(
"Supplied viewing key cannot decode transactions to given \
payment address."
),
(Err(PinnedBalanceError::NoTransactionPinned), _) => {
println!("Payment address {} has not yet been consumed.", owner)
}
(Ok((balance, epoch)), Some(token)) => {
let token_alias = wallet.lookup_alias(token);
let total_balance = balance
.get(&(epoch, token.clone()))
.cloned()
.unwrap_or_default();
if total_balance.is_zero() {
println!(
"Payment address {} was consumed during epoch {}. \
Received no shielded {}",
owner, epoch, token_alias
);
} else {
let formatted = format_denominated_amount(
client,
token,
total_balance.into(),
)
.await;
println!(
"Payment address {} was consumed during epoch {}. \
Received {} {}",
owner, epoch, formatted, token_alias,
);
}
}
(Ok((balance, epoch)), None) => {
let mut found_any = false;
for ((_, token_addr), value) in balance
.iter()
.filter(|((token_epoch, _), _)| *token_epoch == epoch)
{
if !found_any {
println!(
"Payment address {} was consumed during epoch {}. \
Received:",
owner, epoch
);
found_any = true;
}
let formatted = format_denominated_amount(
client,
token_addr,
(*value).into(),
)
.await;
let token_alias = tokens
.get(token_addr)
.map(|a| a.to_string())
.unwrap_or_else(|| token_addr.to_string());
println!(" {}: {}", token_alias, formatted,);
}
if !found_any {
println!(
"Payment address {} was consumed during epoch {}. \
Received no shielded assets.",
owner, epoch
);
}
}
}
}
}
async fn print_balances<C: namada::ledger::queries::Client + Sync>(
client: &C,
wallet: &Wallet<CliWalletUtils>,
balances: impl Iterator<Item = (storage::Key, token::Amount)>,
token: Option<&Address>,
target: Option<&Address>,
) {
let stdout = io::stdout();
let mut w = stdout.lock();
let mut print_num = 0;
let mut print_token = None;
for (key, balance) in balances {
// Get the token, the owner, and the balance with the token and the
// owner
let (t, o, s) = match token::is_any_token_balance_key(&key) {
Some([tok, owner]) => (
tok.clone(),
owner.clone(),
format!(
": {}, owned by {}",
format_denominated_amount(client, tok, balance).await,
wallet.lookup_alias(owner)
),
),
None => continue,
};
// Get the token and the balance
let (t, s) = match (token, target) {
// the given token and the given target are the same as the
// retrieved ones
(Some(token), Some(target)) if t == *token && o == *target => {
(t, s)
}
// the given token is the same as the retrieved one
(Some(token), None) if t == *token => (t, s),
// the given target is the same as the retrieved one
(None, Some(target)) if o == *target => (t, s),
// no specified token or target
(None, None) => (t, s),
// otherwise, this balance will not be printed
_ => continue,
};
// Print the token if it isn't printed yet
match &print_token {
Some(token) if *token == t => {
// the token has been already printed
}
_ => {
let token_alias = wallet.lookup_alias(&t);
writeln!(w, "Token {}", token_alias).unwrap();
print_token = Some(t);
}
}
// Print the balance
writeln!(w, "{}", s).unwrap();
print_num += 1;
}
if print_num == 0 {
match (token, target) {
(Some(_), Some(target)) | (None, Some(target)) => writeln!(
w,
"No balances owned by {}",
wallet.lookup_alias(target)
)
.unwrap(),
(Some(token), None) => {
let token_alias = wallet.lookup_alias(token);
writeln!(w, "No balances for token {}", token_alias).unwrap()
}
(None, None) => writeln!(w, "No balances").unwrap(),
}
}
}
/// Query Proposals
pub async fn query_proposal<C: namada::ledger::queries::Client + Sync>(
client: &C,
args: args::QueryProposal,
) {
async fn print_proposal<C: namada::ledger::queries::Client + Sync>(
client: &C,
id: u64,
current_epoch: Epoch,
details: bool,
) -> Option<()> {
let author_key = gov_storage::get_author_key(id);
let start_epoch_key = gov_storage::get_voting_start_epoch_key(id);
let end_epoch_key = gov_storage::get_voting_end_epoch_key(id);
let proposal_type_key = gov_storage::get_proposal_type_key(id);
let author =
query_storage_value::<C, Address>(client, &author_key).await?;
let start_epoch =
query_storage_value::<C, Epoch>(client, &start_epoch_key).await?;
let end_epoch =
query_storage_value::<C, Epoch>(client, &end_epoch_key).await?;
let proposal_type =
query_storage_value::<C, ProposalType>(client, &proposal_type_key)
.await?;
if details {
let content_key = gov_storage::get_content_key(id);
let grace_epoch_key = gov_storage::get_grace_epoch_key(id);
let content = query_storage_value::<C, HashMap<String, String>>(
client,
&content_key,
)
.await?;
let grace_epoch =
query_storage_value::<C, Epoch>(client, &grace_epoch_key)
.await?;
println!("Proposal: {}", id);
println!("{:4}Type: {}", "", proposal_type);
println!("{:4}Author: {}", "", author);
println!("{:4}Content:", "");
for (key, value) in &content {
println!("{:8}{}: {}", "", key, value);
}
println!("{:4}Start Epoch: {}", "", start_epoch);
println!("{:4}End Epoch: {}", "", end_epoch);
println!("{:4}Grace Epoch: {}", "", grace_epoch);
let votes = get_proposal_votes(client, start_epoch, id).await;
let total_stake = get_total_staked_tokens(client, start_epoch)
.await
.try_into()
.unwrap();
if start_epoch > current_epoch {
println!("{:4}Status: pending", "");
} else if start_epoch <= current_epoch && current_epoch <= end_epoch
{
match utils::compute_tally(votes, total_stake, &proposal_type) {
Ok(partial_proposal_result) => {
println!(
"{:4}Yay votes: {}",
"", partial_proposal_result.total_yay_power
);
println!(
"{:4}Nay votes: {}",
"", partial_proposal_result.total_nay_power
);
println!("{:4}Status: on-going", "");
}
Err(msg) => {
eprintln!("Error in tally computation: {}", msg)
}
}
} else {
match utils::compute_tally(votes, total_stake, &proposal_type) {
Ok(proposal_result) => {
println!("{:4}Status: done", "");
println!("{:4}Result: {}", "", proposal_result);
}
Err(msg) => {
eprintln!("Error in tally computation: {}", msg)
}
}
}
} else {
println!("Proposal: {}", id);
println!("{:4}Type: {}", "", proposal_type);
println!("{:4}Author: {}", "", author);
println!("{:4}Start Epoch: {}", "", start_epoch);
println!("{:4}End Epoch: {}", "", end_epoch);
if start_epoch > current_epoch {
println!("{:4}Status: pending", "");
} else if start_epoch <= current_epoch && current_epoch <= end_epoch
{
println!("{:4}Status: on-going", "");
} else {
println!("{:4}Status: done", "");
}
}
Some(())
}
let current_epoch = query_and_print_epoch(client).await;
match args.proposal_id {
Some(id) => {
if print_proposal::<C>(client, id, current_epoch, true)
.await
.is_none()
{
eprintln!("No valid proposal was found with id {}", id)
}
}
None => {
let last_proposal_id_key = gov_storage::get_counter_key();
let last_proposal_id =
query_storage_value::<C, u64>(client, &last_proposal_id_key)
.await
.unwrap();
for id in 0..last_proposal_id {
if print_proposal::<C>(client, id, current_epoch, false)
.await
.is_none()
{
eprintln!("No valid proposal was found with id {}", id)
};
}
}
}
}
/// Query token shielded balance(s)
pub async fn query_shielded_balance<
C: namada::ledger::queries::Client + Sync,
U: ShieldedUtils,
>(
client: &C,
wallet: &mut Wallet<CliWalletUtils>,
shielded: &mut ShieldedContext<U>,
args: args::QueryBalance,
) {
// Used to control whether balances for all keys or a specific key are
// printed
let owner = args.owner.and_then(|x| x.full_viewing_key());
// Used to control whether conversions are automatically performed
let no_conversions = args.no_conversions;
// Viewing keys are used to query shielded balances. If a spending key is
// provided, then convert to a viewing key first.
let viewing_keys = match owner {
Some(viewing_key) => vec![viewing_key],
None => wallet.get_viewing_keys().values().copied().collect(),
};
let _ = shielded.load().await;
let fvks: Vec<_> = viewing_keys
.iter()
.map(|fvk| ExtendedFullViewingKey::from(*fvk).fvk.vk)
.collect();
shielded.fetch(client, &[], &fvks).await;
// Save the update state so that future fetches can be short-circuited
let _ = shielded.save().await;
// The epoch is required to identify timestamped tokens
let epoch = query_and_print_epoch(client).await;
// Map addresses to token names
let tokens = wallet.get_addresses_with_vp_type(AddressVpType::Token);
match (args.token, owner.is_some()) {
// Here the user wants to know the balance for a specific token
(Some(token), true) => {
// Query the multi-asset balance at the given spending key
let viewing_key =
ExtendedFullViewingKey::from(viewing_keys[0]).fvk.vk;
let balance: MaspAmount = if no_conversions {
shielded
.compute_shielded_balance(client, &viewing_key)
.await
.expect("context should contain viewing key")
} else {
shielded
.compute_exchanged_balance(client, &viewing_key, epoch)
.await
.expect("context should contain viewing key")
};
let token_alias = wallet.lookup_alias(&token);
let total_balance = balance
.get(&(epoch, token.clone()))
.cloned()
.unwrap_or_default();
if total_balance.is_zero() {
println!(
"No shielded {} balance found for given key",
token_alias
);
} else {
println!(
"{}: {}",
token_alias,
format_denominated_amount(
client,
&token,
token::Amount::from(total_balance)
)
.await
);
}
}
// Here the user wants to know the balance of all tokens across users
(None, false) => {
// Maps asset types to balances divided by viewing key
let mut balances = HashMap::new();
for fvk in viewing_keys {
// Query the multi-asset balance at the given spending key
let viewing_key = ExtendedFullViewingKey::from(fvk).fvk.vk;
let balance = if no_conversions {
shielded
.compute_shielded_balance(client, &viewing_key)
.await
.expect("context should contain viewing key")
} else {
shielded
.compute_exchanged_balance(client, &viewing_key, epoch)
.await
.expect("context should contain viewing key")
};
for (key, value) in balance.iter() {
if !balances.contains_key(key) {
balances.insert(key.clone(), Vec::new());
}
balances.get_mut(key).unwrap().push((fvk, *value));
}
}
// Print non-zero balances whose asset types can be decoded
// TODO Implement a function for this
let mut balance_map = HashMap::new();
for ((asset_epoch, token_addr), balances) in balances {
if asset_epoch == epoch {
// remove this from here, should not be making the
// hashtable creation any uglier
if balances.is_empty() {
println!(
"No shielded {} balance found for any wallet key",
&token_addr
);
}
for (fvk, value) in balances {
balance_map.insert((fvk, token_addr.clone()), value);
}
}
}
for ((fvk, token), token_balance) in balance_map {
// Only assets with the current timestamp count
let alias = tokens
.get(&token)
.map(|a| a.to_string())
.unwrap_or_else(|| token.to_string());
println!("Shielded Token {}:", alias);
let formatted = format_denominated_amount(
client,
&token,
token_balance.into(),
)
.await;
println!(" {}, owned by {}", formatted, fvk);
}
}
// Here the user wants to know the balance for a specific token across
// users
(Some(token), false) => {
// Compute the unique asset identifier from the token address
let token = token;
let _asset_type = AssetType::new(
(token.clone(), epoch.0)
.try_to_vec()
.expect("token addresses should serialize")
.as_ref(),
)
.unwrap();
let token_alias = wallet.lookup_alias(&token);
println!("Shielded Token {}:", token_alias);
let mut found_any = false;
let token_alias = wallet.lookup_alias(&token);
println!("Shielded Token {}:", token_alias,);
for fvk in viewing_keys {
// Query the multi-asset balance at the given spending key
let viewing_key = ExtendedFullViewingKey::from(fvk).fvk.vk;
let balance = if no_conversions {
shielded
.compute_shielded_balance(client, &viewing_key)
.await
.expect("context should contain viewing key")
} else {
shielded
.compute_exchanged_balance(client, &viewing_key, epoch)
.await
.expect("context should contain viewing key")
};
for ((_, address), val) in balance.iter() {
if !val.is_zero() {
found_any = true;
}
let formatted = format_denominated_amount(
client,
address,
(*val).into(),
)
.await;
println!(" {}, owned by {}", formatted, fvk);
}
}
if !found_any {
println!(
"No shielded {} balance found for any wallet key",
token_alias,
);
}
}
// Here the user wants to know all possible token balances for a key
(None, true) => {
// Query the multi-asset balance at the given spending key
let viewing_key =
ExtendedFullViewingKey::from(viewing_keys[0]).fvk.vk;
if no_conversions {
let balance = shielded
.compute_shielded_balance(client, &viewing_key)
.await
.expect("context should contain viewing key");
// Print balances by human-readable token names
print_decoded_balance_with_epoch(client, wallet, balance).await;
} else {
let balance = shielded
.compute_exchanged_balance(client, &viewing_key, epoch)
.await
.expect("context should contain viewing key");
// Print balances by human-readable token names
print_decoded_balance(client, wallet, balance, epoch).await;
}
}
}
}
pub async fn print_decoded_balance<
C: namada::ledger::queries::Client + Sync,
>(
client: &C,
wallet: &mut Wallet<CliWalletUtils>,
decoded_balance: MaspAmount,
epoch: Epoch,
) {
if decoded_balance.is_empty() {
println!("No shielded balance found for given key");
} else {
for ((_, token_addr), amount) in decoded_balance
.iter()
.filter(|((token_epoch, _), _)| *token_epoch == epoch)
{
println!(
"{} : {}",
wallet.lookup_alias(token_addr),
format_denominated_amount(client, token_addr, (*amount).into())
.await,
);
}
}
}
pub async fn print_decoded_balance_with_epoch<
C: namada::ledger::queries::Client + Sync,
>(
client: &C,
wallet: &mut Wallet<CliWalletUtils>,
decoded_balance: MaspAmount,
) {
let tokens = wallet.get_addresses_with_vp_type(AddressVpType::Token);
if decoded_balance.is_empty() {
println!("No shielded balance found for given key");
}
for ((epoch, token_addr), value) in decoded_balance.iter() {
let asset_value = (*value).into();
let alias = tokens
.get(token_addr)
.map(|a| a.to_string())
.unwrap_or_else(|| token_addr.to_string());
println!(
"{} | {} : {}",
alias,
epoch,
format_denominated_amount(client, token_addr, asset_value).await,
);
}
}
/// Query token amount of owner.
pub async fn get_token_balance<C: namada::ledger::queries::Client + Sync>(
client: &C,
token: &Address,
owner: &Address,
) -> token::Amount {
namada::ledger::rpc::get_token_balance(client, token, owner).await
}
pub async fn query_proposal_result<
C: namada::ledger::queries::Client + Sync,
>(
client: &C,
args: args::QueryProposalResult,
) {
let current_epoch = query_epoch(client).await;
match args.proposal_id {
Some(id) => {
let end_epoch_key = gov_storage::get_voting_end_epoch_key(id);
let end_epoch =
query_storage_value::<C, Epoch>(client, &end_epoch_key).await;
match end_epoch {
Some(end_epoch) => {
if current_epoch > end_epoch {
let votes =
get_proposal_votes(client, end_epoch, id).await;
let proposal_type_key =
gov_storage::get_proposal_type_key(id);
let proposal_type = query_storage_value::<
C,
ProposalType,
>(
client, &proposal_type_key
)
.await