Skip to content

Commit

Permalink
Problem: unnecessary use of REST API instead of grpc-web (`get_accoun…
Browse files Browse the repository at this point in the history
…t_balance` part) (#663)  #511

Solution:
* Replace REST API with `grpc-web` for `get_account_balance` functions.

* Update CPP example.

* Fix CPP integration-test.

* Replace `mainnet.crypto.org:1317` with GRPC URL `mainnet.crypto.org:9090`.

* Fix JS example for balance query.

* Update JS example to make work with local chain-main.
  • Loading branch information
stevenatcrypto authored Nov 22, 2022
1 parent 308197c commit f0efa3b
Show file tree
Hide file tree
Showing 15 changed files with 146 additions and 162 deletions.
12 changes: 11 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Changelog
## [0.x.x] - unreleased
### Added
### Changed
- Update `get_account_balance` functions to replace REST API with `grpc` (non-wasm) and `grpc-web` (wasm) and delete `BalanceApiVersion`

## [0.3.0] - 2022-11-14
### Added
Expand Down Expand Up @@ -75,5 +78,12 @@
- Add basic integration-test (uncompleted) with Dev node of [chain-main](https://github.com/crypto-org-chain/chain-main) and [cronos](https://github.com/crypto-org-chain/cronos).
- Add example code in folder `example`.

\[Unreleased\]: https://github.com/crypto-com/defi-wallet-core-rs/compare/v0.1.12...HEAD
\[Unreleased\]: https://github.com/crypto-com/defi-wallet-core-rs/compare/v0.3.0...HEAD

\[0.3.0\]: https://github.com/crypto-com/defi-wallet-core-rs/releases/tag/v0.3.0

\[0.2.1\]: https://github.com/crypto-com/defi-wallet-core-rs/releases/tag/v0.2.1

\[0.2.0\]: https://github.com/crypto-com/defi-wallet-core-rs/releases/tag/v0.2.0

\[0.1.12\]: https://github.com/crypto-com/defi-wallet-core-rs/releases/tag/v0.1.12
1 change: 0 additions & 1 deletion Cargo.lock

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

24 changes: 7 additions & 17 deletions bindings/cpp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ use defi_wallet_core_common::node::ethereum::provider::set_ethers_httpagent;
use defi_wallet_core_common::{
broadcast_tx_sync_blocking, build_signed_msg_tx, build_signed_single_msg_tx,
get_account_balance_blocking, get_account_details_blocking, get_single_msg_sign_payload,
BalanceApiVersion, CosmosSDKMsg, CosmosSDKTxInfo, EthError, EthNetwork, EthTxInfo, HDWallet,
Height, LoginInfo, Network, PublicKeyBytesWrapper, RawRpcAccountResponse, SecretKey,
SingleCoin, TransactionReceipt, TxBroadcastResult, WalletCoin,
COMPRESSED_SECP256K1_PUBKEY_SIZE,
CosmosSDKMsg, CosmosSDKTxInfo, EthError, EthNetwork, EthTxInfo, HDWallet, Height, LoginInfo,
Network, PublicKeyBytesWrapper, RawRpcAccountResponse, SecretKey, SingleCoin,
TransactionReceipt, TxBroadcastResult, WalletCoin, COMPRESSED_SECP256K1_PUBKEY_SIZE,
};

use ethers::types::Signature;
Expand Down Expand Up @@ -399,10 +398,9 @@ pub mod ffi {
) -> Result<CosmosTransactionReceiptRaw>;
/// query account balance from cosmos address and denom name
pub fn query_account_balance(
api_url: String,
grpc_url: String,
address: String,
denom: String,
api_version: u8,
) -> Result<String>;
type PrivateKey;
type CosmosSDKMsgRaw;
Expand Down Expand Up @@ -1014,18 +1012,10 @@ pub fn query_account_details_info(
}

/// query account balance from cosmos address and denom name
pub fn query_account_balance(
api_url: String,
address: String,
denom: String,
api_version: u8,
) -> Result<String> {
let balance_api_version = BalanceApiVersion::from(api_version);

let account_details =
get_account_balance_blocking(&api_url, &address, &denom, balance_api_version)?;
pub fn query_account_balance(grpc_url: String, address: String, denom: String) -> Result<String> {
let balance = get_account_balance_blocking(&grpc_url, &address, &denom)?;

Ok(serde_json::to_string(&account_details)?)
Ok(serde_json::to_string(&balance)?)
}

/// broadcast the cosmos transaction
Expand Down
1 change: 0 additions & 1 deletion bindings/wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,5 @@ wasm-bindgen-test = "0.3"
ethers = { version = "0.17", features = ["rustls"] }
wasm-timer = "0.2"
tendermint-rpc = "0.23"
reqwest = { version = "0.11", default-features = false, features = ["blocking", "json", "rustls-tls"] }
defi-wallet-core-proto = { version = "0.1", path = "../../proto" }
tonic-web-wasm-client = "0.2"
31 changes: 9 additions & 22 deletions bindings/wasm/src/cosmos_sdk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{format_to_js_error, PrivateKey};
use cosmos_sdk_proto::cosmos::base::query::v1beta1::PageRequest;
use defi_wallet_core_common::{
broadcast_tx_sync, build_signed_msg_tx, get_account_balance, get_account_details, node,
BalanceApiVersion, CosmosSDKMsg, CosmosSDKTxInfo, Height, Network, SingleCoin,
CosmosSDKMsg, CosmosSDKTxInfo, Height, Network, SingleCoin,
};
use js_sys::Promise;
use serde::{Deserialize, Serialize};
Expand All @@ -27,27 +27,11 @@ impl CosmosClient {
Self { config }
}

/// Retrieve the account balance for a given address and a denom.
/// api-version: https://github.com/cosmos/cosmos-sdk/releases/tag/v0.42.11
/// - 0 means before 0.42.11 or 0.44.4
/// - >=1 means after 0.42.11 or 0.44.4
/// TODO: switch to grpc-web
pub fn query_account_balance(
&self,
address: String,
denom: String,
api_version: u8,
) -> Promise {
let api_url = self.config.api_url.to_owned();
pub fn query_account_balance(&self, address: String, denom: String) -> Promise {
let grpc_web_url = self.config.grpc_web_url.to_string();
future_to_promise(async move {
let api_version = if api_version == 0 {
BalanceApiVersion::Old
} else {
BalanceApiVersion::New
};
let account_details =
get_account_balance(&api_url, &address, &denom, api_version).await?;
serde_wasm_bindgen::to_value(&account_details).map_err(format_to_js_error)
let balance = get_account_balance(&grpc_web_url, &address, &denom).await?;
serde_wasm_bindgen::to_value(&balance).map_err(format_to_js_error)
})
}

Expand Down Expand Up @@ -84,17 +68,20 @@ impl CosmosClient {
#[derive(Serialize, Deserialize)]
#[wasm_bindgen]
pub struct CosmosClientConfig {
// TODO: Delete after replacing all with grpc-web.
api_url: String,
grpc_web_url: String,
tendermint_rpc_url: String,
}

#[wasm_bindgen]
impl CosmosClientConfig {
/// Create an instance.
#[wasm_bindgen(constructor)]
pub fn new(api_url: String, tendermint_rpc_url: String) -> Self {
pub fn new(api_url: String, grpc_web_url: String, tendermint_rpc_url: String) -> Self {
Self {
api_url,
grpc_web_url,
tendermint_rpc_url,
}
}
Expand Down
38 changes: 22 additions & 16 deletions bindings/wasm/tests/test_helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,14 @@ use wasm_timer::Delay;
pub(crate) const CHAIN_ID: &str = "chainmain-1";
pub(crate) const CHAINMAIN_DENOM: &str = "basecro";
pub(crate) const CRONOS_DENOM: &str = "basetcro";

pub(crate) const CHAINMAIN_API_URL: &str = "http://127.0.0.1:26804";
pub(crate) const CHAINMAIN_GRPC_WEB_URL: &str = "http://127.0.0.1:26808";
pub(crate) const TENDERMINT_RPC_URL: &str = "http://127.0.0.1:26807";

pub(crate) const CRONOS_RPC_URL: &str = "http://127.0.0.1:26651";
pub(crate) const CRONOS_API_URL: &str = "http://127.0.0.1:26654";
pub(crate) const TENDERMINT_RPC_URL: &str = "http://127.0.0.1:26807";
pub(crate) const GRPC_WEB_URL: &str = "http://127.0.0.1:26808";
pub(crate) const CRONOS_GRPC_WEB_URL: &str = "http://127.0.0.1:26658";

pub(crate) const COMMUNITY: &str = "cro1qj4u2y23hx7plrztswrel2hgf8mh2m22k80fet";
pub(crate) const DELEGATOR1: &str = "cro1ykec6vralvrh5vcvpf7w7u02gj728u4wp738kz";
Expand Down Expand Up @@ -51,8 +54,11 @@ pub(crate) const DEFAULT_WAITING_SECS: u64 = 3;
// Helper functions

pub(crate) fn chainmain_client() -> CosmosClient {
let config =
CosmosClientConfig::new(CHAINMAIN_API_URL.to_owned(), TENDERMINT_RPC_URL.to_owned());
let config = CosmosClientConfig::new(
CHAINMAIN_API_URL.to_owned(),
CHAINMAIN_GRPC_WEB_URL.to_owned(),
TENDERMINT_RPC_URL.to_owned(),
);
CosmosClient::new(config)
}

Expand All @@ -73,7 +79,11 @@ pub(crate) async fn chainmain_tx_info(address: &str) -> CosmosSDKTxInfoRaw {
}

pub(crate) fn cronos_client() -> CosmosClient {
let config = CosmosClientConfig::new(CRONOS_API_URL.to_owned(), TENDERMINT_RPC_URL.to_owned());
let config = CosmosClientConfig::new(
CRONOS_API_URL.to_owned(),
CRONOS_GRPC_WEB_URL.to_owned(),
TENDERMINT_RPC_URL.to_owned(),
);
CosmosClient::new(config)
}

Expand All @@ -83,7 +93,7 @@ pub(crate) fn get_private_key(mnemonic: &str) -> PrivateKey {
}

pub(crate) fn tonic_web_wasm_client() -> GrpcWebClient {
GrpcWebClient::new(GRPC_WEB_URL.to_owned())
GrpcWebClient::new(CHAINMAIN_GRPC_WEB_URL.to_owned())
}

pub(crate) async fn query_chainmain_account(address: &str) -> RawRpcAccountStatus {
Expand All @@ -101,23 +111,19 @@ pub(crate) async fn query_chainmain_account(address: &str) -> RawRpcAccountStatu
}

pub(crate) async fn query_chainmain_balance(address: &str) -> RawRpcBalance {
JsFuture::from(chainmain_client().query_account_balance(
address.to_owned(),
CHAINMAIN_DENOM.to_owned(),
1,
))
JsFuture::from(
chainmain_client().query_account_balance(address.to_owned(), CHAINMAIN_DENOM.to_owned()),
)
.await
.unwrap()
.into_serde::<RawRpcBalance>()
.unwrap()
}

pub(crate) async fn query_cronos_balance(address: &str) -> RawRpcBalance {
JsFuture::from(cronos_client().query_account_balance(
address.to_owned(),
CRONOS_DENOM.to_owned(),
0,
))
JsFuture::from(
cronos_client().query_account_balance(address.to_owned(), CRONOS_DENOM.to_owned()),
)
.await
.unwrap()
.into_serde::<RawRpcBalance>()
Expand Down
2 changes: 1 addition & 1 deletion common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ uniffi_macros = { version = "^0.21", optional = true }
url = "2"

[target.'cfg(target_arch = "wasm32")'.dependencies]
cosmos-sdk-proto = { version = "0.14", default-features = false, features = ["cosmwasm"] }
cosmos-sdk-proto = { version = "0.14", default-features = false, features = ["cosmwasm", "grpc"] }
defi-wallet-core-proto = { version = "0.1", path = "../proto" }
# NOTE: crate `bip39` cannot work with latest crate `rand` (0.8.0)
# FIXME: https://github.com/rust-bitcoin/rust-bip39/issues/14
Expand Down
9 changes: 2 additions & 7 deletions common/src/common.udl
Original file line number Diff line number Diff line change
Expand Up @@ -215,11 +215,6 @@ interface RawRpcAccountResponse {
ErrorResponse(i64 code, string message, sequence<string> details);
};

enum BalanceApiVersion {
"Old",
"New",
};

dictionary TxBroadcastResult {
string tx_hash_hex;
u32 code;
Expand All @@ -243,7 +238,7 @@ dictionary DenomMetadata {
};

interface CosmosSDKClient {
constructor(string tendermint_rpc_url, string rest_api_url, BalanceApiVersion balance_api_version, string grpc_url);
constructor(string tendermint_rpc_url, string grpc_url);

[Throws=RestError]
TxBroadcastResult broadcast_tx(sequence<u8> raw_signed_tx, TxBroadcastMode? mode);
Expand Down Expand Up @@ -545,7 +540,7 @@ namespace common {
[Throws=RestError]
RawRpcAccountResponse get_account_details_blocking([ByRef] string api_url, [ByRef] string address);
[Throws=RestError]
RawRpcBalance get_account_balance_blocking([ByRef] string api_url, [ByRef] string address, [ByRef] string denom, BalanceApiVersion version);
RawRpcBalance get_account_balance_blocking([ByRef] string grpc_url, [ByRef] string address, [ByRef] string denom);
[Throws=RestError]
u64 simulate_blocking([ByRef] string grpc_url, sequence<u8> raw_signed_tx);
[Throws=RestError]
Expand Down
Loading

0 comments on commit f0efa3b

Please sign in to comment.