all crates building

This commit is contained in:
Jędrzej Stuczyński
2023-08-01 17:55:59 +01:00
parent 8ef9560843
commit 3c8dd7a72b
40 changed files with 275 additions and 230 deletions
+13 -10
View File
@@ -18,8 +18,8 @@ use clap::{CommandFactory, Parser};
use nym_bin_common::logging::setup_logging;
use nym_client_core::config::disk_persistence::CommonClientPaths;
use nym_validator_client::nyxd::contract_traits::DkgQueryClient;
use nym_validator_client::nyxd::{Coin, CosmWasmClient};
use nym_validator_client::Config;
use nym_validator_client::nyxd::{Coin, Config};
use nym_validator_client::DirectSigningHttpRpcNyxdClient;
const SAFETY_BUFFER_SECS: u64 = 60; // 1 minute
@@ -34,11 +34,11 @@ struct Cli {
pub(crate) command: Command,
}
async fn block_until_coconut_is_available<C: CosmWasmClient + Send + Sync>(
client: &nym_validator_client::Client<C>,
async fn block_until_coconut_is_available<C: DkgQueryClient + Send + Sync>(
client: &C,
) -> Result<()> {
loop {
let epoch = client.nyxd.get_current_epoch().await?;
let epoch = client.get_current_epoch().await?;
let current_timestamp_secs = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)?
.as_secs();
@@ -89,15 +89,18 @@ async fn main() -> Result<()> {
r.amount as u128,
network_details.chain_details.mix_denom.base,
);
let client =
nym_validator_client::Client::new_signing(config, r.mnemonic.parse().unwrap())?;
let endpoint = network_details.endpoints[0].nyxd_url.as_str();
let client = DirectSigningHttpRpcNyxdClient::connect_with_mnemonic(
config,
endpoint,
r.mnemonic.parse().unwrap(),
)?;
block_until_coconut_is_available(&client).await?;
info!("Starting depositing funds, don't kill the process");
if !r.recovery_mode {
let state =
nym_bandwidth_controller::acquire::deposit(&client.nyxd, amount).await?;
let state = nym_bandwidth_controller::acquire::deposit(&client, amount).await?;
if nym_bandwidth_controller::acquire::get_credential(
&state,
&client,
@@ -117,7 +120,7 @@ async fn main() -> Result<()> {
}
}
} else {
recover_credentials(&client.nyxd, &recovery_storage, &shared_storage).await?;
recover_credentials(&client, &recovery_storage, &shared_storage).await?;
}
}
Command::Completions(c) => c.generate(&mut Cli::command(), bin_name),
+1
View File
@@ -3128,6 +3128,7 @@ dependencies = [
"colored",
"cosmrs",
"cosmwasm-std",
"cw-utils",
"cw3",
"cw4",
"eyre",
+2 -6
View File
@@ -14,7 +14,6 @@ use crate::storage::traits::FullWasmClientStorage;
use crate::storage::ClientStorage;
use crate::topology::WasmNymTopology;
use js_sys::Promise;
use nym_bandwidth_controller::wasm_mockups::{Client as FakeClient, DirectSigningNyxdClient};
use nym_client_core::client::base_client::{
BaseClientBuilder, ClientInput, ClientOutput, ClientState,
};
@@ -26,6 +25,7 @@ use nym_task::TaskManager;
use nym_topology::provider_trait::{HardcodedTopologyProvider, TopologyProvider};
use nym_topology::NymTopology;
use nym_validator_client::client::IdentityKey;
use nym_validator_client::QueryWasmRpcNyxdClient;
use rand::rngs::OsRng;
use rand::RngCore;
use std::sync::Arc;
@@ -152,11 +152,7 @@ impl NymClientBuilder {
let maybe_topology_provider = self.topology_provider();
let mut base_builder: BaseClientBuilder<_, FullWasmClientStorage> =
BaseClientBuilder::<FakeClient<DirectSigningNyxdClient>, _>::new(
&self.config.base,
storage,
None,
);
BaseClientBuilder::<QueryWasmRpcNyxdClient, _>::new(&self.config.base, storage, None);
if let Some(topology_provider) = maybe_topology_provider {
base_builder = base_builder.with_topology_provider(topology_provider);
}
+9 -9
View File
@@ -3,24 +3,24 @@
use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
// #[cfg(target_arch = "wasm32")]
mod client;
#[cfg(target_arch = "wasm32")]
// #[cfg(target_arch = "wasm32")]
pub mod encoded_payload_helper;
#[cfg(target_arch = "wasm32")]
// #[cfg(target_arch = "wasm32")]
pub mod error;
#[cfg(target_arch = "wasm32")]
// #[cfg(target_arch = "wasm32")]
pub mod gateway_selector;
#[cfg(target_arch = "wasm32")]
// #[cfg(target_arch = "wasm32")]
pub mod storage;
#[cfg(target_arch = "wasm32")]
// #[cfg(target_arch = "wasm32")]
pub mod tester;
#[cfg(target_arch = "wasm32")]
// #[cfg(target_arch = "wasm32")]
pub mod topology;
#[cfg(target_arch = "wasm32")]
// #[cfg(target_arch = "wasm32")]
pub mod validation;
#[cfg(target_arch = "wasm32")]
// #[cfg(target_arch = "wasm32")]
mod helpers;
mod constants;
+3 -5
View File
@@ -12,7 +12,6 @@ use crate::tester::helpers::{
use crate::topology::WasmNymTopology;
use futures::channel::mpsc;
use js_sys::Promise;
use nym_bandwidth_controller::wasm_mockups::{Client as FakeClient, DirectSigningNyxdClient};
use nym_bandwidth_controller::BandwidthController;
use nym_client_core::client::key_manager::ManagedKeys;
use nym_client_core::init::{InitialisationDetails, InitialisationResult};
@@ -27,6 +26,7 @@ use nym_sphinx::preparer::PreparedFragment;
use nym_task::TaskManager;
use nym_topology::NymTopology;
use nym_validator_client::client::IdentityKey;
use nym_validator_client::QueryWasmRpcNyxdClient;
use rand::rngs::OsRng;
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
@@ -41,8 +41,7 @@ mod ephemeral_receiver;
pub(crate) mod helpers;
pub type NodeTestMessage = TestMessage<WasmTestMessageExt>;
type LockedGatewayClient =
Arc<AsyncMutex<GatewayClient<FakeClient<DirectSigningNyxdClient>, EphemeralStorage>>>;
type LockedGatewayClient = Arc<AsyncMutex<GatewayClient<QueryWasmRpcNyxdClient, EphemeralStorage>>>;
pub(crate) const DEFAULT_TEST_TIMEOUT: Duration = Duration::from_secs(10);
pub(crate) const DEFAULT_TEST_PACKETS: u32 = 20;
@@ -78,8 +77,7 @@ pub struct NymNodeTesterBuilder {
base_topology: NymTopology,
// unimplemented
bandwidth_controller:
Option<BandwidthController<FakeClient<DirectSigningNyxdClient>, EphemeralStorage>>,
bandwidth_controller: Option<BandwidthController<QueryWasmRpcNyxdClient, EphemeralStorage>>,
}
fn address(keys: &ManagedKeys, gateway_identity: NodeIdentity) -> Recipient {
@@ -23,7 +23,7 @@ async fn main() {
let signer_address = signer.try_derive_accounts().unwrap()[0].address().clone();
// local 'client' ONLY signing messages
let tx_signer = TxSigner::new(signer);
let tx_signer = signer;
// possibly remote client that doesn't do ANY signing
// (only broadcasts + queries for sequence numbers)
@@ -23,6 +23,8 @@ pub use nym_mixnet_contract_common::{
// re-export the type to not break existing imports
pub use crate::coconut::CoconutApiClient;
#[cfg(feature = "http-client")]
use crate::signing::direct_wallet::DirectSecp256k1HdWallet;
#[cfg(feature = "http-client")]
use tendermint_rpc::HttpClient;
@@ -73,6 +75,11 @@ impl Config {
self.nyxd_url = nyxd_url;
self
}
pub fn with_simulated_gas_multiplier(mut self, gas_multiplier: f32) -> Self {
self.nyxd_config.simulated_gas_multiplier = gas_multiplier;
self
}
}
pub struct Client<C, S = NoSigner> {
@@ -81,7 +88,7 @@ pub struct Client<C, S = NoSigner> {
pub nyxd: NyxdClient<C, S>,
}
#[cfg(all(feature = "direct-secp256k1-wallet", feature = "http-client"))]
#[cfg(feature = "http-client")]
impl Client<HttpClient, DirectSecp256k1HdWallet> {
pub fn new_signing(
config: Config,
@@ -147,7 +154,7 @@ impl<C> Client<C> {
}
// validator-api wrappers
impl<C> Client<C> {
impl<C, S> Client<C, S> {
pub fn change_nym_api(&mut self, new_endpoint: Url) {
self.nym_api.change_url(new_endpoint)
}
+14 -1
View File
@@ -23,7 +23,9 @@ pub type SigningValidatorClient<C, S> = Client<C, S>;
#[cfg(feature = "http-client")]
pub use cosmrs::rpc::HttpClient as HttpRpcClient;
#[cfg(feature = "http-client")]
#[cfg(target_arch = "wasm32")]
pub use crate::nyxd::wasm::WasmRpcClient;
use crate::signing::direct_wallet::DirectSecp256k1HdWallet;
#[cfg(feature = "http-client")]
@@ -37,3 +39,14 @@ pub type DirectSigningHttpRpcValidatorClient = Client<HttpRpcClient, DirectSecp2
pub type DirectSigningHttpRpcNyxdClient = nyxd::NyxdClient<HttpRpcClient, DirectSecp256k1HdWallet>;
// TODO: the same for reqwest client (once implemented)
// TODO: rename it to whatever we end up using in wasm
#[cfg(target_arch = "wasm32")]
pub type QueryWasmRpcValidatorClient = Client<WasmRpcClient>;
#[cfg(target_arch = "wasm32")]
pub type QueryWasmRpcNyxdClient = nyxd::NyxdClient<WasmRpcClient>;
#[cfg(target_arch = "wasm32")]
pub type DirectSigningWasmRpcValidatorClient = Client<WasmRpcClient, DirectSecp256k1HdWallet>;
#[cfg(target_arch = "wasm32")]
pub type DirectSigningWasmRpcNyxdClient = nyxd::NyxdClient<WasmRpcClient, DirectSecp256k1HdWallet>;
@@ -17,7 +17,6 @@ use async_trait::async_trait;
use cosmrs::cosmwasm;
use cosmrs::tx::Msg;
use cosmwasm_std::Addr;
use log::{debug, trace};
use nym_network_defaults::{ChainDetails, NymNetworkDetails};
use serde::Serialize;
use std::time::SystemTime;
@@ -58,6 +57,9 @@ pub mod cosmwasm_client;
pub mod error;
pub mod fee;
#[cfg(target_arch = "wasm32")]
pub mod wasm;
// TODO: reqwest based for wasm
#[derive(Debug, Clone)]
@@ -69,29 +71,29 @@ pub struct Config {
}
impl Config {
fn parse_optional_account(
raw: Option<&String>,
expected_prefix: &str,
) -> Result<Option<AccountId>, NyxdError> {
if let Some(address) = raw {
trace!("Raw address:{:?}", raw);
trace!("Expected prefix:{:?}", expected_prefix);
let parsed: AccountId = address
.parse()
.map_err(|_| NyxdError::MalformedAccountAddress(address.clone()))?;
debug!("Parsed prefix:{:?}", parsed);
if parsed.prefix() != expected_prefix {
Err(NyxdError::UnexpectedBech32Prefix {
got: parsed.prefix().into(),
expected: expected_prefix.into(),
})
} else {
Ok(Some(parsed))
}
} else {
Ok(None)
}
}
// fn parse_optional_account(
// raw: Option<&String>,
// expected_prefix: &str,
// ) -> Result<Option<AccountId>, NyxdError> {
// if let Some(address) = raw {
// trace!("Raw address:{:?}", raw);
// trace!("Expected prefix:{:?}", expected_prefix);
// let parsed: AccountId = address
// .parse()
// .map_err(|_| NyxdError::MalformedAccountAddress(address.clone()))?;
// debug!("Parsed prefix:{:?}", parsed);
// if parsed.prefix() != expected_prefix {
// Err(NyxdError::UnexpectedBech32Prefix {
// got: parsed.prefix().into(),
// expected: expected_prefix.into(),
// })
// } else {
// Ok(Some(parsed))
// }
// } else {
// Ok(None)
// }
// }
pub fn try_from_nym_network_details(details: &NymNetworkDetails) -> Result<Self, NyxdError> {
Ok(Config {
@@ -188,8 +190,27 @@ impl<S> NyxdClient<HttpClient, S> {
}
}
impl<C> NyxdClient<C> {
pub fn new(config: Config, client: C) -> Self {
NyxdClient {
client: MaybeSigningClient::new(client, (&config).into()),
config,
}
}
}
// no trait bounds
impl<C, S> NyxdClient<C, S> {
pub fn new_signing(config: Config, client: C, signer: S) -> Self
where
S: OfflineSigner,
{
NyxdClient {
client: MaybeSigningClient::new_signing(client, signer, (&config).into()),
config,
}
}
pub fn current_config(&self) -> &Config {
&self.config
}
@@ -271,6 +292,18 @@ where
C: TendermintClient + Send + Sync,
S: Send + Sync,
{
pub async fn get_account_public_key(
&self,
address: &AccountId,
) -> Result<Option<cosmrs::crypto::PublicKey>, NyxdError> {
if let Some(account) = self.client.get_account(address).await? {
let base_account = account.try_get_base_account()?;
return Ok(base_account.pubkey);
}
Ok(None)
}
pub async fn get_current_block_timestamp(&self) -> Result<TendermintTime, NyxdError> {
self.get_block_timestamp(None).await
}
@@ -310,18 +343,6 @@ where
S: OfflineSigner + Send + Sync,
NyxdError: From<<S as OfflineSigner>::Error>,
{
pub async fn get_account_public_key(
&self,
address: &AccountId,
) -> Result<Option<cosmrs::crypto::PublicKey>, NyxdError> {
if let Some(account) = self.client.get_account(address).await? {
let base_account = account.try_get_base_account()?;
return Ok(base_account.pubkey);
}
Ok(None)
}
pub fn address(&self) -> AccountId {
match self.client.signer_addresses() {
Ok(addresses) => addresses[0].clone(),
@@ -0,0 +1,20 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nyxd::TendermintClient;
use async_trait::async_trait;
use tendermint_rpc::{Error, SimpleRequest};
pub struct WasmRpcClient {
//
}
#[async_trait]
impl TendermintClient for WasmRpcClient {
async fn perform<R>(&self, _request: R) -> Result<R::Output, Error>
where
R: SimpleRequest,
{
todo!()
}
}
@@ -5,75 +5,6 @@ use crate::signing::signer::{OfflineSigner, SigningError};
use crate::signing::SignerData;
use cosmrs::tx::{SignDoc, SignerInfo};
use cosmrs::{tx, AccountId, Any};
//
// #[derive(Debug)]
// /// A client that has only one responsibility - sign transactions
// /// and not touch chain.
// pub struct TxSigner<S> {
// signer: S,
// }
//
// impl<S> TxSigner<S> {
// pub fn new(signer: S) -> Self {
// TxSigner { signer }
// }
//
// pub fn signer(&self) -> &S {
// &self.signer
// }
//
// pub fn into_inner_signer(self) -> S {
// self.signer
// }
//
// pub fn sign_amino(
// &self,
// _signer_address: &AccountId,
// _messages: Vec<Any>,
// _fee: tx::Fee,
// _memo: impl Into<String> + Send + 'static,
// _signer_data: SignerData,
// ) -> Result<tx::Raw, S::Error>
// where
// S: OfflineSigner,
// {
// unimplemented!()
// }
//
// // TODO: change this sucker to use the trait better
// pub fn sign_direct(
// &self,
// signer_address: &AccountId,
// messages: Vec<Any>,
// fee: tx::Fee,
// memo: impl Into<String> + Send + 'static,
// signer_data: SignerData,
// ) -> Result<tx::Raw, S::Error>
// where
// S: OfflineSigner,
// {
// let account_from_signer = self.signer.find_account(signer_address)?;
//
// // TODO: experiment with this field
// let timeout_height = 0u32;
//
// let tx_body = tx::Body::new(messages, memo, timeout_height);
// let signer_info =
// SignerInfo::single_direct(Some(account_from_signer.public_key), signer_data.sequence);
// let auth_info = signer_info.auth_info(fee);
//
// let sign_doc = SignDoc::new(
// &tx_body,
// &auth_info,
// &signer_data.chain_id,
// signer_data.account_number,
// )
// .map_err(|source| SigningError::SignDocFailure { source })?;
//
// self.signer
// .sign_direct_with_account(&account_from_signer, sign_doc)
// }
// }
// extension trait for the OfflineSigner to allow to sign transactions
pub trait TxSigner: OfflineSigner {
+9 -7
View File
@@ -8,17 +8,19 @@ use nym_network_defaults::{
NymNetworkDetails,
};
pub use nym_validator_client::nym_api::Client as NymApiClient;
use nym_validator_client::nyxd::{
self, AccountId, DirectSigningNyxdClient, NyxdClient, QueryNyxdClient,
use nym_validator_client::nyxd::{self, AccountId, NyxdClient};
use nym_validator_client::{
DirectSigningHttpRpcNyxdClient, DirectSigningHttpRpcValidatorClient, QueryHttpRpcNyxdClient,
QueryHttpRpcValidatorClient,
};
use tap::prelude::*;
pub mod errors;
pub type SigningClient = nym_validator_client::nyxd::NyxdClient<DirectSigningNyxdClient>;
pub type QueryClient = nym_validator_client::nyxd::NyxdClient<QueryNyxdClient>;
pub type SigningClientWithNyxd = nym_validator_client::Client<DirectSigningNyxdClient>;
pub type QueryClientWithNyxd = nym_validator_client::Client<QueryNyxdClient>;
pub type SigningClient = DirectSigningHttpRpcNyxdClient;
pub type QueryClient = QueryHttpRpcNyxdClient;
pub type SigningClientWithNyxd = DirectSigningHttpRpcValidatorClient;
pub type QueryClientWithNyxd = QueryHttpRpcValidatorClient;
#[derive(Debug)]
pub struct ClientArgs {
@@ -79,7 +81,7 @@ pub fn create_signing_client(
.nyxd_url
.as_str();
match NyxdClient::connect_with_mnemonic(client_config, nyxd_url, mnemonic, None) {
match NyxdClient::connect_with_mnemonic(client_config, nyxd_url, mnemonic) {
Ok(client) => Ok(client),
Err(e) => Err(ContextError::NyxdError(format!("{e}"))),
}
@@ -4,7 +4,7 @@
use clap::Parser;
use log::{error, info};
use nym_validator_client::nyxd::AccountId;
use nym_validator_client::nyxd::{AccountId, CosmWasmClient};
use crate::context::QueryClient;
use crate::utils::{pretty_coin, show_error};
@@ -3,7 +3,7 @@
use clap::Parser;
use log::{error, info};
use nym_validator_client::nyxd::AccountId;
use nym_validator_client::nyxd::{AccountId, CosmWasmClient};
use nym_validator_client::signing::direct_wallet::DirectSecp256k1HdWallet;
use crate::context::QueryClient;
@@ -68,7 +68,7 @@ pub fn get_pubkey_from_mnemonic(address: AccountId, prefix: &str, mnemonic: bip3
pub async fn get_pubkey_from_chain(address: AccountId, client: &QueryClient) {
info!("Getting public key for address {} from chain...", address);
match client.get_account_details(&address).await {
match client.get_account(&address).await {
Ok(Some(account)) => {
if let Ok(base_account) = account.try_get_base_account() {
if let Some(pubkey) = base_account.pubkey {
@@ -10,6 +10,7 @@ use crate::utils::{pretty_cosmwasm_coin, show_error_passthrough};
use comfy_table::Table;
use cosmwasm_std::Addr;
use nym_mixnet_contract_common::{Delegation, PendingEpochEvent, PendingEpochEventKind};
use nym_validator_client::nyxd::contract_traits::PagedMixnetQueryClient;
#[derive(Debug, Parser)]
pub struct Args {}
@@ -21,12 +22,14 @@ pub async fn execute(_args: Args, client: SigningClientWithNyxd) {
);
let delegations = client
.get_all_delegator_delegations(client.nyxd.address())
.nyxd
.get_all_delegator_delegations(&client.nyxd.address())
.await
.map_err(show_error_passthrough);
let mixnet_contract_events = client
.get_all_nyxd_pending_epoch_events()
.nyxd
.get_all_pending_epoch_events()
.await
.map_err(show_error_passthrough);
@@ -8,7 +8,7 @@ use cosmwasm_std::Coin;
use nym_bin_common::output_format::OutputFormat;
use nym_mixnet_contract_common::construct_gateway_bonding_sign_payload;
use nym_network_defaults::{DEFAULT_CLIENT_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT};
use nym_validator_client::nyxd::contract_traits::MixnetQueryClient;
use nym_validator_client::nyxd::contract_traits::{MixnetQueryClient, NymContractsProvider};
#[derive(Debug, Parser)]
pub struct Args {
@@ -62,7 +62,7 @@ pub async fn create_payload(args: Args, client: SigningClient) {
let coin = Coin::new(args.amount, denom);
let nonce = match client.get_signing_nonce(client.address()).await {
let nonce = match client.get_signing_nonce(&client.address()).await {
Ok(nonce) => nonce,
Err(err) => {
eprint!(
@@ -73,9 +73,11 @@ pub async fn create_payload(args: Args, client: SigningClient) {
}
};
let address = account_id_to_cw_addr(client.address());
let address = account_id_to_cw_addr(&client.address());
let proxy = if args.with_vesting_account {
Some(account_id_to_cw_addr(client.vesting_contract_address()))
Some(account_id_to_cw_addr(
client.vesting_contract_address().unwrap(),
))
} else {
None
};
@@ -29,7 +29,7 @@ pub async fn update_config(args: Args, client: SigningClient) {
info!("Update gateway config!");
let current_details = match client
.get_owned_gateway(client.address())
.get_owned_gateway(&client.address())
.await
.expect("failed to query the chain for gateway details")
.gateway
@@ -30,7 +30,7 @@ pub async fn vesting_update_config(args: Args, client: SigningClient) {
info!("Update vesting gateway config!");
let current_details = match client
.get_owned_gateway(client.address())
.get_owned_gateway(&client.address())
.await
.expect("failed to query the chain for gateway details")
.gateway
@@ -10,7 +10,7 @@ use nym_bin_common::output_format::OutputFormat;
use nym_crypto::asymmetric::identity;
use nym_mixnet_contract_common::construct_family_join_permit;
use nym_mixnet_contract_common::families::FamilyHead;
use nym_validator_client::nyxd::contract_traits::MixnetQueryClient;
use nym_validator_client::nyxd::contract_traits::{MixnetQueryClient, NymContractsProvider};
#[derive(Debug, Parser)]
pub struct Args {
@@ -47,7 +47,7 @@ pub async fn create_family_join_permit_sign_payload(args: Args, client: QueryCli
// make sure this mixnode is actually a family head
if client
.get_node_family_by_head(mixnode.bond_information.identity())
.get_node_family_by_head(mixnode.bond_information.identity().to_string())
.await
.unwrap()
.family
@@ -70,7 +70,9 @@ pub async fn create_family_join_permit_sign_payload(args: Args, client: QueryCli
// let address = account_id_to_cw_addr(&args.address);
let proxy = if args.with_vesting_account {
Some(account_id_to_cw_addr(client.vesting_contract_address()))
Some(account_id_to_cw_addr(
client.vesting_contract_address().unwrap(),
))
} else {
None
};
@@ -11,7 +11,7 @@ use nym_mixnet_contract_common::{construct_mixnode_bonding_sign_payload, MixNode
use nym_network_defaults::{
DEFAULT_HTTP_API_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT, DEFAULT_VERLOC_LISTENING_PORT,
};
use nym_validator_client::nyxd::contract_traits::MixnetQueryClient;
use nym_validator_client::nyxd::contract_traits::{MixnetQueryClient, NymContractsProvider};
use nym_validator_client::nyxd::CosmWasmCoin;
#[derive(Debug, Parser)]
@@ -88,7 +88,7 @@ pub async fn create_payload(args: Args, client: SigningClient) {
},
};
let nonce = match client.get_signing_nonce(client.address()).await {
let nonce = match client.get_signing_nonce(&client.address()).await {
Ok(nonce) => nonce,
Err(err) => {
eprint!(
@@ -99,9 +99,11 @@ pub async fn create_payload(args: Args, client: SigningClient) {
}
};
let address = account_id_to_cw_addr(client.address());
let address = account_id_to_cw_addr(&client.address());
let proxy = if args.with_vesting_account {
Some(account_id_to_cw_addr(client.vesting_contract_address()))
Some(account_id_to_cw_addr(
client.vesting_contract_address().unwrap(),
))
} else {
None
};
@@ -29,7 +29,7 @@ pub async fn update_config(args: Args, client: SigningClient) {
info!("Update mix node config!");
let current_details = match client
.get_owned_mixnode(client.address())
.get_owned_mixnode(&client.address())
.await
.expect("failed to query the chain for mixnode details")
.mixnode_details
@@ -30,7 +30,7 @@ pub async fn vesting_update_config(client: SigningClient, args: Args) {
info!("Update vesting mix node config!");
let current_details = match client
.get_owned_mixnode(client.address())
.get_owned_mixnode(&client.address())
.await
.expect("failed to query the chain for mixnode details")
.mixnode_details
@@ -42,7 +42,7 @@ pub async fn create_payload(args: Args, client: SigningClient) {
let denom = client.current_chain_details().mix_denom.base.as_str();
let deposit = Coin::new(args.amount, denom);
let nonce = match client.get_service_signing_nonce(client.address()).await {
let nonce = match client.get_service_signing_nonce(&client.address()).await {
Ok(nonce) => nonce,
Err(err) => {
eprint!(
@@ -53,7 +53,7 @@ pub async fn create_payload(args: Args, client: SigningClient) {
}
};
let address = account_id_to_cw_addr(client.address());
let address = account_id_to_cw_addr(&client.address());
let payload =
construct_service_provider_announce_sign_payload(nonce, address, deposit, service);
let wrapper = DataWrapper::new(payload.to_base58_string().unwrap());
@@ -7,6 +7,7 @@ use std::str::FromStr;
use crate::context::QueryClient;
use crate::utils::show_error;
use cosmrs::tendermint::Hash;
use nym_validator_client::nyxd::CosmWasmClient;
use serde_json::json;
#[derive(Debug, Parser)]
@@ -5,6 +5,7 @@ use std::str::FromStr;
use clap::Parser;
use cosmrs::rpc::query::Query;
use nym_validator_client::nyxd::CosmWasmClient;
use serde_json::json;
use crate::context::QueryClient;
@@ -5,7 +5,7 @@ use clap::Parser;
use cosmrs::AccountId;
use log::{error, info};
use nym_validator_client::nyxd::{contract_traits::VestingQueryClient, Coin};
use nym_validator_client::nyxd::{contract_traits::VestingQueryClient, Coin, CosmWasmClient};
use crate::context::QueryClient;
use crate::utils::show_error;
@@ -6,7 +6,7 @@ use cosmrs::AccountId;
use cosmwasm_std::Coin as CosmWasmCoin;
use log::{error, info};
use nym_validator_client::nyxd::{contract_traits::VestingQueryClient, Coin};
use nym_validator_client::nyxd::{contract_traits::VestingQueryClient, Coin, CosmWasmClient};
use crate::context::QueryClient;
use crate::utils::show_error;
@@ -6,7 +6,7 @@ use log::info;
use nym_validator_client::nyxd::{
contract_traits::{VestingQueryClient, VestingSigningClient},
Coin,
Coin, CosmWasmClient,
};
use crate::context::SigningClient;
@@ -39,7 +39,7 @@ pub async fn execute(args: Args, client: SigningClient) {
.await
.unwrap_or_else(|_| Coin::new(0u128, denom));
let liquid_account_balance = client
.get_balance(account_id, denom.to_string())
.get_balance(&account_id, denom.to_string())
.await
.unwrap_or(None)
.unwrap_or_else(|| Coin::new(0u128, denom));
@@ -97,7 +97,7 @@ pub async fn execute(args: Args, client: SigningClient) {
.unwrap_or_else(|_| Coin::new(0u128, denom));
let liquid_account_balance = client
.get_balance(account_id, denom.to_string())
.get_balance(&account_id, denom.to_string())
.await
.unwrap_or(None)
.unwrap_or_else(|| Coin::new(0u128, denom));
+11 -6
View File
@@ -12,10 +12,10 @@ use nym_mixnet_contract_common::{
construct_mixnode_bonding_sign_payload, Gateway, GatewayBondingPayload, MixNode,
MixNodeCostParams, SignableGatewayBondingMsg, SignableMixNodeBondingMsg,
};
use nym_validator_client::nyxd::contract_traits::MixnetQueryClient;
use nym_validator_client::nyxd::contract_traits::{MixnetQueryClient, NymContractsProvider};
use nym_validator_client::nyxd::error::NyxdError;
use nym_validator_client::nyxd::{Coin, DirectSigningNyxdClient};
use nym_validator_client::Client;
use nym_validator_client::nyxd::Coin;
use nym_validator_client::DirectSigningHttpRpcValidatorClient;
// define this as a separate trait for mocking purposes
#[async_trait]
@@ -26,15 +26,20 @@ pub(crate) trait AddressAndNonceProvider {
}
#[async_trait]
impl AddressAndNonceProvider for Client<DirectSigningNyxdClient> {
impl AddressAndNonceProvider for DirectSigningHttpRpcValidatorClient {
async fn get_signing_nonce(&self) -> Result<Nonce, NyxdError> {
self.nyxd.get_signing_nonce(self.nyxd.address()).await
self.nyxd.get_signing_nonce(&self.nyxd.address()).await
}
fn vesting_contract_address(&self) -> Addr {
// the call to unchecked is fine here as we're converting directly from `AccountId`
// which must have been a valid bech32 address
Addr::unchecked(self.nyxd.vesting_contract_address().as_ref())
Addr::unchecked(
self.nyxd
.vesting_contract_address()
.expect("unknown vesting contract address")
.as_ref(),
)
}
fn cw_address(&self) -> Addr {
@@ -9,9 +9,10 @@ use cosmrs::bip32::DerivationPath;
use itertools::Itertools;
use nym_config::defaults::{NymNetworkDetails, COSMOS_DERIVATION_PATH};
use nym_types::account::{Account, AccountEntry, Balance};
use nym_validator_client::nyxd::CosmWasmClient;
use nym_validator_client::signing::direct_wallet::DirectSecp256k1HdWallet;
use nym_validator_client::signing::AccountData;
use nym_validator_client::{nyxd::DirectSigningNyxdClient, Client};
use nym_validator_client::DirectSigningHttpRpcValidatorClient;
use nym_wallet_types::network::Network as WalletNetwork;
use std::collections::HashMap;
use strum::IntoEnumIterator;
@@ -35,7 +36,7 @@ pub async fn get_balance(state: tauri::State<'_, WalletState>) -> Result<Balance
match client
.nyxd
.get_balance(address, base_mix_denom.to_string())
.get_balance(&address, base_mix_denom.to_string())
.await?
{
Some(coin) => {
@@ -251,7 +252,7 @@ fn create_clients(
default_api_urls: &HashMap<WalletNetwork, Url>,
config: &Config,
mnemonic: &Mnemonic,
) -> Result<Vec<(WalletNetwork, Client<DirectSigningNyxdClient>)>, BackendError> {
) -> Result<Vec<(WalletNetwork, DirectSigningHttpRpcValidatorClient)>, BackendError> {
let mut clients = Vec::new();
for network in WalletNetwork::iter() {
let nyxd_url = if let Some(url) = config.get_selected_validator_nyxd_url(network) {
@@ -285,10 +286,10 @@ fn create_clients(
.with_vesting_contract(Some(config.get_vesting_contract_address(network).as_ref()));
let config = nym_validator_client::Config::try_from_nym_network_details(&network_details)?
.with_urls(nyxd_url, api_url);
.with_urls(nyxd_url, api_url)
.with_simulated_gas_multiplier(CUSTOM_SIMULATED_GAS_MULTIPLIER);
let mut client = nym_validator_client::Client::new_signing(config, mnemonic.clone())?;
client.set_nyxd_simulated_gas_multiplier(CUSTOM_SIMULATED_GAS_MULTIPLIER);
let client = nym_validator_client::Client::new_signing(config, mnemonic.clone())?;
clients.push((network, client));
}
Ok(clients)
@@ -337,7 +337,10 @@ pub async fn get_mixnode_avg_uptime(
log::info!(">>> Get mixnode bond details");
let guard = state.read().await;
let client = guard.current_client()?;
let res = client.nyxd.get_owned_mixnode(client.nyxd.address()).await?;
let res = client
.nyxd
.get_owned_mixnode(&client.nyxd.address())
.await?;
match res.mixnode_details {
Some(details) => {
@@ -363,7 +366,10 @@ pub async fn mixnode_bond_details(
log::info!(">>> Get mixnode bond details");
let guard = state.read().await;
let client = guard.current_client()?;
let res = client.nyxd.get_owned_mixnode(client.nyxd.address()).await?;
let res = client
.nyxd
.get_owned_mixnode(&client.nyxd.address())
.await?;
let details = res
.mixnode_details
.map(|details| {
@@ -391,7 +397,10 @@ pub async fn gateway_bond_details(
log::info!(">>> Get gateway bond details");
let guard = state.read().await;
let client = guard.current_client()?;
let bond = client.nyxd.get_owned_gateway(client.nyxd.address()).await?;
let bond = client
.nyxd
.get_owned_gateway(&client.nyxd.address())
.await?;
let res = bond
.gateway
.map(|bond| {
@@ -13,7 +13,9 @@ use nym_types::deprecated::{
use nym_types::mixnode::MixNodeCostParams;
use nym_types::pending_events::PendingEpochEvent;
use nym_types::transaction::TransactionExecuteResult;
use nym_validator_client::nyxd::contract_traits::{MixnetQueryClient, MixnetSigningClient};
use nym_validator_client::nyxd::contract_traits::{
MixnetQueryClient, MixnetSigningClient, NymContractsProvider, PagedMixnetQueryClient,
};
use nym_validator_client::nyxd::Fee;
#[tauri::command]
@@ -25,7 +27,7 @@ pub async fn get_pending_delegation_events(
let reg = guard.registered_coins()?;
let client = guard.current_client()?;
let events = client.get_all_nyxd_pending_epoch_events().await?;
let events = client.nyxd.get_all_pending_epoch_events().await?;
let converted = events
.into_iter()
.map(|e| PendingEpochEvent::try_from_mixnet_contract(e, reg))
@@ -156,10 +158,13 @@ pub async fn get_all_mix_delegations(
let address = client.nyxd.address();
let network = guard.current_network();
let base_mix_denom = network.base_mix_denom().to_string();
let vesting_contract = client.nyxd.vesting_contract_address();
let vesting_contract = client
.nyxd
.vesting_contract_address()
.expect("vesting contract address is not available");
log::info!(" >>> Get delegations");
let delegations = client.get_all_delegator_delegations(address).await?;
let delegations = client.nyxd.get_all_delegator_delegations(&address).await?;
log::info!(" <<< {} delegations", delegations.len());
let pending_events_for_account = get_pending_delegation_events(state.clone()).await?;
@@ -185,7 +190,11 @@ pub async fn get_all_mix_delegations(
d.amount
);
let mixnode = client.get_mixnode_details(d.mix_id).await?.mixnode_details;
let mixnode = client
.nyxd
.get_mixnode_details(d.mix_id)
.await?
.mixnode_details;
let accumulated_by_operator = mixnode
.as_ref()
@@ -214,7 +223,7 @@ pub async fn get_all_mix_delegations(
log::trace!(" >>> Get accumulated rewards: address = {}", address);
let pending_reward = client
.nyxd
.get_pending_delegator_reward(address, d.mix_id, d.proxy.clone())
.get_pending_delegator_reward(&address, d.mix_id, d.proxy.clone())
.await?;
let accumulated_rewards = match &pending_reward.amount_earned {
@@ -5,7 +5,7 @@ use crate::error::BackendError;
use crate::nyxd_client;
use crate::state::WalletState;
use nym_types::pending_events::{PendingEpochEvent, PendingIntervalEvent};
use nym_validator_client::nyxd::contract_traits::MixnetQueryClient;
use nym_validator_client::nyxd::contract_traits::{MixnetQueryClient, PagedMixnetQueryClient};
use nym_wallet_types::interval::Interval;
#[tauri::command]
@@ -26,7 +26,7 @@ pub async fn get_pending_epoch_events(
let guard = state.read().await;
let reg = guard.registered_coins()?;
let client = guard.current_client()?;
let res = client.get_all_nyxd_pending_epoch_events().await?;
let res = client.nyxd.get_all_pending_epoch_events().await?;
log::info!("<<< got = {:?} events", res.len());
@@ -46,7 +46,7 @@ pub async fn get_pending_interval_events(
let guard = state.read().await;
let reg = guard.registered_coins()?;
let client = guard.current_client()?;
let res = client.get_all_nyxd_pending_interval_events().await?;
let res = client.nyxd.get_all_pending_interval_events().await?;
log::info!("<<< got = {:?} events", res.len());
@@ -3,7 +3,9 @@ use crate::state::WalletState;
use crate::vesting::rewards::vesting_claim_delegator_reward;
use nym_mixnet_contract_common::{MixId, RewardingParams};
use nym_types::transaction::TransactionExecuteResult;
use nym_validator_client::nyxd::contract_traits::{MixnetQueryClient, MixnetSigningClient};
use nym_validator_client::nyxd::contract_traits::{
MixnetQueryClient, MixnetSigningClient, NymContractsProvider, PagedMixnetQueryClient,
};
use nym_validator_client::nyxd::Fee;
#[tauri::command]
@@ -64,13 +66,21 @@ pub async fn claim_locked_and_unlocked_delegator_reward(
log::trace!(">>> Get delegations: mix_id = {}", mix_id);
let address = client.nyxd.address();
let delegations = client.get_all_delegator_delegations(address).await?;
let delegations = client.nyxd.get_all_delegator_delegations(&address).await?;
log::trace!("<<< {} delegations", delegations.len());
let vesting_contract = client.nyxd.vesting_contract_address().to_string();
let liquid_delegation = client.get_delegation_details(mix_id, address, None).await?;
let vesting_contract = client
.nyxd
.vesting_contract_address()
.expect("vesting contract address is not available")
.to_string();
let liquid_delegation = client
.nyxd
.get_delegation_details(mix_id, &address, None)
.await?;
let vesting_delegation = client
.get_delegation_details(mix_id, address, Some(vesting_contract))
.nyxd
.get_delegation_details(mix_id, &address, Some(vesting_contract))
.await?;
drop(guard);
@@ -4,6 +4,7 @@ use cosmrs::crypto::secp256k1::{Signature, VerifyingKey};
use cosmrs::crypto::PublicKey;
use cosmrs::AccountId;
use k256::ecdsa::signature::Verifier;
use nym_validator_client::nyxd::CosmWasmClient;
use nym_validator_client::signing::signer::OfflineSigner;
use serde::Serialize;
use serde_json::json;
@@ -23,15 +24,16 @@ pub async fn sign(
) -> Result<String, BackendError> {
let guard = state.read().await;
let client = guard.current_client()?;
let wallet = client.nyxd.signer();
let derived_accounts = wallet.try_derive_accounts()?;
let derived_accounts = client.nyxd.get_accounts()?;
let account = derived_accounts.first().ok_or_else(|| {
log::error!(">>> Unable to derive account");
BackendError::SignatureError("unable to derive account".to_string())
})?;
log::info!("<<< Signing message");
let signature = wallet.sign_raw_with_account(account, message.as_bytes())?;
let signature = client
.nyxd
.sign_raw_with_account(account, message.as_bytes())?;
let output = SignatureOutputJson {
account_id: account.address().to_string(),
public_key: account.public_key(),
@@ -49,14 +51,10 @@ async fn get_pubkey_from_account_address(
log::info!("Getting public key for address {} from chain...", address);
let guard = state.read().await;
let client = guard.current_client()?;
let account = client
.nyxd
.get_account_details(address)
.await?
.ok_or_else(|| {
log::error!("No account associated with address {}", address);
BackendError::SignatureError(format!("No account associated with address {address}"))
})?;
let account = client.nyxd.get_account(address).await?.ok_or_else(|| {
log::error!("No account associated with address {}", address);
BackendError::SignatureError(format!("No account associated with address {address}"))
})?;
let base_account = account.try_get_base_account()?;
base_account.pubkey.ok_or_else(|| {
@@ -116,7 +114,7 @@ pub async fn verify(
// get public key from current account address
let guard = state.read().await;
let client = guard.current_client()?;
let address = client.nyxd.address();
let address = &client.nyxd.address();
get_pubkey_from_account_address(address, &state).await?
}
};
@@ -5,6 +5,7 @@ use crate::error::BackendError;
use crate::operations::simulate::FeeDetails;
use crate::WalletState;
use nym_mixnet_contract_common::{ContractStateParams, ExecuteMsg};
use nym_validator_client::nyxd::contract_traits::NymContractsProvider;
use nym_wallet_types::admin::TauriContractStateParams;
#[tauri::command]
@@ -18,7 +19,10 @@ pub async fn simulate_update_contract_settings(
params.try_convert_to_mixnet_contract_params(reg)?;
let client = guard.current_client()?;
let mixnet_contract = client.nyxd.mixnet_contract_address();
let mixnet_contract = client
.nyxd
.mixnet_contract_address()
.expect("mixnet contract address is not available");
let msg = client.nyxd.wrap_contract_execute_message(
mixnet_contract,
@@ -11,6 +11,7 @@ use nym_mixnet_contract_common::{ExecuteMsg, Gateway, MixId, MixNode};
use nym_mixnet_contract_common::{GatewayConfigUpdate, MixNodeConfigUpdate};
use nym_types::currency::DecCoin;
use nym_types::mixnode::MixNodeCostParams;
use nym_validator_client::nyxd::contract_traits::NymContractsProvider;
async fn simulate_mixnet_operation(
msg: ExecuteMsg,
@@ -28,7 +29,10 @@ async fn simulate_mixnet_operation(
};
let client = guard.current_client()?;
let mixnet_contract = client.nyxd.mixnet_contract_address();
let mixnet_contract = client
.nyxd
.mixnet_contract_address()
.expect("mixnet contract address is not available");
let msg = client
.nyxd
@@ -11,6 +11,7 @@ use nym_mixnet_contract_common::{Gateway, MixId, MixNode};
use nym_mixnet_contract_common::{GatewayConfigUpdate, MixNodeConfigUpdate};
use nym_types::currency::DecCoin;
use nym_types::mixnode::MixNodeCostParams;
use nym_validator_client::nyxd::contract_traits::NymContractsProvider;
use nym_vesting_contract_common::ExecuteMsg;
async fn simulate_vesting_operation(
@@ -29,7 +30,10 @@ async fn simulate_vesting_operation(
};
let client = guard.current_client()?;
let vesting_contract = client.nyxd.vesting_contract_address();
let vesting_contract = client
.nyxd
.vesting_contract_address()
.expect("vesting contract address is not available");
let msg = client
.nyxd
+9 -11
View File
@@ -8,10 +8,8 @@ use log::warn;
use nym_types::currency::{DecCoin, Denom, RegisteredCoins};
use nym_types::fees::FeeDetails;
use nym_validator_client::nyxd::cosmwasm_client::types::SimulateResponse;
use nym_validator_client::nyxd::{
AccountId as CosmosAccountId, Coin, DirectSigningNyxdClient, Fee,
};
use nym_validator_client::Client;
use nym_validator_client::nyxd::{AccountId as CosmosAccountId, Coin, Fee, SigningCosmWasmClient};
use nym_validator_client::DirectSigningHttpRpcValidatorClient;
use nym_wallet_types::network::Network;
use nym_wallet_types::network_config;
use once_cell::sync::Lazy;
@@ -67,7 +65,7 @@ impl WalletState {
#[derive(Default)]
pub struct WalletStateInner {
config: config::Config,
signing_clients: HashMap<Network, Client<DirectSigningNyxdClient>>,
signing_clients: HashMap<Network, DirectSigningHttpRpcValidatorClient>,
current_network: Network,
// All the accounts the we get from decrypting the wallet. We hold on to these for being able to
@@ -181,7 +179,7 @@ impl WalletStateInner {
// this MUST succeed as we just used it before
let client = self.current_client()?;
let gas_price = client.nyxd.gas_price().clone();
let gas_adjustment = client.nyxd.gas_adjustment();
let gas_adjustment = client.nyxd.simulated_gas_multiplier();
let res = SimulateResult::new(simulate_response.gas_info, gas_price, gas_adjustment);
@@ -196,7 +194,7 @@ impl WalletStateInner {
pub fn client(
&self,
network: Network,
) -> Result<&Client<DirectSigningNyxdClient>, BackendError> {
) -> Result<&DirectSigningHttpRpcValidatorClient, BackendError> {
self.signing_clients
.get(&network)
.ok_or(BackendError::ClientNotInitialized)
@@ -205,13 +203,13 @@ impl WalletStateInner {
pub fn client_mut(
&mut self,
network: Network,
) -> Result<&mut Client<DirectSigningNyxdClient>, BackendError> {
) -> Result<&mut DirectSigningHttpRpcValidatorClient, BackendError> {
self.signing_clients
.get_mut(&network)
.ok_or(BackendError::ClientNotInitialized)
}
pub fn current_client(&self) -> Result<&Client<DirectSigningNyxdClient>, BackendError> {
pub fn current_client(&self) -> Result<&DirectSigningHttpRpcValidatorClient, BackendError> {
self.signing_clients
.get(&self.current_network)
.ok_or(BackendError::ClientNotInitialized)
@@ -220,7 +218,7 @@ impl WalletStateInner {
#[allow(unused)]
pub fn current_client_mut(
&mut self,
) -> Result<&mut Client<DirectSigningNyxdClient>, BackendError> {
) -> Result<&mut DirectSigningHttpRpcValidatorClient, BackendError> {
self.signing_clients
.get_mut(&self.current_network)
.ok_or(BackendError::ClientNotInitialized)
@@ -240,7 +238,7 @@ impl WalletStateInner {
Ok(self.config.save_to_files()?)
}
pub fn add_client(&mut self, network: Network, client: Client<DirectSigningNyxdClient>) {
pub fn add_client(&mut self, network: Network, client: DirectSigningHttpRpcValidatorClient) {
self.signing_clients.insert(network, client);
}
+2 -2
View File
@@ -30,7 +30,7 @@ pub fn get_env() -> AppEnv {
#[tauri::command]
pub async fn owns_mixnode(state: tauri::State<'_, WalletState>) -> Result<bool, BackendError> {
Ok(nyxd_client!(state)
.get_owned_mixnode(nyxd_client!(state).address())
.get_owned_mixnode(&nyxd_client!(state).address())
.await?
.mixnode_details
.is_some())
@@ -39,7 +39,7 @@ pub async fn owns_mixnode(state: tauri::State<'_, WalletState>) -> Result<bool,
#[tauri::command]
pub async fn owns_gateway(state: tauri::State<'_, WalletState>) -> Result<bool, BackendError> {
Ok(nyxd_client!(state)
.get_owned_gateway(nyxd_client!(state).address())
.get_owned_gateway(&nyxd_client!(state).address())
.await?
.gateway
.is_some())