Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement async client trait #173

Merged
merged 1 commit into from
Dec 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions apps/namada-interface/src/slices/StakingAndGovernance/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from "./types";
import { myStakingData } from "./fakeData";
import { RootState } from "store";
import { Abci } from "@anoma/shared";
import { Query } from "@anoma/shared";
import { RpcClient } from "@anoma/rpc";
import { fetchWasmCode } from "@anoma/utils";
import { SignedTx, Signer, Tokens, TxWasm } from "@anoma/types";
Expand Down Expand Up @@ -83,8 +83,8 @@ export const fetchValidators = createAsyncThunk<
const { chainId } = thunkApi.getState().settings;
const { rpc } = chains[chainId];

const abci = new Abci(rpc);
const allValidators = (await abci.query_all_validators()).map(toValidator);
const query = new Query(rpc);
const allValidators = (await query.query_all_validators()).map(toValidator);

thunkApi.dispatch(fetchMyValidators(allValidators));
return Promise.resolve({ allValidators });
Expand Down Expand Up @@ -120,8 +120,8 @@ export const fetchMyValidators = createAsyncThunk<

const accounts = thunkApi.getState().accounts.derived[chainId];
const addresses = Object.keys(accounts);
const abci = new Abci(rpc);
const myValidatorsRes = await abci.query_my_validators(addresses);
const query = new Query(rpc);
const myValidatorsRes = await query.query_my_validators(addresses);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

query.query_ does not look nice, but I think we can figure out naming later :)


const myValidators = myValidatorsRes.reduce(toMyValidators, []);
const myStakingPositions = myValidatorsRes.map(toStakingPosition);
Expand Down
4 changes: 3 additions & 1 deletion apps/namada-interface/src/slices/transfers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from "slices/notifications";
import { fetchBalanceByToken } from "./balances";
import { getIntegration } from "services";
import { Query } from "@anoma/shared";

enum Toasts {
TransferStarted,
Expand Down Expand Up @@ -362,6 +363,7 @@ export const submitTransferTransaction = createAsyncThunk(
const { rpc } = chains[chainId];

const rpcClient = new RpcClient(rpc);
const query = new Query(rpc);

notify &&
dispatch(
Expand All @@ -379,7 +381,7 @@ export const submitTransferTransaction = createAsyncThunk(
};

try {
const epoch = await rpcClient.queryEpoch();
const epoch = await query.query_epoch();
const revealPk = await revealPublicKey(
account,
token.address || "",
Expand Down
72 changes: 14 additions & 58 deletions packages/shared/lib/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/shared/lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ license = "MIT"
crate-type = ["cdylib", "rlib"]

[dependencies]
async-trait = {version = "0.1.51"}
borsh = "0.9.0"
chrono = "0.4.22"
getrandom = { version = "0.2.7", features = ["js"] }
gloo-utils = { version = "0.1.5", features = ["serde"] }
js-sys = "0.3.60"
masp_primitives = { git = "https://github.com/anoma/masp", rev = "bee40fc465f6afbd10558d12fe96eb1742eee45c" }
namada = {git = "https://github.com/anoma/namada", tag = "v0.11.0", features = ["ferveo-tpke"]}
namada = {git = "https://github.com/anoma/namada", branch = "mateusz/0.11.0", features = ["ferveo-tpke", "async-client"]}
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is 0.11.0 branch with changes to ?Send
PR here anoma/namada#900

prost = "0.9.0"
prost-types = "0.9.0"
rand = "0.8.5"
Expand All @@ -27,7 +28,6 @@ serde_json = "1.0"
thiserror = "^1"
wasm-bindgen = "0.2.83"
wasm-bindgen-futures = "0.4.33"
tendermint = {git = "https://github.com/heliaxdev/tendermint-rs.git", rev = "87be41b8c9cc2850830f4d8028c1fe1bd9f96284"}

[dependencies.web-sys]
version = "0.3.4"
Expand Down
102 changes: 102 additions & 0 deletions packages/shared/lib/src/api.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
use gloo_utils::format::JsValueSerdeExt;
use namada::ledger::queries::RPC;
use namada::types::address::Address;
use namada::types::token::Amount;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use wasm_bindgen::prelude::*;

use crate::rpc_client::HttpClient;

#[wasm_bindgen]
pub struct Query {
client: HttpClient,
}

#[wasm_bindgen]
impl Query {
fn to_js_result<T>(result: T) -> Result<JsValue, JsError>
where
T: Serialize,
{
match JsValue::from_serde(&result) {
Ok(v) => Ok(v),
Err(e) => Err(JsError::new(&e.to_string())),
}
}
#[wasm_bindgen(constructor)]
pub fn new(url: String) -> Query {
let client = HttpClient::new(url);
Query { client }
}

pub async fn query_epoch(&self) -> Result<JsValue, JsError> {
let epoch = RPC.shell().epoch(&self.client).await?;

Query::to_js_result(epoch)
}

pub async fn query_all_validators(&self) -> Result<JsValue, JsError> {
let validator_addresses = RPC
.vp()
.pos()
.validator_addresses(&self.client, &None)
.await?;

let mut result: Vec<(Address, Amount)> = Vec::new();

for address in validator_addresses.into_iter() {
let total_bonds = RPC
.vp()
.pos()
.validator_stake(&self.client, &address, &None)
.await?;

result.push((address, total_bonds));
}

Query::to_js_result(result)
}

pub async fn query_my_validators(
&self,
owner_addresses: Box<[JsValue]>,
) -> Result<JsValue, JsError> {
let owner_addresses: Vec<Address> = owner_addresses
.into_iter()
.map(|address| {
let address_str = &(address.as_string().unwrap()[..]);
Address::from_str(address_str).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().delegations(&self.client, &address).await?;

validators_per_address.insert(address, validators);
}

//TODO: Change to Vec of structs
//Owner, Validator, Amount
let mut result: Vec<(Address, Address, Amount)> = Vec::new();

for (owner, validators) in validators_per_address.into_iter() {
for validator in validators.into_iter() {
// let bond_path = &format!("/vp/pos/bond_amount/{}/{}", owner, validator)[..];
// let total_bonds = abci_query::<Amount>(&self.url, bond_path).await?;
let total_bonds = RPC
.vp()
.pos()
.bond_amount(&self.client, &owner, &validator, &None)
.await?;

result.push((owner.clone(), validator, total_bonds));
}
}

Query::to_js_result(result)
}
}
6 changes: 3 additions & 3 deletions packages/shared/lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
//! A library of functions to integrate shared functionality from the Anoma ecosystem

pub mod account;
pub mod reveal_pk;
pub mod bond;
pub mod ibc_transfer;
pub mod query;
pub mod reveal_pk;
pub mod rpc_client;
pub mod signer;
pub mod transfer;
pub mod types;
pub mod rpc_client;
mod utils;
Loading