-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathquery.rs
More file actions
922 lines (789 loc) · 32.3 KB
/
query.rs
File metadata and controls
922 lines (789 loc) · 32.3 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
use gloo_utils::format::JsValueSerdeExt;
use js_sys::Uint8Array;
use namada_sdk::address::Address;
use namada_sdk::borsh::BorshSerialize;
use namada_sdk::collections::{HashMap, HashSet};
use namada_sdk::eth_bridge::bridge_pool::query_signed_bridge_pool;
use namada_sdk::eth_bridge_pool::TransferToEthereum;
use namada_sdk::governance::storage::keys as governance_storage;
use namada_sdk::governance::utils::{
compute_proposal_result, ProposalVotes, TallyResult, TallyType, VotePower,
};
use namada_sdk::governance::{ProposalType, ProposalVote};
use namada_sdk::hash::Hash;
use namada_sdk::masp::shielded_wallet::ShieldedApi;
use namada_sdk::masp::utils::MaspClient as NamadaMaspClient;
use namada_sdk::masp::utils::RetryStrategy;
use namada_sdk::masp::{IndexerMaspClient, LedgerMaspClient, LinearBackoffSleepMaspClient};
use namada_sdk::masp::{ShieldedContext, ShieldedSyncConfig};
use namada_sdk::masp_primitives::asset_type::AssetType;
use namada_sdk::masp_primitives::sapling::ViewingKey;
use namada_sdk::masp_primitives::transaction::components::ValueSum;
use namada_sdk::masp_primitives::zip32::ExtendedFullViewingKey;
use namada_sdk::parameters::storage;
use namada_sdk::proof_of_stake::Epoch;
use namada_sdk::queries::RPC;
use namada_sdk::rpc::{
self, get_public_key_at, get_token_balance, get_total_staked_tokens, is_steward, query_epoch,
query_masp_epoch, query_masp_reward_tokens, query_native_token, query_proposal_by_id,
query_proposal_votes, query_storage_value,
};
use namada_sdk::state::Key;
use namada_sdk::token;
use namada_sdk::tx::{
TX_BOND_WASM, TX_CLAIM_REWARDS_WASM, TX_IBC_WASM, TX_REDELEGATE_WASM, TX_REVEAL_PK,
TX_TRANSFER_WASM, TX_UNBOND_WASM, TX_VOTE_PROPOSAL, TX_WITHDRAW_WASM,
};
use namada_sdk::uint::I256;
use namada_sdk::wallet::DatedKeypair;
use namada_sdk::ExtendedViewingKey;
use std::collections::BTreeMap;
use std::str::FromStr;
use std::time::Duration;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsError;
use crate::rpc_client::HttpClient;
use crate::sdk::{
io::WebIo,
masp::{sync, JSShieldedUtils},
};
use crate::types::masp::DatedViewingKey;
use crate::types::query::{MaspTokenRewardData, ProposalInfo, WasmHash};
use crate::utils::{set_panic_hook, to_js_result};
/// Progress bar names
pub const SDK_SCANNED_PROGRESS_BAR: &str = "namada_sdk::progress_bar::scanned";
pub const SDK_FETCHED_PROGRESS_BAR: &str = "namada_sdk::progress_bar::fetched";
pub const SDK_APPLIED_PROGRESS_BAR: &str = "namada_sdk::progress_bar::applied";
#[wasm_bindgen]
pub struct ProgressBarNames {}
#[wasm_bindgen]
impl ProgressBarNames {
#[allow(non_snake_case)]
#[wasm_bindgen(getter)]
pub fn Scanned() -> String {
SDK_SCANNED_PROGRESS_BAR.to_string()
}
#[allow(non_snake_case)]
#[wasm_bindgen(getter)]
pub fn Fetched() -> String {
SDK_FETCHED_PROGRESS_BAR.to_string()
}
#[allow(non_snake_case)]
#[wasm_bindgen(getter)]
pub fn Applied() -> String {
SDK_APPLIED_PROGRESS_BAR.to_string()
}
}
enum MaspClient {
Ledger(LinearBackoffSleepMaspClient<LedgerMaspClient<HttpClient>>),
Indexer(LinearBackoffSleepMaspClient<IndexerMaspClient>),
}
#[wasm_bindgen]
/// Represents an API for querying the ledger
pub struct Query {
client: HttpClient,
masp_client: MaspClient,
}
#[wasm_bindgen]
impl Query {
#[wasm_bindgen(constructor)]
pub fn new(url: String, masp_url: Option<String>) -> Query {
set_panic_hook();
let client = HttpClient::new(url);
let masp_client = if let Some(url) = masp_url {
let client = reqwest::Client::builder().build().unwrap();
// TODO: for now we just concatenate the v1 api path
let url = reqwest::Url::parse(&format!("{}/api/v1", url)).unwrap();
MaspClient::Indexer(LinearBackoffSleepMaspClient::new(
IndexerMaspClient::new(client, url, true, 100),
Duration::from_millis(5),
))
} else {
MaspClient::Ledger(LinearBackoffSleepMaspClient::new(
LedgerMaspClient::new(
client.clone(),
// Using one does not break the progress indicators
1,
),
Duration::from_millis(5),
))
};
Query {
client,
masp_client,
}
}
/// Gets current epoch
///
/// # Errors
///
/// Returns an error if the RPC call fails
pub async fn query_epoch(&self) -> Result<u64, JsError> {
let epoch = RPC.shell().epoch(&self.client).await?;
Ok(epoch.0)
}
/// Gets all active validator addresses
///
/// # Errors
///
/// Returns an error if the RPC call fails
pub async fn query_all_validator_addresses(&self) -> Result<JsValue, JsError> {
let validator_addresses = RPC
.vp()
.pos()
.validator_addresses(&self.client, &None)
.await?;
to_js_result(validator_addresses)
}
/// Gets total bonds by validator address
///
/// # Errors
///
/// Returns an error if the RPC call fails
pub async fn query_total_bonds(&self, address: String) -> Result<JsValue, JsError> {
let address = Address::from_str(&address)?;
let total_bonds = RPC
.vp()
.pos()
.validator_stake(&self.client, &address, &None)
.await?;
to_js_result(total_bonds)
}
/// Gets all delegations for every provided address.
/// Returns a tuple of:
/// (owner_address, validator_address, total_bonds, total_unbonds, withdrawable)
///
/// # Arguments
///
/// * `owner_addresses` - Account address in form of bech32, base64 encoded string
///
/// # Errors
///
/// Panics if address can't be deserialized
pub async fn query_my_validators(
&self,
owner_addresses: Box<[JsValue]>,
) -> Result<JsValue, JsError> {
let owner_addresses: Vec<Address> = owner_addresses
.iter()
.map(|address| {
address
.as_string()
.and_then(|address_str| Address::from_str(&address_str).ok())
// TODO: we unwrap but we could also filter_map with warning or map to error
.unwrap()
})
.collect();
let mut validators_per_address: HashMap<Address, HashSet<Address>> = HashMap::new();
for address in owner_addresses.into_iter() {
let validators = RPC
.vp()
.pos()
.delegation_validators(&self.client, &address, &None)
.await?;
validators_per_address.insert(address, validators);
}
let mut result: Vec<(Address, Address, String, String, String)> = Vec::new();
let epoch = query_epoch(&self.client).await?;
for (owner, validators) in validators_per_address.into_iter() {
for validator in validators.into_iter() {
let owner_option = &Some(owner.clone());
let validator_option = &Some(validator.clone());
let enriched = RPC
.vp()
.pos()
.enriched_bonds_and_unbonds(&self.client, epoch, owner_option, validator_option)
.await?;
result.push((
owner.clone(),
validator,
enriched.bonds_total.to_string_native(),
enriched.unbonds_total.to_string_native(),
enriched.total_withdrawable.to_string_native(),
));
}
}
to_js_result(result)
}
fn get_decoded_balance(
decoded_balance: (ValueSum<Address, I256>, ValueSum<AssetType, i128>),
) -> Vec<(Address, token::Amount)> {
let mut result = Vec::new();
for (token_addr, amount) in decoded_balance.0.components() {
let amount = token::Amount::from_change(*amount);
result.push((token_addr.clone(), amount));
}
result
}
pub async fn query_staking_positions(
&self,
owner_addresses: Box<[JsValue]>,
) -> Result<JsValue, JsError> {
let owner_addresses: Vec<Address> = owner_addresses
.iter()
.filter_map(|address| address.as_string())
.filter_map(|address| Address::from_str(&address).ok())
.collect();
let mut validators_per_address: HashMap<Address, HashSet<Address>> = HashMap::new();
for address in owner_addresses.into_iter() {
let validators = RPC
.vp()
.pos()
.delegation_validators(&self.client, &address, &None)
.await?;
validators_per_address.insert(address, validators);
}
let mut bonds = vec![];
let mut unbonds = vec![];
let epoch = query_epoch(&self.client).await?;
for (owner, validators) in validators_per_address.into_iter() {
for validator in validators.into_iter() {
let owner_option = &Some(owner.clone());
let validator_option = &Some(validator.clone());
let enriched = RPC
.vp()
.pos()
.enriched_bonds_and_unbonds(&self.client, epoch, owner_option, validator_option)
.await?;
for (bond_id, details) in &enriched.data {
for bond in &details.data.bonds {
bonds.push((
bond_id.source.clone(),
bond_id.validator.clone(),
bond.amount.to_string_native(),
bond.start.to_string(),
));
}
for unbond in &details.data.unbonds {
unbonds.push((
bond_id.source.clone(),
bond_id.validator.clone(),
unbond.amount.to_string_native(),
unbond.start.to_string(),
unbond.withdraw.to_string(),
));
}
}
}
}
to_js_result((bonds, unbonds))
}
/// Queries transparent balance for a given address
///
/// # Arguments
///
/// * `owner` - Account address in form of bech32, base64 encoded string
async fn query_transparent_balance(
&self,
owner: Address,
tokens: Vec<Address>,
) -> Result<Vec<(Address, token::Amount)>, JsError> {
let mut result = vec![];
for token in tokens {
let balances = get_token_balance(&self.client, &token, &owner, None).await?;
result.push((token, balances));
}
Ok(result)
}
pub async fn shielded_sync(
&self,
vks: Box<[DatedViewingKey]>,
chain_id: String,
) -> Result<(), JsError> {
let dated_keypairs = vks.iter().map(|vk| vk.0).collect::<Vec<_>>();
match &self.masp_client {
MaspClient::Indexer(client) => {
web_sys::console::info_1(&"Syncing using IndexerMaspClient".into());
self.sync(client.clone(), dated_keypairs, chain_id).await?
}
MaspClient::Ledger(client) => {
web_sys::console::info_1(&"Syncing using LedgerMaspClient".into());
self.sync(client.clone(), dated_keypairs, chain_id).await?
}
};
Ok(())
}
async fn sync<C>(
&self,
client: C,
dated_keypairs: Vec<DatedKeypair<ViewingKey>>,
chain_id: String,
) -> Result<(), JsError>
where
C: NamadaMaspClient + Send + Sync + Unpin + 'static,
{
let progress_bar_scanned = sync::ProgressBarWeb::new(SDK_SCANNED_PROGRESS_BAR);
let progress_bar_fetched = sync::ProgressBarWeb::new(SDK_FETCHED_PROGRESS_BAR);
let progress_bar_applied = sync::ProgressBarWeb::new(SDK_APPLIED_PROGRESS_BAR);
let shutdown_signal_web = sync::ShutdownSignalWeb {};
// batch size does not matter for masp ledger client, and if we set to sth else than 1 it breaks
// progress bar
let batch_size = match self.masp_client {
MaspClient::Ledger(_) => 1,
MaspClient::Indexer(_) => 100,
};
let config = ShieldedSyncConfig::builder()
.client(client)
.scanned_tracker(progress_bar_scanned)
.fetched_tracker(progress_bar_fetched)
.applied_tracker(progress_bar_applied)
.shutdown_signal(shutdown_signal_web)
.block_batch_size(batch_size)
.wait_for_last_query_height(true)
// Total of requests that can be failed before sync is aborted
.retry_strategy(RetryStrategy::Times(1000))
.build();
let env = sync::TaskEnvWeb::new();
let mut shielded_context: ShieldedContext<JSShieldedUtils> = ShieldedContext::default();
shielded_context.utils.chain_id = chain_id.clone();
shielded_context
.sync(env, config, None, &[], dated_keypairs.as_slice())
.await
.map_err(|e| JsError::new(&format!("{:?}", e)))?;
Ok(())
}
/// Queries shielded balance for a given extended viewing key
///
/// # Arguments
///
/// * `xvk` - Extended viewing key
async fn query_shielded_balance(
&self,
xvk: ExtendedViewingKey,
tokens: Vec<Address>,
chain_id: String,
) -> Result<Vec<(Address, token::Amount)>, JsError> {
let viewing_key = ExtendedFullViewingKey::from(xvk).fvk.vk;
// We are recreating shielded context to avoid multiple mutable borrows
let mut shielded: ShieldedContext<JSShieldedUtils> = ShieldedContext::default();
shielded.utils.chain_id = chain_id.clone();
// TODO: pass handler
shielded.try_load(async |_| {}).await;
shielded
.precompute_asset_types(&self.client, tokens.iter().collect())
.await
.map_err(|e| JsError::new(&format!("{:?}", e)))?;
let _ = shielded.save().await;
let epoch = query_masp_epoch(&self.client).await?;
let balance = shielded
.compute_exchanged_balance(&self.client, &WebIo, &viewing_key)
.await
.map_err(|e| JsError::new(&format!("{:?}", e)))?;
let res = match balance {
Some(balance) => {
let decoded_balance = shielded
.decode_combine_sum_to_epoch(&self.client, balance, epoch)
.await;
Self::get_decoded_balance(decoded_balance)
}
None => vec![],
};
Ok(res)
}
pub async fn query_balance(
&self,
owner: String,
tokens: Box<[JsValue]>,
// We need to pass chain id to load correct context
chain_id: String,
) -> Result<JsValue, JsError> {
let tokens: Vec<Address> = tokens
.iter()
.map(|address| {
let address_str = address.as_string().unwrap();
Address::from_str(&address_str).unwrap()
})
.collect();
let result = match Address::from_str(&owner) {
Ok(addr) => self.query_transparent_balance(addr, tokens).await,
Err(e1) => match ExtendedViewingKey::from_str(&owner) {
Ok(xvk) => self.query_shielded_balance(xvk, tokens, chain_id).await,
Err(e2) => return Err(JsError::new(&format!("{} {}", e1, e2))),
},
}?;
let mut mapped_result: Vec<(Address, String)> = vec![];
for (token, amount) in result {
mapped_result.push((token.clone(), amount.to_string()))
}
to_js_result(mapped_result)
}
pub async fn query_public_key(&self, address: &str) -> Result<JsValue, JsError> {
let addr = Address::from_str(address).map_err(JsError::from)?;
let pk = get_public_key_at(&self.client, &addr, 0).await?;
let result = pk.map(|v| v.to_string());
to_js_result(result)
}
pub async fn query_signed_bridge_pool(
&self,
owner_addresses: Box<[JsValue]>,
) -> Result<JsValue, JsError> {
let bridge_pool = query_signed_bridge_pool(&self.client, &WebIo).await?;
let owner_addresses: Vec<Address> = owner_addresses
.iter()
.filter_map(|address| address.as_string())
.filter_map(|address| Address::from_str(&address).ok())
.collect();
let result: Vec<TransferToEthereum> = bridge_pool
.into_iter()
.filter_map(|(_hash, pending_transfer)| {
if owner_addresses.contains(&pending_transfer.transfer.sender) {
Some(pending_transfer.transfer)
} else {
None
}
})
.collect();
to_js_result(result)
}
pub async fn query_total_staked_tokens(&self, epoch: u64) -> Result<JsValue, JsError> {
let total_staked_tokens = get_total_staked_tokens(&self.client, Epoch(epoch)).await?;
to_js_result(total_staked_tokens)
}
pub async fn query_proposal_counter(&self) -> Result<JsValue, JsError> {
let proposal_counter_key = governance_storage::get_counter_key();
let proposal_counter =
query_storage_value::<HttpClient, u64>(&self.client, &proposal_counter_key)
.await
.unwrap();
to_js_result(proposal_counter)
}
pub async fn query_proposal_by_id(&self, id: u64) -> Result<Uint8Array, JsError> {
let proposal = query_proposal_by_id(&self.client, id)
.await
.unwrap()
.expect("Proposal should be written to storage.");
let content = serde_json::to_string(&proposal.content)?;
let is_steward = is_steward(&self.client, &proposal.author).await;
let tally_type = proposal.get_tally_type(is_steward);
let tally_type_string = match tally_type {
// TODO: Change in interface
TallyType::TwoFifths => "two-fifths",
TallyType::OneHalfOverOneThird => "one-half-over-one-third",
TallyType::LessOneHalfOverOneThirdNay => "less-one-half-over-one-third-nay",
};
let (proposal_type, data) = match proposal.r#type {
ProposalType::Default => ("default", None),
ProposalType::DefaultWithWasm(hash) => ("default", Some(hash.to_string())),
ProposalType::PGFSteward(data) => {
let data_string = serde_json::to_string(&data)?;
("pgf_steward", Some(data_string))
}
ProposalType::PGFPayment(data) => {
let data_string = serde_json::to_string(&data)?;
("pgf_payment", Some(data_string))
}
};
let proposal_info = ProposalInfo {
id: proposal.id,
author: proposal.author.to_string(),
start_epoch: proposal.voting_start_epoch.0,
end_epoch: proposal.voting_end_epoch.0,
grace_epoch: proposal.activation_epoch.0,
content,
tally_type: String::from(tally_type_string),
proposal_type: String::from(proposal_type),
data,
};
let mut writer = vec![];
BorshSerialize::serialize(&proposal_info, &mut writer)?;
Ok(Uint8Array::from(writer.as_slice()))
}
#[allow(clippy::type_complexity)]
pub async fn query_proposal_votes(
&self,
proposal_id: u64,
epoch: u64,
) -> Result<JsValue, JsError> {
let votes = compute_proposal_votes(&self.client, proposal_id, Epoch(epoch)).await;
let validator_votes: Vec<(Address, String, token::Amount)> =
Vec::from_iter(votes.validators_vote.iter().map(|(address, vote)| {
let vote = match vote {
ProposalVote::Yay => "yay",
ProposalVote::Nay => "nay",
ProposalVote::Abstain => "abstain",
};
let voting_power = *votes
.validator_voting_power
.get(address)
.expect("validator has voting power entry");
(address.clone(), String::from(vote), voting_power)
}));
// TODO: refactor this to fix type_complexity clippy warning
let delegator_votes: Vec<(Address, String, Vec<(Address, token::Amount)>)> =
Vec::from_iter(votes.delegators_vote.iter().map(|(address, vote)| {
let vote = match vote {
ProposalVote::Yay => "yay",
ProposalVote::Nay => "nay",
ProposalVote::Abstain => "abstain",
};
let voting_power = votes
.delegator_voting_power
.get(address)
.expect("delegator has voting power entry")
.clone()
.into_iter()
.collect();
(address.clone(), String::from(vote), voting_power)
}));
to_js_result((validator_votes, delegator_votes))
}
pub async fn query_proposal_result(
&self,
proposal_id: u64,
epoch: u64,
) -> Result<JsValue, JsError> {
let epoch = Epoch(epoch);
let votes = compute_proposal_votes(&self.client, proposal_id, epoch).await;
let total_voting_power = get_total_staked_tokens(&self.client, epoch).await?;
let proposal = query_proposal_by_id(&self.client, proposal_id)
.await
.unwrap()
.expect("Proposal should be written to storage.");
let is_steward = is_steward(&self.client, &proposal.author).await;
let tally_type = proposal.get_tally_type(is_steward);
let proposal_result = compute_proposal_result(votes, total_voting_power, tally_type)
.expect("could compute proposal result");
let passed = match proposal_result.result {
TallyResult::Passed => true,
TallyResult::Rejected => false,
};
to_js_result((
passed,
proposal_result.total_yay_power,
proposal_result.total_nay_power,
proposal_result.total_abstain_power,
proposal_result.total_voting_power,
))
}
pub async fn query_proposal_code(&self, proposal_id: u64) -> Result<Uint8Array, JsError> {
let proposal_code_key = governance_storage::get_proposal_code_key(proposal_id);
let code =
query_storage_value::<HttpClient, Vec<u8>>(&self.client, &proposal_code_key).await?;
Ok(Uint8Array::from(code.as_slice()))
}
/// Returns a list of all delegations for given addresses and epoch
///
/// # Arguments
///
/// * `addresses` - delegators addresses
/// * `epoch` - epoch in which we want to query delegations
pub async fn get_total_delegations(
&self,
addresses: Box<[JsValue]>,
epoch: Option<u64>,
) -> Result<JsValue, JsError> {
let addresses: Vec<Address> = addresses
.iter()
.filter_map(|address| address.as_string())
.filter_map(|address| Address::from_str(&address).ok())
.collect();
let epoch = epoch.map(Epoch);
let mut delegations: HashMap<Address, token::Amount> = HashMap::new();
for address in addresses.into_iter() {
let validators: HashMap<Address, token::Amount> = RPC
.vp()
.pos()
.delegations(&self.client, &address, &epoch)
.await?;
let sum_of_delegations = validators
.into_values()
.fold(token::Amount::zero(), |acc, curr| {
acc.checked_add(curr).expect("Amount overflow")
});
delegations.insert(address, sum_of_delegations);
}
to_js_result(delegations)
}
pub async fn masp_reward_tokens(&self) -> Result<JsValue, JsError> {
let rewards = query_masp_reward_tokens(&self.client).await?;
let serializable_rewards: Vec<MaspTokenRewardData> = rewards
.iter()
.map(|reward| MaspTokenRewardData {
name: reward.name.clone(),
address: reward.address.clone(),
max_reward_rate: reward.max_reward_rate,
kp_gain: reward.kp_gain,
kd_gain: reward.kd_gain,
locked_amount_target: reward.locked_amount_target,
})
.collect();
to_js_result(serializable_rewards)
}
/// Returns list of delegators that already voted on a proposal
///
/// # Arguments
///
/// * `proposal_id` - id of proposal to get delegators votes from
pub async fn delegators_votes(&self, proposal_id: u64) -> Result<JsValue, JsError> {
let votes = query_proposal_votes(&self.client, proposal_id).await?;
let res: Vec<(Address, bool)> = votes
.into_iter()
.map(|vote| {
let is_yay = match vote.data {
ProposalVote::Yay => true,
ProposalVote::Nay => false,
ProposalVote::Abstain => false,
};
(vote.delegator, is_yay)
})
.collect();
to_js_result(res)
}
pub async fn query_gas_costs(&self) -> Result<JsValue, JsError> {
let key = storage::get_gas_cost_key();
let gas_cost_table =
query_storage_value::<HttpClient, BTreeMap<Address, token::Amount>>(&self.client, &key)
.await
.expect("Parameter should be defined.");
let mut result: Vec<(String, String)> = Vec::new();
for (token, gas_cost) in gas_cost_table {
result.push((token.to_string(), gas_cost.to_string_native()));
}
to_js_result(result)
}
pub async fn query_native_token(&self) -> Result<JsValue, JsError> {
let address = query_native_token(&self.client).await?;
to_js_result(address)
}
// Vec of code paths of supported transactions
pub fn code_paths() -> Vec<String> {
vec![
TX_TRANSFER_WASM.to_string(),
TX_BOND_WASM.to_string(),
TX_REDELEGATE_WASM.to_string(),
TX_UNBOND_WASM.to_string(),
TX_WITHDRAW_WASM.to_string(),
TX_CLAIM_REWARDS_WASM.to_string(),
TX_REVEAL_PK.to_string(),
TX_VOTE_PROPOSAL.to_string(),
TX_IBC_WASM.to_string(),
]
}
// Query supported wasm code-paths, and return a serialized vec of object containing path and hash
pub async fn query_wasm_hashes(&self) -> Result<JsValue, JsError> {
let mut results: Vec<WasmHash> = vec![];
let code_paths = Query::code_paths();
for path in code_paths {
let hash = self.query_wasm_hash(&path).await;
if hash.is_some() {
let wasm_hash = WasmHash::new(path, hash.unwrap());
results.push(wasm_hash);
}
}
Ok(JsValue::from_serde(&results).unwrap())
}
// Query hash of wasm code on chain
pub async fn query_wasm_hash(&self, tx_code_path: &str) -> Option<String> {
let hash_key = Key::wasm_hash(tx_code_path);
let (tx_code_res, _) = rpc::query_storage_value_bytes(&self.client, &hash_key, None, false)
.await
.ok()?;
if let Some(tx_code_bytes) = tx_code_res {
let tx_code = Hash::try_from(&tx_code_bytes[..]).expect("Invalid code hash");
Some(tx_code.to_string())
} else {
None
}
}
/// Gets next epoch information including timing and block details
///
/// # Errors
///
/// Returns an error if the RPC call fails
pub async fn query_next_epoch_info(&self) -> Result<JsValue, JsError> {
// TODO: This needs to be implemented in the Namada SDK RPC module
// For now, we'll return a placeholder structure
// The actual implementation should look something like:
let current_epoch = query_epoch(&self.client).await?;
let (this_epoch_first_height, epoch_duration) =
rpc::query_next_epoch_info(&self.client).await?;
let this_epoch_first_height_header =
rpc::query_block_header(&self.client, this_epoch_first_height)
.await?
.unwrap();
let first_block_time = this_epoch_first_height_header.time;
let next_epoch_time = first_block_time + epoch_duration.min_duration;
let next_epoch_block = this_epoch_first_height.0 + epoch_duration.min_num_of_blocks;
let next_epoch = current_epoch.next();
let result: (Epoch, u64, String) =
(next_epoch, next_epoch_block, next_epoch_time.to_rfc3339());
// For now, return an error indicating this needs to be implemented
// Err(JsError::new("query_next_epoch_info is not yet implemented in the Namada SDK. Please implement rpc::query_next_epoch_info first."))
// Expected return structure when implemented:
// let result = json!({
// "next_epoch": next_epoch_info.next_epoch,
// "min_block_height": next_epoch_info.min_block_height,
// "next_epoch_time": next_epoch_info.next_epoch_time.to_rfc3339(),
// });
to_js_result(result)
}
/// Gets block header information for a specific height
///
/// # Arguments
///
/// * `height` - Block height to query (optional, defaults to latest)
///
/// # Errors
///
/// Returns an error if the RPC call fails
pub async fn query_block_header(&self, height: Option<u64>) -> Result<JsValue, JsError> {
// TODO: This needs to be implemented in the Namada SDK RPC module
// For now, we'll return a placeholder structure
// The actual implementation should look something like:
// let block_header = rpc::query_block_header(&self.client, height).await?;
// For now, return an error indicating this needs to be implemented
Err(JsError::new("query_block_header is not yet implemented in the Namada SDK. Please implement rpc::query_block_header first."))
// Expected return structure when implemented:
// let result = json!({
// "height": block_header.height,
// "time": block_header.time.to_rfc3339(),
// "hash": block_header.hash.to_string(),
// "proposer_address": block_header.proposer_address.to_string(),
// });
// to_js_result(result)
}
}
//TODO: remove after moving this fn from apps to shared
pub async fn compute_proposal_votes(
client: &HttpClient,
proposal_id: u64,
epoch: Epoch,
) -> ProposalVotes {
let votes = query_proposal_votes(client, proposal_id).await.unwrap();
let mut validators_vote: HashMap<Address, ProposalVote> = HashMap::default();
let mut validator_voting_power: HashMap<Address, VotePower> = HashMap::default();
let mut delegators_vote: HashMap<Address, ProposalVote> = HashMap::default();
let mut delegator_voting_power: HashMap<Address, HashMap<Address, VotePower>> =
HashMap::default();
for vote in votes {
if vote.is_validator() {
let validator_stake = RPC
.vp()
.pos()
.validator_stake(client, &vote.validator.clone(), &Some(epoch))
.await
.expect("Validator stake should be present")
.unwrap_or_default();
validators_vote.insert(vote.validator.clone(), vote.data);
validator_voting_power.insert(vote.validator, validator_stake);
} else {
let delegator_stake = RPC
.vp()
.pos()
.bond_with_slashing(client, &vote.delegator, &vote.validator, &Some(epoch))
.await
.expect("Delegator stake should be present");
delegators_vote.insert(vote.delegator.clone(), vote.data);
delegator_voting_power
.entry(vote.delegator.clone())
.or_default()
.insert(vote.validator, delegator_stake);
}
}
ProposalVotes {
validators_vote,
validator_voting_power,
delegators_vote,
delegator_voting_power,
}
}