Feature/rename nymd to nyxd (#2696)

* Renaming all instances of nymd to nyxd

* Might as well get the changelogs too

* Making it clearer that an ApiClient is a NymApiClient

* Lining up config templates with struct keys on gateway

* Changed the last references to validator_urls to nyxd_urls

* Fixed up a few type errors after refactoring

* Changed the changelog

* Fixed typo in changelog

* Further instances of renaming 'nymd' + introducing additional clap aliases

* updated environmental variables and allowed usage of deprecated variants

* missing occurences of coconut-locked environmental variables

Co-authored-by: Jędrzej Stuczyński <jedrzej.stuczynski@gmail.com>
This commit is contained in:
Dave Hrycyszyn
2023-01-05 15:35:47 +00:00
committed by GitHub
parent 5f4926dd49
commit 29091aab8e
196 changed files with 1750 additions and 1721 deletions
+6 -4
View File
@@ -1,6 +1,8 @@
{ {
"mainnet":[{ "mainnet": [
"nymd_url":"https://rpc.nyx.nodes.guru/", {
"api_url":"https://api.nyx.nodes.guru/" "nyxd_url": "https://rpc.nyx.nodes.guru/",
}] "api_url": "https://api.nyx.nodes.guru/"
}
]
} }
+10 -8
View File
@@ -10,6 +10,8 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
### Changed ### Changed
- renamed all references to validator_api to nym_api
- renamed all references to nymd to nyxd
- all-binaries: improved error logging ([#2686]) - all-binaries: improved error logging ([#2686])
- native client: bring shutdown logic up to the same level as socks5-client - native client: bring shutdown logic up to the same level as socks5-client
- nym-api, coconut-dkg contract: automatic, time-based dkg epoch state advancement ([#2670]) - nym-api, coconut-dkg contract: automatic, time-based dkg epoch state advancement ([#2670])
@@ -45,7 +47,7 @@ The release also include some additional work for distributed key generation in
### Changed ### Changed
- validator-api: can recover from shutdown during DKG process ([#1872]) - validator-api: can recover from shutdown during DKG process ([#1872])
- clients: deduplicate gateway inititialization, part of work towards a rust-sdk - clients: deduplicate gateway initialization, part of work towards a rust-sdk
- clients: keep all transmission lanes going at all times by making priority probabilistic - clients: keep all transmission lanes going at all times by making priority probabilistic
- clients: ability to use multi-reply SURBs to send arbitrarily long messages fully anonymously whilst requesting additional reply blocks whenever they're about to run out ([#1796], [#1801], [#1804], [#1835], [#1858], [#1883])) - clients: ability to use multi-reply SURBs to send arbitrarily long messages fully anonymously whilst requesting additional reply blocks whenever they're about to run out ([#1796], [#1801], [#1804], [#1835], [#1858], [#1883]))
@@ -120,7 +122,7 @@ The release also include some additional work for distributed key generation in
- native-client/socks5-client/wasm-client: `use_extended_packet_size` Debug config option to make the client use 'ExtendedPacketSize' for its traffic (32kB as opposed to 2kB in 1.0.2) ([#1671]) - native-client/socks5-client/wasm-client: `use_extended_packet_size` Debug config option to make the client use 'ExtendedPacketSize' for its traffic (32kB as opposed to 2kB in 1.0.2) ([#1671])
- network-requester: added additional Blockstream Green wallet endpoint to `example.allowed.list` ([#1611]) - network-requester: added additional Blockstream Green wallet endpoint to `example.allowed.list` ([#1611])
- validator-api: add `interval_operating_cost` and `profit_margin_percent` to compute reward estimation endpoint - validator-api: add `interval_operating_cost` and `profit_margin_percent` to compute reward estimation endpoint
- validator-client: added `query_contract_smart` and `query_contract_raw` on `NymdClient` ([#1558]) - validator-client: added `query_contract_smart` and `query_contract_raw` on `NyxdClient` ([#1558])
- wasm-client: uses updated wasm-compatible `client-core` so that it's now capable of packet retransmission, cover traffic and poisson delay (among other things!) ([#1673]) - wasm-client: uses updated wasm-compatible `client-core` so that it's now capable of packet retransmission, cover traffic and poisson delay (among other things!) ([#1673])
### Fixed ### Fixed
@@ -215,7 +217,7 @@ The release also include some additional work for distributed key generation in
- All binaries and cosmwasm blobs are configured at runtime now; binaries are configured using environment variables or .env files and contracts keep the configuration parameters in storage ([#1463]) - All binaries and cosmwasm blobs are configured at runtime now; binaries are configured using environment variables or .env files and contracts keep the configuration parameters in storage ([#1463])
- gateway, network-statistics: include gateway id in the sent statistical data ([#1478]) - gateway, network-statistics: include gateway id in the sent statistical data ([#1478])
- network explorer: tweak how active set probability is shown ([#1503]) - network explorer: tweak how active set probability is shown ([#1503])
- validator-api: rewarder set update fails without panicking on possible nymd queries ([#1520]) - validator-api: rewarder set update fails without panicking on possible nyxd queries ([#1520])
- network-requester, socks5 client (nym-connect): send and receive respectively a message error to be displayed about filter check failure ([#1576]) - network-requester, socks5 client (nym-connect): send and receive respectively a message error to be displayed about filter check failure ([#1576])
[#1249]: https://github.com/nymtech/nym/pull/1249 [#1249]: https://github.com/nymtech/nym/pull/1249
@@ -588,14 +590,14 @@ The release also include some additional work for distributed key generation in
- Feature/update wallet with stake rates [\#739](https://github.com/nymtech/nym/pull/739) ([neacsu](https://github.com/neacsu)) - Feature/update wallet with stake rates [\#739](https://github.com/nymtech/nym/pull/739) ([neacsu](https://github.com/neacsu))
- Add stake reward rates and bump version of client [\#738](https://github.com/nymtech/nym/pull/738) ([neacsu](https://github.com/neacsu)) - Add stake reward rates and bump version of client [\#738](https://github.com/nymtech/nym/pull/738) ([neacsu](https://github.com/neacsu))
- Bump next from 10.1.3 to 11.1.0 in /wallet-web [\#737](https://github.com/nymtech/nym/pull/737) ([dependabot[bot]](https://github.com/apps/dependabot)) - Bump next from 10.1.3 to 11.1.0 in /wallet-web [\#737](https://github.com/nymtech/nym/pull/737) ([dependabot[bot]](https://github.com/apps/dependabot))
- Feature/nymd client integration [\#736](https://github.com/nymtech/nym/pull/736) ([jstuczyn](https://github.com/jstuczyn)) - Feature/nyxd client integration [\#736](https://github.com/nymtech/nym/pull/736) ([jstuczyn](https://github.com/jstuczyn))
- Bug/fix parking lot on wasm [\#735](https://github.com/nymtech/nym/pull/735) ([neacsu](https://github.com/neacsu)) - Bug/fix parking lot on wasm [\#735](https://github.com/nymtech/nym/pull/735) ([neacsu](https://github.com/neacsu))
- Explorer API: add new HTTP resource to decorate mix nodes with geoip locations [\#734](https://github.com/nymtech/nym/pull/734) ([mmsinclair](https://github.com/mmsinclair)) - Explorer API: add new HTTP resource to decorate mix nodes with geoip locations [\#734](https://github.com/nymtech/nym/pull/734) ([mmsinclair](https://github.com/mmsinclair))
- Feature/completing nymd client api [\#732](https://github.com/nymtech/nym/pull/732) ([jstuczyn](https://github.com/jstuczyn)) - Feature/completing nyxd client api [\#732](https://github.com/nymtech/nym/pull/732) ([jstuczyn](https://github.com/jstuczyn))
- Explorer API - add port check and node description/stats proxy [\#731](https://github.com/nymtech/nym/pull/731) ([mmsinclair](https://github.com/mmsinclair)) - Explorer API - add port check and node description/stats proxy [\#731](https://github.com/nymtech/nym/pull/731) ([mmsinclair](https://github.com/mmsinclair))
- Feature/nymd client fee handling [\#730](https://github.com/nymtech/nym/pull/730) ([jstuczyn](https://github.com/jstuczyn)) - Feature/nyxd client fee handling [\#730](https://github.com/nymtech/nym/pull/730) ([jstuczyn](https://github.com/jstuczyn))
- Update DelegationCheck.tsx [\#725](https://github.com/nymtech/nym/pull/725) ([jessgess](https://github.com/jessgess)) - Update DelegationCheck.tsx [\#725](https://github.com/nymtech/nym/pull/725) ([jessgess](https://github.com/jessgess))
- Rust nymd/cosmwasm client [\#724](https://github.com/nymtech/nym/pull/724) ([jstuczyn](https://github.com/jstuczyn)) - Rust nyxd/cosmwasm client [\#724](https://github.com/nymtech/nym/pull/724) ([jstuczyn](https://github.com/jstuczyn))
- Removed wasm feature bypassing cyclic dependencies [\#723](https://github.com/nymtech/nym/pull/723) ([jstuczyn](https://github.com/jstuczyn)) - Removed wasm feature bypassing cyclic dependencies [\#723](https://github.com/nymtech/nym/pull/723) ([jstuczyn](https://github.com/jstuczyn))
- Updated used sphinx dependency to the most recent revision [\#722](https://github.com/nymtech/nym/pull/722) ([jstuczyn](https://github.com/jstuczyn)) - Updated used sphinx dependency to the most recent revision [\#722](https://github.com/nymtech/nym/pull/722) ([jstuczyn](https://github.com/jstuczyn))
- update state management and validation [\#721](https://github.com/nymtech/nym/pull/721) ([fmtabbara](https://github.com/fmtabbara)) - update state management and validation [\#721](https://github.com/nymtech/nym/pull/721) ([fmtabbara](https://github.com/fmtabbara))
@@ -614,7 +616,7 @@ The release also include some additional work for distributed key generation in
- Bond and delegation alerts [\#698](https://github.com/nymtech/nym/pull/698) ([fmtabbara](https://github.com/fmtabbara)) - Bond and delegation alerts [\#698](https://github.com/nymtech/nym/pull/698) ([fmtabbara](https://github.com/fmtabbara))
- Bugfix/network monitor version check [\#697](https://github.com/nymtech/nym/pull/697) ([jstuczyn](https://github.com/jstuczyn)) - Bugfix/network monitor version check [\#697](https://github.com/nymtech/nym/pull/697) ([jstuczyn](https://github.com/jstuczyn))
- Feature/other containers [\#692](https://github.com/nymtech/nym/pull/692) ([neacsu](https://github.com/neacsu)) - Feature/other containers [\#692](https://github.com/nymtech/nym/pull/692) ([neacsu](https://github.com/neacsu))
- Using validator API instead of nymd [\#690](https://github.com/nymtech/nym/pull/690) ([futurechimp](https://github.com/futurechimp)) - Using validator API instead of nyxd [\#690](https://github.com/nymtech/nym/pull/690) ([futurechimp](https://github.com/futurechimp))
- Hang coconut issuance off the validator-api [\#679](https://github.com/nymtech/nym/pull/679) ([durch](https://github.com/durch)) - Hang coconut issuance off the validator-api [\#679](https://github.com/nymtech/nym/pull/679) ([durch](https://github.com/durch))
- Update hmac and blake3 [\#673](https://github.com/nymtech/nym/pull/673) ([durch](https://github.com/durch)) - Update hmac and blake3 [\#673](https://github.com/nymtech/nym/pull/673) ([durch](https://github.com/durch))
@@ -152,7 +152,7 @@ impl TopologyRefresherConfig {
} }
pub struct TopologyRefresher { pub struct TopologyRefresher {
validator_client: validator_client::client::ApiClient, validator_client: validator_client::client::NymApiClient,
client_version: String, client_version: String,
nym_api_urls: Vec<Url>, nym_api_urls: Vec<Url>,
@@ -168,7 +168,9 @@ impl TopologyRefresher {
cfg.nym_api_urls.shuffle(&mut thread_rng()); cfg.nym_api_urls.shuffle(&mut thread_rng());
TopologyRefresher { TopologyRefresher {
validator_client: validator_client::client::ApiClient::new(cfg.nym_api_urls[0].clone()), validator_client: validator_client::client::NymApiClient::new(
cfg.nym_api_urls[0].clone(),
),
client_version: cfg.client_version, client_version: cfg.client_version,
nym_api_urls: cfg.nym_api_urls, nym_api_urls: cfg.nym_api_urls,
topology_accessor, topology_accessor,
+7 -7
View File
@@ -172,8 +172,8 @@ impl<T> Config<T> {
self.client.gateway_endpoint.gateway_id = id.into(); self.client.gateway_endpoint.gateway_id = id.into();
} }
pub fn set_custom_validators(&mut self, validator_urls: Vec<Url>) { pub fn set_custom_nyxd(&mut self, nyxd_urls: Vec<Url>) {
self.client.validator_urls = validator_urls; self.client.nyxd_urls = nyxd_urls;
} }
pub fn set_custom_nym_apis(&mut self, nym_api_urls: Vec<Url>) { pub fn set_custom_nym_apis(&mut self, nym_api_urls: Vec<Url>) {
@@ -234,7 +234,7 @@ impl<T> Config<T> {
} }
pub fn get_validator_endpoints(&self) -> Vec<Url> { pub fn get_validator_endpoints(&self) -> Vec<Url> {
self.client.validator_urls.clone() self.client.nyxd_urls.clone()
} }
pub fn get_nym_api_endpoints(&self) -> Vec<Url> { pub fn get_nym_api_endpoints(&self) -> Vec<Url> {
@@ -420,9 +420,9 @@ pub struct Client<T> {
#[serde(default)] #[serde(default)]
disabled_credentials_mode: bool, disabled_credentials_mode: bool,
/// Addresses to nymd validators via which the client can communicate with the chain. /// Addresses to nyxd validators via which the client can communicate with the chain.
#[serde(default)] #[serde(alias = "validator_urls")]
validator_urls: Vec<Url>, nyxd_urls: Vec<Url>,
/// Addresses to APIs running on validator from which the client gets the view of the network. /// Addresses to APIs running on validator from which the client gets the view of the network.
#[serde(alias = "validator_api_urls")] #[serde(alias = "validator_api_urls")]
@@ -476,7 +476,7 @@ impl<T: NymConfig> Default for Client<T> {
version: env!("CARGO_PKG_VERSION").to_string(), version: env!("CARGO_PKG_VERSION").to_string(),
id: "".to_string(), id: "".to_string(),
disabled_credentials_mode: true, disabled_credentials_mode: true,
validator_urls: vec![], nyxd_urls: vec![],
nym_api_urls: vec![], nym_api_urls: vec![],
private_identity_key_file: Default::default(), private_identity_key_file: Default::default(),
public_identity_key_file: Default::default(), public_identity_key_file: Default::default(),
+1 -1
View File
@@ -23,7 +23,7 @@ pub(super) async fn query_gateway_details(
let nym_api = validator_servers let nym_api = validator_servers
.choose(&mut thread_rng()) .choose(&mut thread_rng())
.ok_or(ClientCoreError::ListOfNymApisIsEmpty)?; .ok_or(ClientCoreError::ListOfNymApisIsEmpty)?;
let validator_client = validator_client::client::ApiClient::new(nym_api.clone()); let validator_client = validator_client::client::NymApiClient::new(nym_api.clone());
log::trace!("Fetching list of gateways from: {}", nym_api); log::trace!("Fetching list of gateways from: {}", nym_api);
let gateways = validator_client.get_cached_gateways().await?; let gateways = validator_client.get_cached_gateways().await?;
+1 -1
View File
@@ -23,7 +23,7 @@ credential-storage = { path = "../../common/credential-storage" }
crypto = { path = "../../common/crypto", features = ["rand", "asymmetric", "symmetric", "aes", "hashing"] } crypto = { path = "../../common/crypto", features = ["rand", "asymmetric", "symmetric", "aes", "hashing"] }
network-defaults = { path = "../../common/network-defaults" } network-defaults = { path = "../../common/network-defaults" }
pemstore = { path = "../../common/pemstore" } pemstore = { path = "../../common/pemstore" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] } validator-client = { path = "../../common/client-libs/validator-client", features = ["nyxd-client"] }
[features] [features]
coconut = ["credentials/coconut"] coconut = ["credentials/coconut"]
+11 -11
View File
@@ -6,27 +6,27 @@ use bip39::Mnemonic;
use network_defaults::{NymNetworkDetails, VOUCHER_INFO}; use network_defaults::{NymNetworkDetails, VOUCHER_INFO};
use std::str::FromStr; use std::str::FromStr;
use url::Url; use url::Url;
use validator_client::nymd; use validator_client::nyxd;
use validator_client::nymd::traits::CoconutBandwidthSigningClient; use validator_client::nyxd::traits::CoconutBandwidthSigningClient;
use validator_client::nymd::{Coin, Fee, NymdClient, SigningNymdClient}; use validator_client::nyxd::{Coin, Fee, NyxdClient, SigningNyxdClient};
pub(crate) struct Client { pub(crate) struct Client {
nymd_client: NymdClient<SigningNymdClient>, nyxd_client: NyxdClient<SigningNyxdClient>,
mix_denom_base: String, mix_denom_base: String,
} }
impl Client { impl Client {
pub fn new(nymd_url: &str, mnemonic: &str) -> Self { pub fn new(nyxd_url: &str, mnemonic: &str) -> Self {
let nymd_url = Url::from_str(nymd_url).unwrap(); let nyxd_url = Url::from_str(nyxd_url).unwrap();
let mnemonic = Mnemonic::from_str(mnemonic).unwrap(); let mnemonic = Mnemonic::from_str(mnemonic).unwrap();
let network_details = NymNetworkDetails::new_from_env(); let network_details = NymNetworkDetails::new_from_env();
let config = nymd::Config::try_from_nym_network_details(&network_details) let config = nyxd::Config::try_from_nym_network_details(&network_details)
.expect("failed to construct valid validator client config with the provided network"); .expect("failed to construct valid validator client config with the provided network");
let nymd_client = let nyxd_client =
NymdClient::connect_with_mnemonic(config, nymd_url.as_ref(), mnemonic, None).unwrap(); NyxdClient::connect_with_mnemonic(config, nyxd_url.as_ref(), mnemonic, None).unwrap();
Client { Client {
nymd_client, nyxd_client,
mix_denom_base: network_details.chain_details.mix_denom.base, mix_denom_base: network_details.chain_details.mix_denom.base,
} }
} }
@@ -40,7 +40,7 @@ impl Client {
) -> Result<String> { ) -> Result<String> {
let amount = Coin::new(amount as u128, self.mix_denom_base.clone()); let amount = Coin::new(amount as u128, self.mix_denom_base.clone());
Ok(self Ok(self
.nymd_client .nyxd_client
.deposit( .deposit(
amount, amount,
String::from(VOUCHER_INFO), String::from(VOUCHER_INFO),
+5 -5
View File
@@ -13,7 +13,7 @@ use credentials::coconut::bandwidth::{BandwidthVoucher, TOTAL_ATTRIBUTES};
use credentials::coconut::utils::obtain_aggregate_signature; use credentials::coconut::utils::obtain_aggregate_signature;
use crypto::asymmetric::{encryption, identity}; use crypto::asymmetric::{encryption, identity};
use network_defaults::{NymNetworkDetails, VOUCHER_INFO}; use network_defaults::{NymNetworkDetails, VOUCHER_INFO};
use validator_client::nymd::tx::Hash; use validator_client::nyxd::tx::Hash;
use validator_client::{CoconutApiClient, Config}; use validator_client::{CoconutApiClient, Config};
use crate::client::Client; use crate::client::Client;
@@ -38,9 +38,9 @@ pub(crate) struct Run {
#[clap(long)] #[clap(long)]
pub(crate) client_home_directory: std::path::PathBuf, pub(crate) client_home_directory: std::path::PathBuf,
/// The nymd URL that should be used /// The nyxd URL that should be used
#[clap(long)] #[clap(long)]
pub(crate) nymd_url: String, pub(crate) nyxd_url: String,
/// A mnemonic for the account that buys the credential /// A mnemonic for the account that buys the credential
#[clap(long)] #[clap(long)]
@@ -51,12 +51,12 @@ pub(crate) struct Run {
pub(crate) amount: u64, pub(crate) amount: u64,
} }
pub(crate) async fn deposit(nymd_url: &str, mnemonic: &str, amount: u64) -> Result<State> { pub(crate) async fn deposit(nyxd_url: &str, mnemonic: &str, amount: u64) -> Result<State> {
let mut rng = OsRng; let mut rng = OsRng;
let signing_keypair = KeyPair::from(identity::KeyPair::new(&mut rng)); let signing_keypair = KeyPair::from(identity::KeyPair::new(&mut rng));
let encryption_keypair = KeyPair::from(encryption::KeyPair::new(&mut rng)); let encryption_keypair = KeyPair::from(encryption::KeyPair::new(&mut rng));
let client = Client::new(nymd_url, mnemonic); let client = Client::new(nyxd_url, mnemonic);
let tx_hash = client let tx_hash = client
.deposit( .deposit(
amount, amount,
+3 -3
View File
@@ -7,15 +7,15 @@ use credential_storage::error::StorageError;
use credentials::error::Error as CredentialError; use credentials::error::Error as CredentialError;
use crypto::asymmetric::encryption::KeyRecoveryError; use crypto::asymmetric::encryption::KeyRecoveryError;
use crypto::asymmetric::identity::Ed25519RecoveryError; use crypto::asymmetric::identity::Ed25519RecoveryError;
use validator_client::nymd::error::NymdError; use validator_client::nyxd::error::NyxdError;
use validator_client::ValidatorClientError; use validator_client::ValidatorClientError;
pub type Result<T> = std::result::Result<T, CredentialClientError>; pub type Result<T> = std::result::Result<T, CredentialClientError>;
#[derive(Error, Debug)] #[derive(Error, Debug)]
pub enum CredentialClientError { pub enum CredentialClientError {
#[error("Nymd error: {0}")] #[error("Nyxd error: {0}")]
Nymd(#[from] NymdError), Nyxd(#[from] NyxdError),
#[error("Validator client error: {0}")] #[error("Validator client error: {0}")]
ValidatorClientError(#[from] ValidatorClientError), ValidatorClientError(#[from] ValidatorClientError),
+1 -1
View File
@@ -39,7 +39,7 @@ cfg_if::cfg_if! {
let db_path = r.client_home_directory.join(DATA_DIR).join(DB_FILE_NAME); let db_path = r.client_home_directory.join(DATA_DIR).join(DB_FILE_NAME);
let shared_storage = credential_storage::initialise_storage(db_path).await; let shared_storage = credential_storage::initialise_storage(db_path).await;
let state = deposit(&r.nymd_url, &r.mnemonic, r.amount).await?; let state = deposit(&r.nyxd_url, &r.mnemonic, r.amount).await?;
get_credential(&state, shared_storage).await?; get_credential(&state, shared_storage).await?;
} }
Command::Completions(c) => c.generate(&mut crate::Cli::command(), bin_name), Command::Completions(c) => c.generate(&mut crate::Cli::command(), bin_name),
+1 -1
View File
@@ -51,7 +51,7 @@ nymsphinx = { path = "../../common/nymsphinx" }
pemstore = { path = "../../common/pemstore" } pemstore = { path = "../../common/pemstore" }
task = { path = "../../common/task" } task = { path = "../../common/task" }
topology = { path = "../../common/topology" } topology = { path = "../../common/topology" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] } validator-client = { path = "../../common/client-libs/validator-client", features = ["nyxd-client"] }
version-checker = { path = "../../common/version-checker" } version-checker = { path = "../../common/version-checker" }
websocket-requests = { path = "websocket-requests" } websocket-requests = { path = "websocket-requests" }
+3 -3
View File
@@ -23,9 +23,9 @@ id = '{{ client.id }}'
# to claim bandwidth without presenting bandwidth credentials. # to claim bandwidth without presenting bandwidth credentials.
disabled_credentials_mode = {{ client.disabled_credentials_mode }} disabled_credentials_mode = {{ client.disabled_credentials_mode }}
# Addresses to nymd validators via which the client can communicate with the chain. # Addresses to nyxd validators via which the client can communicate with the chain.
validator_urls = [ nyxd_urls = [
{{#each client.validator_urls }} {{#each client.nyxd_urls }}
'{{this}}', '{{this}}',
{{/each}} {{/each}}
] ]
+3 -3
View File
@@ -52,18 +52,18 @@ impl SocketClient {
let mut client_config = let mut client_config =
validator_client::Config::try_from_nym_network_details(&details) validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config"); .expect("failed to construct validator client config");
let nymd_url = config let nyxd_url = config
.get_base() .get_base()
.get_validator_endpoints() .get_validator_endpoints()
.pop() .pop()
.expect("No nymd validator endpoint provided"); .expect("No nyxd validator endpoint provided");
let api_url = config let api_url = config
.get_base() .get_base()
.get_nym_api_endpoints() .get_nym_api_endpoints()
.pop() .pop()
.expect("No validator api endpoint provided"); .expect("No validator api endpoint provided");
// overwrite env configuration with config URLs // overwrite env configuration with config URLs
client_config = client_config.with_urls(nymd_url, api_url); client_config = client_config.with_urls(nyxd_url, api_url);
let client = validator_client::Client::new_query(client_config) let client = validator_client::Client::new_query(client_config)
.expect("Could not construct query client"); .expect("Could not construct query client");
let coconut_api_clients = let coconut_api_clients =
+4 -4
View File
@@ -29,10 +29,10 @@ pub(crate) struct Init {
#[clap(long)] #[clap(long)]
force_register_gateway: bool, force_register_gateway: bool,
/// Comma separated list of rest endpoints of the nymd validators /// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
#[clap(long, value_delimiter = ',')] #[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nymd_validators: Option<Vec<url::Url>>, nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the API validators /// Comma separated list of rest endpoints of the API validators
#[clap(long, alias = "api_validators", value_delimiter = ',')] #[clap(long, alias = "api_validators", value_delimiter = ',')]
@@ -77,7 +77,7 @@ impl From<Init> for OverrideConfig {
no_cover: init_config.no_cover, no_cover: init_config.no_cover,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
nymd_validators: init_config.nymd_validators, nyxd_urls: init_config.nyxd_urls,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
enabled_credentials_mode: init_config.enabled_credentials_mode, enabled_credentials_mode: init_config.enabled_credentials_mode,
} }
+8 -8
View File
@@ -59,7 +59,7 @@ pub(crate) struct OverrideConfig {
no_cover: bool, no_cover: bool,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
nymd_validators: Option<Vec<url::Url>>, nyxd_urls: Option<Vec<url::Url>>,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
enabled_credentials_mode: bool, enabled_credentials_mode: bool,
} }
@@ -81,8 +81,8 @@ pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Confi
if let Some(nym_apis) = args.nym_apis { if let Some(nym_apis) = args.nym_apis {
config.get_base_mut().set_custom_nym_apis(nym_apis); config.get_base_mut().set_custom_nym_apis(nym_apis);
} else if std::env::var(network_defaults::var_names::CONFIGURED).is_ok() { } else if std::env::var(network_defaults::var_names::CONFIGURED).is_ok() {
let raw_validators = std::env::var(network_defaults::var_names::API_VALIDATOR) let raw_validators =
.expect("api validator not set"); std::env::var(network_defaults::var_names::NYM_API).expect("api validator not set");
config config
.get_base_mut() .get_base_mut()
.set_custom_nym_apis(config::parse_urls(&raw_validators)); .set_custom_nym_apis(config::parse_urls(&raw_validators));
@@ -98,14 +98,14 @@ pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Confi
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
{ {
if let Some(nymd_validators) = args.nymd_validators { if let Some(nyxd_urls) = args.nyxd_urls {
config.get_base_mut().set_custom_validators(nymd_validators); config.get_base_mut().set_custom_nyxd(nyxd_urls);
} else if std::env::var(network_defaults::var_names::CONFIGURED).is_ok() { } else if std::env::var(network_defaults::var_names::CONFIGURED).is_ok() {
let raw_validators = std::env::var(network_defaults::var_names::NYMD_VALIDATOR) let raw_validators =
.expect("nymd validator not set"); std::env::var(network_defaults::var_names::NYXD).expect("nyxd validator not set");
config config
.get_base_mut() .get_base_mut()
.set_custom_validators(config::parse_urls(&raw_validators)); .set_custom_nyxd(config::parse_urls(&raw_validators));
} }
if args.enabled_credentials_mode { if args.enabled_credentials_mode {
config.get_base_mut().with_disabled_credentials(false) config.get_base_mut().with_disabled_credentials(false)
+4 -4
View File
@@ -21,10 +21,10 @@ pub(crate) struct Run {
#[clap(long)] #[clap(long)]
id: String, id: String,
/// Comma separated list of rest endpoints of the nymd validators /// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
#[clap(long, value_delimiter = ',')] #[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nymd_validators: Option<Vec<url::Url>>, nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the API validators /// Comma separated list of rest endpoints of the API validators
#[clap(long, alias = "api_validators", value_delimiter = ',')] #[clap(long, alias = "api_validators", value_delimiter = ',')]
@@ -70,7 +70,7 @@ impl From<Run> for OverrideConfig {
no_cover: run_config.no_cover, no_cover: run_config.no_cover,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
nymd_validators: run_config.nymd_validators, nyxd_urls: run_config.nyxd_urls,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
enabled_credentials_mode: run_config.enabled_credentials_mode, enabled_credentials_mode: run_config.enabled_credentials_mode,
} }
+1 -1
View File
@@ -47,7 +47,7 @@ proxy-helpers = { path = "../../common/socks5/proxy-helpers" }
socks5-requests = { path = "../../common/socks5/requests" } socks5-requests = { path = "../../common/socks5/requests" }
task = { path = "../../common/task" } task = { path = "../../common/task" }
topology = { path = "../../common/topology" } topology = { path = "../../common/topology" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] } validator-client = { path = "../../common/client-libs/validator-client", features = ["nyxd-client"] }
version-checker = { path = "../../common/version-checker" } version-checker = { path = "../../common/version-checker" }
[features] [features]
+3 -3
View File
@@ -23,9 +23,9 @@ id = '{{ client.id }}'
# to claim bandwidth without presenting bandwidth credentials. # to claim bandwidth without presenting bandwidth credentials.
disabled_credentials_mode = {{ client.disabled_credentials_mode }} disabled_credentials_mode = {{ client.disabled_credentials_mode }}
# Addresses to nymd validators via which the client can communicate with the chain. # Addresses to nyxd validators via which the client can communicate with the chain.
validator_urls = [ nyxd_urls = [
{{#each client.validator_urls }} {{#each client.nyxd_urls }}
'{{this}}', '{{this}}',
{{/each}} {{/each}}
] ]
+3 -3
View File
@@ -60,18 +60,18 @@ impl NymClient {
let mut client_config = let mut client_config =
validator_client::Config::try_from_nym_network_details(&details) validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config"); .expect("failed to construct validator client config");
let nymd_url = config let nyxd_url = config
.get_base() .get_base()
.get_validator_endpoints() .get_validator_endpoints()
.pop() .pop()
.expect("No nymd validator endpoint provided"); .expect("No nyxd validator endpoint provided");
let api_url = config let api_url = config
.get_base() .get_base()
.get_nym_api_endpoints() .get_nym_api_endpoints()
.pop() .pop()
.expect("No validator api endpoint provided"); .expect("No validator api endpoint provided");
// overwrite env configuration with config URLs // overwrite env configuration with config URLs
client_config = client_config.with_urls(nymd_url, api_url); client_config = client_config.with_urls(nyxd_url, api_url);
let client = validator_client::Client::new_query(client_config) let client = validator_client::Client::new_query(client_config)
.expect("Could not construct query client"); .expect("Could not construct query client");
let coconut_api_clients = let coconut_api_clients =
+4 -4
View File
@@ -42,10 +42,10 @@ pub(crate) struct Init {
#[clap(long)] #[clap(long)]
force_register_gateway: bool, force_register_gateway: bool,
/// Comma separated list of rest endpoints of the nymd validators /// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
#[clap(long, value_delimiter = ',')] #[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nymd_validators: Option<Vec<url::Url>>, nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the API validators /// Comma separated list of rest endpoints of the API validators
#[clap(long, alias = "api_validators", value_delimiter = ',')] #[clap(long, alias = "api_validators", value_delimiter = ',')]
@@ -86,7 +86,7 @@ impl From<Init> for OverrideConfig {
no_cover: init_config.no_cover, no_cover: init_config.no_cover,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
nymd_validators: init_config.nymd_validators, nyxd_urls: init_config.nyxd_urls,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
enabled_credentials_mode: init_config.enabled_credentials_mode, enabled_credentials_mode: init_config.enabled_credentials_mode,
} }
+6 -8
View File
@@ -62,7 +62,7 @@ pub(crate) struct OverrideConfig {
no_cover: bool, no_cover: bool,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
nymd_validators: Option<Vec<url::Url>>, nyxd_urls: Option<Vec<url::Url>>,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
enabled_credentials_mode: bool, enabled_credentials_mode: bool,
} }
@@ -83,7 +83,7 @@ pub(crate) async fn execute(args: &Cli) -> Result<(), Box<dyn Error + Send + Syn
pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Config { pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Config {
if let Some(nym_apis) = args.nym_apis { if let Some(nym_apis) = args.nym_apis {
config.get_base_mut().set_custom_nym_apis(nym_apis); config.get_base_mut().set_custom_nym_apis(nym_apis);
} else if let Ok(raw_validators) = std::env::var(network_defaults::var_names::API_VALIDATOR) { } else if let Ok(raw_validators) = std::env::var(network_defaults::var_names::NYM_API) {
config config
.get_base_mut() .get_base_mut()
.set_custom_nym_apis(parse_urls(&raw_validators)); .set_custom_nym_apis(parse_urls(&raw_validators));
@@ -99,14 +99,12 @@ pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Confi
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
{ {
if let Some(nymd_validators) = args.nymd_validators { if let Some(nyxd_urls) = args.nyxd_urls {
config.get_base_mut().set_custom_validators(nymd_validators); config.get_base_mut().set_custom_nyxd(nyxd_urls);
} else if let Ok(raw_validators) = } else if let Ok(raw_validators) = std::env::var(network_defaults::var_names::NYXD) {
std::env::var(network_defaults::var_names::NYMD_VALIDATOR)
{
config config
.get_base_mut() .get_base_mut()
.set_custom_validators(parse_urls(&raw_validators)); .set_custom_nyxd(parse_urls(&raw_validators));
} }
if args.enabled_credentials_mode { if args.enabled_credentials_mode {
config.get_base_mut().with_disabled_credentials(false) config.get_base_mut().with_disabled_credentials(false)
+4 -4
View File
@@ -42,10 +42,10 @@ pub(crate) struct Run {
#[clap(long)] #[clap(long)]
gateway: Option<identity::PublicKey>, gateway: Option<identity::PublicKey>,
/// Comma separated list of rest endpoints of the nymd validators /// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
#[clap(long, value_delimiter = ',')] #[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nymd_validators: Option<Vec<url::Url>>, nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the Nym APIs /// Comma separated list of rest endpoints of the Nym APIs
#[clap(long, value_delimiter = ',')] #[clap(long, value_delimiter = ',')]
@@ -81,7 +81,7 @@ impl From<Run> for OverrideConfig {
no_cover: run_config.no_cover, no_cover: run_config.no_cover,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
nymd_validators: run_config.nymd_validators, nyxd_urls: run_config.nyxd_urls,
#[cfg(feature = "coconut")] #[cfg(feature = "coconut")]
enabled_credentials_mode: run_config.enabled_credentials_mode, enabled_credentials_mode: run_config.enabled_credentials_mode,
} }
+14 -14
View File
@@ -85,7 +85,7 @@ export default class ValidatorClient implements INymClient {
static async connect( static async connect(
mnemonic: string, mnemonic: string,
nymdUrl: string, nyxdUrl: string,
nymApiUrl: string, nymApiUrl: string,
prefix: string, prefix: string,
mixnetContract: string, mixnetContract: string,
@@ -94,19 +94,19 @@ export default class ValidatorClient implements INymClient {
): Promise<ValidatorClient> { ): Promise<ValidatorClient> {
const wallet = await ValidatorClient.buildWallet(mnemonic, prefix); const wallet = await ValidatorClient.buildWallet(mnemonic, prefix);
const signingClient = await SigningClient.connectWithNymSigner(wallet, nymdUrl, nymApiUrl, prefix, denom); const signingClient = await SigningClient.connectWithNymSigner(wallet, nyxdUrl, nymApiUrl, prefix, denom);
return new ValidatorClient(signingClient, prefix, mixnetContract, vestingContract, denom); return new ValidatorClient(signingClient, prefix, mixnetContract, vestingContract, denom);
} }
static async connectForQuery( static async connectForQuery(
nymdUrl: string, nyxdUrl: string,
nymApiUrl: string, nymApiUrl: string,
prefix: string, prefix: string,
mixnetContract: string, mixnetContract: string,
vestingContract: string, vestingContract: string,
denom: string, denom: string,
): Promise<ValidatorClient> { ): Promise<ValidatorClient> {
const queryClient = await QueryClient.connectWithNym(nymdUrl, nymApiUrl); const queryClient = await QueryClient.connectWithNym(nyxdUrl, nymApiUrl);
return new ValidatorClient(queryClient, prefix, mixnetContract, vestingContract, denom); return new ValidatorClient(queryClient, prefix, mixnetContract, vestingContract, denom);
} }
@@ -191,11 +191,11 @@ export default class ValidatorClient implements INymClient {
return this.client.getIntervalRewardPercent(this.mixnetContract); return this.client.getIntervalRewardPercent(this.mixnetContract);
} }
public async getAllNymdMixnodes(): Promise<MixNodeBond[]> { public async getAllNyxdMixnodes(): Promise<MixNodeBond[]> {
let mixNodes: MixNodeBond[] = []; let mixNodes: MixNodeBond[] = [];
const limit = 50; const limit = 50;
let startAfter; let startAfter;
for (;;) { for (; ;) {
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedMixnodeResponse = await this.client.getMixNodesPaged(this.mixnetContract, limit); const pagedResponse: PagedMixnodeResponse = await this.client.getMixNodesPaged(this.mixnetContract, limit);
mixNodes = mixNodes.concat(pagedResponse.nodes); mixNodes = mixNodes.concat(pagedResponse.nodes);
@@ -209,11 +209,11 @@ export default class ValidatorClient implements INymClient {
return mixNodes; return mixNodes;
} }
public async getAllNymdGateways(): Promise<GatewayBond[]> { public async getAllNyxdGateways(): Promise<GatewayBond[]> {
let gateways: GatewayBond[] = []; let gateways: GatewayBond[] = [];
const limit = 50; const limit = 50;
let startAfter; let startAfter;
for (;;) { for (; ;) {
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedGatewayResponse = await this.client.getGatewaysPaged(this.mixnetContract, limit); const pagedResponse: PagedGatewayResponse = await this.client.getGatewaysPaged(this.mixnetContract, limit);
gateways = gateways.concat(pagedResponse.nodes); gateways = gateways.concat(pagedResponse.nodes);
@@ -232,11 +232,11 @@ export default class ValidatorClient implements INymClient {
* *
* @param mixIdentity identity of the node to which the delegation was sent * @param mixIdentity identity of the node to which the delegation was sent
*/ */
public async getAllNymdSingleMixnodeDelegations(mixIdentity: string): Promise<Delegation[]> { public async getAllNyxdSingleMixnodeDelegations(mixIdentity: string): Promise<Delegation[]> {
let delegations: Delegation[] = []; let delegations: Delegation[] = [];
const limit = 250; const limit = 250;
let startAfter; let startAfter;
for (;;) { for (; ;) {
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedMixDelegationsResponse = await this.client.getMixNodeDelegationsPaged( const pagedResponse: PagedMixDelegationsResponse = await this.client.getMixNodeDelegationsPaged(
this.mixnetContract, this.mixnetContract,
@@ -255,11 +255,11 @@ export default class ValidatorClient implements INymClient {
return delegations; return delegations;
} }
public async getAllNymdDelegatorDelegations(delegator: string): Promise<Delegation[]> { public async getAllNyxdDelegatorDelegations(delegator: string): Promise<Delegation[]> {
let delegations: Delegation[] = []; let delegations: Delegation[] = [];
const limit = 250; const limit = 250;
let startAfter; let startAfter;
for (;;) { for (; ;) {
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedDelegatorDelegationsResponse = await this.client.getDelegatorDelegationsPaged( const pagedResponse: PagedDelegatorDelegationsResponse = await this.client.getDelegatorDelegationsPaged(
this.mixnetContract, this.mixnetContract,
@@ -278,11 +278,11 @@ export default class ValidatorClient implements INymClient {
return delegations; return delegations;
} }
public async getAllNymdNetworkDelegations(): Promise<Delegation[]> { public async getAllNyxdNetworkDelegations(): Promise<Delegation[]> {
let delegations: Delegation[] = []; let delegations: Delegation[] = [];
const limit = 250; const limit = 250;
let startAfter; let startAfter;
for (;;) { for (; ;) {
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedAllDelegationsResponse = await this.client.getAllNetworkDelegationsPaged( const pagedResponse: PagedAllDelegationsResponse = await this.client.getAllNetworkDelegationsPaged(
this.mixnetContract, this.mixnetContract,
@@ -5,7 +5,7 @@
import { JsonObject } from '@cosmjs/cosmwasm-stargate'; import { JsonObject } from '@cosmjs/cosmwasm-stargate';
// eslint-disable-next-line import/no-cycle // eslint-disable-next-line import/no-cycle
import { INymdQuery } from './query-client'; import { INyxdQuery } from './query-client';
import { import {
ContractStateParams, ContractStateParams,
Delegation, Delegation,
@@ -25,7 +25,7 @@ interface SmartContractQuery {
queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject>; queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject>;
} }
export default class NymdQuerier implements INymdQuery { export default class NyxdQuerier implements INyxdQuery {
client: SmartContractQuery; client: SmartContractQuery;
constructor(client: SmartContractQuery) { constructor(client: SmartContractQuery) {
+23 -23
View File
@@ -12,7 +12,7 @@ import {
} from '@cosmjs/stargate'; } from '@cosmjs/stargate';
import { Code, CodeDetails, Contract, ContractCodeHistoryEntry } from '@cosmjs/cosmwasm-stargate/build/cosmwasmclient'; import { Code, CodeDetails, Contract, ContractCodeHistoryEntry } from '@cosmjs/cosmwasm-stargate/build/cosmwasmclient';
// eslint-disable-next-line import/no-cycle // eslint-disable-next-line import/no-cycle
import NymdQuerier from './nymd-querier'; import NyxdQuerier from './nyxd-querier';
import { import {
ContractStateParams, ContractStateParams,
Delegation, Delegation,
@@ -52,7 +52,7 @@ export interface ICosmWasmQuery {
queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject>; queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject>;
} }
export interface INymdQuery { export interface INyxdQuery {
// nym-specific implemented inside NymQuerier // nym-specific implemented inside NymQuerier
getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion>; getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion>;
@@ -93,46 +93,46 @@ export interface INymdQuery {
): Promise<RewardingStatus>; ): Promise<RewardingStatus>;
} }
export interface IQueryClient extends ICosmWasmQuery, INymdQuery, INymApiQuery { } export interface IQueryClient extends ICosmWasmQuery, INyxdQuery, INymApiQuery { }
export default class QueryClient extends CosmWasmClient implements IQueryClient { export default class QueryClient extends CosmWasmClient implements IQueryClient {
private nymdQuerier: NymdQuerier; private nyxdQuerier: NyxdQuerier;
private nymApiQuerier: NymApiQuerier; private nymApiQuerier: NymApiQuerier;
private constructor(tmClient: Tendermint34Client, nymApiUrl: string) { private constructor(tmClient: Tendermint34Client, nymApiUrl: string) {
super(tmClient); super(tmClient);
this.nymdQuerier = new NymdQuerier(this); this.nyxdQuerier = new NyxdQuerier(this);
this.nymApiQuerier = new NymApiQuerier(nymApiUrl); this.nymApiQuerier = new NymApiQuerier(nymApiUrl);
} }
public static async connectWithNym(nymdUrl: string, nymApiUrl: string): Promise<QueryClient> { public static async connectWithNym(nyxdUrl: string, nymApiUrl: string): Promise<QueryClient> {
const tmClient = await Tendermint34Client.connect(nymdUrl); const tmClient = await Tendermint34Client.connect(nyxdUrl);
return new QueryClient(tmClient, nymApiUrl); return new QueryClient(tmClient, nymApiUrl);
} }
getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion> { getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion> {
return this.nymdQuerier.getContractVersion(mixnetContractAddress); return this.nyxdQuerier.getContractVersion(mixnetContractAddress);
} }
getMixNodesPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedMixnodeResponse> { getMixNodesPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedMixnodeResponse> {
return this.nymdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter); return this.nyxdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter);
} }
getGatewaysPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedGatewayResponse> { getGatewaysPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedGatewayResponse> {
return this.nymdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter); return this.nyxdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter);
} }
ownsMixNode(mixnetContractAddress: string, address: string): Promise<MixOwnershipResponse> { ownsMixNode(mixnetContractAddress: string, address: string): Promise<MixOwnershipResponse> {
return this.nymdQuerier.ownsMixNode(mixnetContractAddress, address); return this.nyxdQuerier.ownsMixNode(mixnetContractAddress, address);
} }
ownsGateway(mixnetContractAddress: string, address: string): Promise<GatewayOwnershipResponse> { ownsGateway(mixnetContractAddress: string, address: string): Promise<GatewayOwnershipResponse> {
return this.nymdQuerier.ownsGateway(mixnetContractAddress, address); return this.nyxdQuerier.ownsGateway(mixnetContractAddress, address);
} }
getStateParams(mixnetContractAddress: string): Promise<ContractStateParams> { getStateParams(mixnetContractAddress: string): Promise<ContractStateParams> {
return this.nymdQuerier.getStateParams(mixnetContractAddress); return this.nyxdQuerier.getStateParams(mixnetContractAddress);
} }
getAllNetworkDelegationsPaged( getAllNetworkDelegationsPaged(
@@ -140,7 +140,7 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
limit?: number, limit?: number,
startAfter?: [string, string], startAfter?: [string, string],
): Promise<PagedAllDelegationsResponse> { ): Promise<PagedAllDelegationsResponse> {
return this.nymdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter); return this.nyxdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter);
} }
getMixNodeDelegationsPaged( getMixNodeDelegationsPaged(
@@ -149,7 +149,7 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
limit?: number, limit?: number,
startAfter?: string, startAfter?: string,
): Promise<PagedMixDelegationsResponse> { ): Promise<PagedMixDelegationsResponse> {
return this.nymdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter); return this.nyxdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter);
} }
getDelegatorDelegationsPaged( getDelegatorDelegationsPaged(
@@ -158,31 +158,31 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
limit?: number, limit?: number,
startAfter?: string, startAfter?: string,
): Promise<PagedDelegatorDelegationsResponse> { ): Promise<PagedDelegatorDelegationsResponse> {
return this.nymdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter); return this.nyxdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter);
} }
getDelegationDetails(mixnetContractAddress: string, mixIdentity: string, delegator: string): Promise<Delegation> { getDelegationDetails(mixnetContractAddress: string, mixIdentity: string, delegator: string): Promise<Delegation> {
return this.nymdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator); return this.nyxdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator);
} }
getLayerDistribution(mixnetContractAddress: string): Promise<LayerDistribution> { getLayerDistribution(mixnetContractAddress: string): Promise<LayerDistribution> {
return this.nymdQuerier.getLayerDistribution(mixnetContractAddress); return this.nyxdQuerier.getLayerDistribution(mixnetContractAddress);
} }
getRewardPool(mixnetContractAddress: string): Promise<string> { getRewardPool(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getRewardPool(mixnetContractAddress); return this.nyxdQuerier.getRewardPool(mixnetContractAddress);
} }
getCirculatingSupply(mixnetContractAddress: string): Promise<string> { getCirculatingSupply(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getCirculatingSupply(mixnetContractAddress); return this.nyxdQuerier.getCirculatingSupply(mixnetContractAddress);
} }
getIntervalRewardPercent(mixnetContractAddress: string): Promise<number> { getIntervalRewardPercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getIntervalRewardPercent(mixnetContractAddress); return this.nyxdQuerier.getIntervalRewardPercent(mixnetContractAddress);
} }
getSybilResistancePercent(mixnetContractAddress: string): Promise<number> { getSybilResistancePercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getSybilResistancePercent(mixnetContractAddress); return this.nyxdQuerier.getSybilResistancePercent(mixnetContractAddress);
} }
getRewardingStatus( getRewardingStatus(
@@ -190,7 +190,7 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
mixIdentity: string, mixIdentity: string,
rewardingIntervalNonce: number, rewardingIntervalNonce: number,
): Promise<RewardingStatus> { ): Promise<RewardingStatus> {
return this.nymdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce); return this.nyxdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce);
} }
getCachedGateways(): Promise<GatewayBond[]> { getCachedGateways(): Promise<GatewayBond[]> {
+21 -21
View File
@@ -14,7 +14,7 @@ import { ChangeAdminResult } from '@cosmjs/cosmwasm-stargate/build/signingcosmwa
import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx'; import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
import { nymGasPrice } from './stargate-helper'; import { nymGasPrice } from './stargate-helper';
import { IQueryClient } from './query-client'; import { IQueryClient } from './query-client';
import NymdQuerier from './nymd-querier'; import NyxdQuerier from './nyxd-querier';
import { import {
ContractStateParams, ContractStateParams,
Delegation, Delegation,
@@ -197,7 +197,7 @@ export interface ISigningClient extends IQueryClient, ICosmWasmSigning, INymSign
} }
export default class SigningClient extends SigningCosmWasmClient implements ISigningClient { export default class SigningClient extends SigningCosmWasmClient implements ISigningClient {
private nymdQuerier: NymdQuerier; private nyxdQuerier: NyxdQuerier;
private nymApiQuerier: NymApiQuerier; private nymApiQuerier: NymApiQuerier;
@@ -212,13 +212,13 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
) { ) {
super(tmClient, wallet, signerOptions); super(tmClient, wallet, signerOptions);
this.clientAddress = clientAddress; this.clientAddress = clientAddress;
this.nymdQuerier = new NymdQuerier(this); this.nyxdQuerier = new NyxdQuerier(this);
this.nymApiQuerier = new NymApiQuerier(nymApiUrl); this.nymApiQuerier = new NymApiQuerier(nymApiUrl);
} }
public static async connectWithNymSigner( public static async connectWithNymSigner(
wallet: DirectSecp256k1HdWallet, wallet: DirectSecp256k1HdWallet,
nymdUrl: string, nyxdUrl: string,
nymApiUrl: string, nymApiUrl: string,
prefix: string, prefix: string,
denom: string, denom: string,
@@ -228,34 +228,34 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
prefix, prefix,
gasPrice: nymGasPrice(denom), gasPrice: nymGasPrice(denom),
}; };
const tmClient = await Tendermint34Client.connect(nymdUrl); const tmClient = await Tendermint34Client.connect(nyxdUrl);
return new SigningClient(address, nymApiUrl, tmClient, wallet, signerOptions); return new SigningClient(address, nymApiUrl, tmClient, wallet, signerOptions);
} }
// query related: // query related:
getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion> { getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion> {
return this.nymdQuerier.getContractVersion(mixnetContractAddress); return this.nyxdQuerier.getContractVersion(mixnetContractAddress);
} }
getMixNodesPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedMixnodeResponse> { getMixNodesPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedMixnodeResponse> {
return this.nymdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter); return this.nyxdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter);
} }
getGatewaysPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedGatewayResponse> { getGatewaysPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedGatewayResponse> {
return this.nymdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter); return this.nyxdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter);
} }
ownsMixNode(mixnetContractAddress: string, address: string): Promise<MixOwnershipResponse> { ownsMixNode(mixnetContractAddress: string, address: string): Promise<MixOwnershipResponse> {
return this.nymdQuerier.ownsMixNode(mixnetContractAddress, address); return this.nyxdQuerier.ownsMixNode(mixnetContractAddress, address);
} }
ownsGateway(mixnetContractAddress: string, address: string): Promise<GatewayOwnershipResponse> { ownsGateway(mixnetContractAddress: string, address: string): Promise<GatewayOwnershipResponse> {
return this.nymdQuerier.ownsGateway(mixnetContractAddress, address); return this.nyxdQuerier.ownsGateway(mixnetContractAddress, address);
} }
getStateParams(mixnetContractAddress: string): Promise<ContractStateParams> { getStateParams(mixnetContractAddress: string): Promise<ContractStateParams> {
return this.nymdQuerier.getStateParams(mixnetContractAddress); return this.nyxdQuerier.getStateParams(mixnetContractAddress);
} }
getAllNetworkDelegationsPaged( getAllNetworkDelegationsPaged(
@@ -263,7 +263,7 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
limit?: number, limit?: number,
startAfter?: [string, string], startAfter?: [string, string],
): Promise<PagedAllDelegationsResponse> { ): Promise<PagedAllDelegationsResponse> {
return this.nymdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter); return this.nyxdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter);
} }
getMixNodeDelegationsPaged( getMixNodeDelegationsPaged(
@@ -272,7 +272,7 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
limit?: number, limit?: number,
startAfter?: string, startAfter?: string,
): Promise<PagedMixDelegationsResponse> { ): Promise<PagedMixDelegationsResponse> {
return this.nymdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter); return this.nyxdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter);
} }
getDelegatorDelegationsPaged( getDelegatorDelegationsPaged(
@@ -281,31 +281,31 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
limit?: number, limit?: number,
startAfter?: string, startAfter?: string,
): Promise<PagedDelegatorDelegationsResponse> { ): Promise<PagedDelegatorDelegationsResponse> {
return this.nymdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter); return this.nyxdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter);
} }
getDelegationDetails(mixnetContractAddress: string, mixIdentity: string, delegator: string): Promise<Delegation> { getDelegationDetails(mixnetContractAddress: string, mixIdentity: string, delegator: string): Promise<Delegation> {
return this.nymdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator); return this.nyxdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator);
} }
getLayerDistribution(mixnetContractAddress: string): Promise<LayerDistribution> { getLayerDistribution(mixnetContractAddress: string): Promise<LayerDistribution> {
return this.nymdQuerier.getLayerDistribution(mixnetContractAddress); return this.nyxdQuerier.getLayerDistribution(mixnetContractAddress);
} }
getRewardPool(mixnetContractAddress: string): Promise<string> { getRewardPool(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getRewardPool(mixnetContractAddress); return this.nyxdQuerier.getRewardPool(mixnetContractAddress);
} }
getCirculatingSupply(mixnetContractAddress: string): Promise<string> { getCirculatingSupply(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getCirculatingSupply(mixnetContractAddress); return this.nyxdQuerier.getCirculatingSupply(mixnetContractAddress);
} }
getIntervalRewardPercent(mixnetContractAddress: string): Promise<number> { getIntervalRewardPercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getIntervalRewardPercent(mixnetContractAddress); return this.nyxdQuerier.getIntervalRewardPercent(mixnetContractAddress);
} }
getSybilResistancePercent(mixnetContractAddress: string): Promise<number> { getSybilResistancePercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getSybilResistancePercent(mixnetContractAddress); return this.nyxdQuerier.getSybilResistancePercent(mixnetContractAddress);
} }
getRewardingStatus( getRewardingStatus(
@@ -313,7 +313,7 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
mixIdentity: string, mixIdentity: string,
rewardingIntervalNonce: number, rewardingIntervalNonce: number,
): Promise<RewardingStatus> { ): Promise<RewardingStatus> {
return this.nymdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce); return this.nyxdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce);
} }
getCachedGateways(): Promise<GatewayBond[]> { getCachedGateways(): Promise<GatewayBond[]> {
+1 -1
View File
@@ -6,7 +6,7 @@ use wasm_bindgen::prelude::*;
#[wasm_bindgen] #[wasm_bindgen]
pub async fn get_gateway(api_server: String, preferred: Option<String>) -> GatewayEndpointConfig { pub async fn get_gateway(api_server: String, preferred: Option<String>) -> GatewayEndpointConfig {
let validator_client = validator_client::client::ApiClient::new(api_server.parse().unwrap()); let validator_client = validator_client::client::NymApiClient::new(api_server.parse().unwrap());
let gateways = match validator_client.get_cached_gateways().await { let gateways = match validator_client.get_cached_gateways().await {
Err(err) => panic!("failed to obtain list of all gateways - {err}"), Err(err) => panic!("failed to obtain list of all gateways - {err}"),
@@ -31,7 +31,7 @@ coconut-interface = { path = "../../coconut-interface" }
network-defaults = { path = "../../network-defaults" } network-defaults = { path = "../../network-defaults" }
nym-api-requests = { path = "../../../nym-api/nym-api-requests", features = ["coconut"] } nym-api-requests = { path = "../../../nym-api/nym-api-requests", features = ["coconut"] }
# required for nymd-client # required for nyxd-client
# at some point it might be possible to make it wasm-compatible # at some point it might be possible to make it wasm-compatible
# perhaps after https://github.com/cosmos/cosmos-rust/pull/97 is resolved (and tendermint-rs is updated) # perhaps after https://github.com/cosmos/cosmos-rust/pull/97 is resolved (and tendermint-rs is updated)
async-trait = { version = "0.1.51", optional = true } async-trait = { version = "0.1.51", optional = true }
@@ -50,7 +50,7 @@ execute = { path = "../../execute" }
ts-rs = "6.1.2" ts-rs = "6.1.2"
[features] [features]
nymd-client = [ nyxd-client = [
"async-trait", "async-trait",
"bip39", "bip39",
"config", "config",
@@ -15,41 +15,41 @@ use nym_api_requests::models::{
RewardEstimationResponse, StakeSaturationResponse, RewardEstimationResponse, StakeSaturationResponse,
}; };
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
use crate::nymd::traits::{DkgQueryClient, MixnetQueryClient, MultisigQueryClient}; use crate::nyxd::traits::{DkgQueryClient, MixnetQueryClient, MultisigQueryClient};
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
use crate::nymd::{self, CosmWasmClient, NymdClient, QueryNymdClient, SigningNymdClient}; use crate::nyxd::{self, CosmWasmClient, NyxdClient, QueryNyxdClient, SigningNyxdClient};
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
use coconut_dkg_common::{ use coconut_dkg_common::{
dealer::ContractDealing, types::DealerDetails, verification_key::ContractVKShare, dealer::ContractDealing, types::DealerDetails, verification_key::ContractVKShare,
}; };
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
use coconut_interface::Base58; use coconut_interface::Base58;
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
use cw3::ProposalResponse; use cw3::ProposalResponse;
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
use mixnet_contract_common::{ use mixnet_contract_common::{
families::{Family, FamilyHead}, families::{Family, FamilyHead},
mixnode::MixNodeBond, mixnode::MixNodeBond,
pending_events::{PendingEpochEvent, PendingIntervalEvent}, pending_events::{PendingEpochEvent, PendingIntervalEvent},
Delegation, IdentityKey, RewardedSetNodeStatus, UnbondedMixnode, Delegation, IdentityKey, RewardedSetNodeStatus, UnbondedMixnode,
}; };
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
use network_defaults::NymNetworkDetails; use network_defaults::NymNetworkDetails;
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
use nym_api_requests::models::MixNodeBondAnnotated; use nym_api_requests::models::MixNodeBondAnnotated;
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
use std::str::FromStr; use std::str::FromStr;
use url::Url; use url::Url;
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
#[must_use] #[must_use]
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Config { pub struct Config {
api_url: Url, api_url: Url,
nymd_url: Url, nyxd_url: Url,
nymd_config: nymd::Config, nyxd_config: nyxd::Config,
mixnode_page_limit: Option<u32>, mixnode_page_limit: Option<u32>,
gateway_page_limit: Option<u32>, gateway_page_limit: Option<u32>,
@@ -60,7 +60,7 @@ pub struct Config {
proposals_page_limit: Option<u32>, proposals_page_limit: Option<u32>,
} }
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
impl Config { impl Config {
pub fn try_from_nym_network_details( pub fn try_from_nym_network_details(
details: &NymNetworkDetails, details: &NymNetworkDetails,
@@ -78,11 +78,11 @@ impl Config {
Ok(Config { Ok(Config {
api_url: api_url.pop().unwrap(), api_url: api_url.pop().unwrap(),
nymd_url: details.endpoints[0] nyxd_url: details.endpoints[0]
.nymd_url .nyxd_url
.parse() .parse()
.map_err(ValidatorClientError::MalformedUrlProvided)?, .map_err(ValidatorClientError::MalformedUrlProvided)?,
nymd_config: nymd::Config::try_from_nym_network_details(details)?, nyxd_config: nyxd::Config::try_from_nym_network_details(details)?,
mixnode_page_limit: None, mixnode_page_limit: None,
gateway_page_limit: None, gateway_page_limit: None,
mixnode_delegations_page_limit: None, mixnode_delegations_page_limit: None,
@@ -95,14 +95,14 @@ impl Config {
// TODO: this method shouldn't really exist as all information should be included immediately // TODO: this method shouldn't really exist as all information should be included immediately
// via `from_nym_network_details`, but it's here for, you guessed it, legacy compatibility // via `from_nym_network_details`, but it's here for, you guessed it, legacy compatibility
pub fn with_urls(mut self, nymd_url: Url, api_url: Url) -> Self { pub fn with_urls(mut self, nyxd_url: Url, api_url: Url) -> Self {
self.nymd_url = nymd_url; self.nyxd_url = nyxd_url;
self.api_url = api_url; self.api_url = api_url;
self self
} }
pub fn with_nymd_url(mut self, nymd_url: Url) -> Self { pub fn with_nyxd_url(mut self, nyxd_url: Url) -> Self {
self.nymd_url = nymd_url; self.nyxd_url = nyxd_url;
self self
} }
@@ -127,7 +127,7 @@ impl Config {
} }
} }
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
pub struct Client<C> { pub struct Client<C> {
// TODO: we really shouldn't be storing a mnemonic here, but removing it would be // TODO: we really shouldn't be storing a mnemonic here, but removing it would be
// non-trivial amount of work and it's out of scope of the current branch // non-trivial amount of work and it's out of scope of the current branch
@@ -143,19 +143,19 @@ pub struct Client<C> {
// ideally they would have been read-only, but unfortunately rust doesn't have such features // ideally they would have been read-only, but unfortunately rust doesn't have such features
pub nym_api: nym_api::Client, pub nym_api: nym_api::Client,
pub nymd: NymdClient<C>, pub nyxd: NyxdClient<C>,
} }
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
impl Client<SigningNymdClient> { impl Client<SigningNyxdClient> {
pub fn new_signing( pub fn new_signing(
config: Config, config: Config,
mnemonic: bip39::Mnemonic, mnemonic: bip39::Mnemonic,
) -> Result<Client<SigningNymdClient>, ValidatorClientError> { ) -> Result<Client<SigningNyxdClient>, ValidatorClientError> {
let nym_api_client = nym_api::Client::new(config.api_url.clone()); let nym_api_client = nym_api::Client::new(config.api_url.clone());
let nymd_client = NymdClient::connect_with_mnemonic( let nyxd_client = NyxdClient::connect_with_mnemonic(
config.nymd_config.clone(), config.nyxd_config.clone(),
config.nymd_url.as_str(), config.nyxd_url.as_str(),
mnemonic.clone(), mnemonic.clone(),
None, None,
)?; )?;
@@ -170,13 +170,13 @@ impl Client<SigningNymdClient> {
verification_key_page_limit: config.verification_key_page_limit, verification_key_page_limit: config.verification_key_page_limit,
proposals_page_limit: config.proposals_page_limit, proposals_page_limit: config.proposals_page_limit,
nym_api: nym_api_client, nym_api: nym_api_client,
nymd: nymd_client, nyxd: nyxd_client,
}) })
} }
pub fn change_nymd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> { pub fn change_nyxd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> {
self.nymd = NymdClient::connect_with_mnemonic( self.nyxd = NyxdClient::connect_with_mnemonic(
self.nymd.current_config().clone(), self.nyxd.current_config().clone(),
new_endpoint.as_ref(), new_endpoint.as_ref(),
self.mnemonic.clone().unwrap(), self.mnemonic.clone().unwrap(),
None, None,
@@ -184,17 +184,17 @@ impl Client<SigningNymdClient> {
Ok(()) Ok(())
} }
pub fn set_nymd_simulated_gas_multiplier(&mut self, multiplier: f32) { pub fn set_nyxd_simulated_gas_multiplier(&mut self, multiplier: f32) {
self.nymd.set_simulated_gas_multiplier(multiplier) self.nyxd.set_simulated_gas_multiplier(multiplier)
} }
} }
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
impl Client<QueryNymdClient> { impl Client<QueryNyxdClient> {
pub fn new_query(config: Config) -> Result<Client<QueryNymdClient>, ValidatorClientError> { pub fn new_query(config: Config) -> Result<Client<QueryNyxdClient>, ValidatorClientError> {
let nym_api_client = nym_api::Client::new(config.api_url.clone()); let nym_api_client = nym_api::Client::new(config.api_url.clone());
let nymd_client = let nyxd_client =
NymdClient::connect(config.nymd_config.clone(), config.nymd_url.as_str())?; NyxdClient::connect(config.nyxd_config.clone(), config.nyxd_url.as_str())?;
Ok(Client { Ok(Client {
mnemonic: None, mnemonic: None,
@@ -206,29 +206,29 @@ impl Client<QueryNymdClient> {
verification_key_page_limit: config.verification_key_page_limit, verification_key_page_limit: config.verification_key_page_limit,
proposals_page_limit: config.proposals_page_limit, proposals_page_limit: config.proposals_page_limit,
nym_api: nym_api_client, nym_api: nym_api_client,
nymd: nymd_client, nyxd: nyxd_client,
}) })
} }
pub fn change_nymd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> { pub fn change_nyxd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> {
self.nymd = NymdClient::connect(self.nymd.current_config().clone(), new_endpoint.as_ref())?; self.nyxd = NyxdClient::connect(self.nyxd.current_config().clone(), new_endpoint.as_ref())?;
Ok(()) Ok(())
} }
} }
// nymd wrappers // nyxd wrappers
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
impl<C> Client<C> { impl<C> Client<C> {
// use case: somebody initialised client without a contract in order to upload and initialise one // use case: somebody initialised client without a contract in order to upload and initialise one
// and now they want to actually use it without making new client // and now they want to actually use it without making new client
pub fn set_mixnet_contract_address(&mut self, mixnet_contract_address: cosmrs::AccountId) { pub fn set_mixnet_contract_address(&mut self, mixnet_contract_address: cosmrs::AccountId) {
self.nymd self.nyxd
.set_mixnet_contract_address(mixnet_contract_address) .set_mixnet_contract_address(mixnet_contract_address)
} }
pub fn get_mixnet_contract_address(&self) -> cosmrs::AccountId { pub fn get_mixnet_contract_address(&self) -> cosmrs::AccountId {
self.nymd.mixnet_contract_address().clone() self.nyxd.mixnet_contract_address().clone()
} }
pub async fn get_all_node_families(&self) -> Result<Vec<Family>, ValidatorClientError> pub async fn get_all_node_families(&self) -> Result<Vec<Family>, ValidatorClientError>
@@ -240,7 +240,7 @@ impl<C> Client<C> {
loop { loop {
let paged_response = self let paged_response = self
.nymd .nyxd
.get_all_node_families_paged(start_after.take(), None) .get_all_node_families_paged(start_after.take(), None)
.await?; .await?;
families.extend(paged_response.families); families.extend(paged_response.families);
@@ -266,7 +266,7 @@ impl<C> Client<C> {
loop { loop {
let paged_response = self let paged_response = self
.nymd .nyxd
.get_all_family_members_paged(start_after.take(), None) .get_all_family_members_paged(start_after.take(), None)
.await?; .await?;
members.extend(paged_response.members); members.extend(paged_response.members);
@@ -282,7 +282,7 @@ impl<C> Client<C> {
} }
// basically handles paging for us // basically handles paging for us
pub async fn get_all_nymd_rewarded_set_mixnodes( pub async fn get_all_nyxd_rewarded_set_mixnodes(
&self, &self,
) -> Result<Vec<(MixId, RewardedSetNodeStatus)>, ValidatorClientError> ) -> Result<Vec<(MixId, RewardedSetNodeStatus)>, ValidatorClientError>
where where
@@ -293,7 +293,7 @@ impl<C> Client<C> {
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_rewarded_set_paged(start_after.take(), self.rewarded_set_page_limit) .get_rewarded_set_paged(start_after.take(), self.rewarded_set_page_limit)
.await?; .await?;
identities.append(&mut paged_response.nodes); identities.append(&mut paged_response.nodes);
@@ -308,7 +308,7 @@ impl<C> Client<C> {
Ok(identities) Ok(identities)
} }
pub async fn get_all_nymd_mixnode_bonds(&self) -> Result<Vec<MixNodeBond>, ValidatorClientError> pub async fn get_all_nyxd_mixnode_bonds(&self) -> Result<Vec<MixNodeBond>, ValidatorClientError>
where where
C: CosmWasmClient + Sync + Send, C: CosmWasmClient + Sync + Send,
{ {
@@ -316,7 +316,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_mixnode_bonds_paged(self.mixnode_page_limit, start_after.take()) .get_mixnode_bonds_paged(self.mixnode_page_limit, start_after.take())
.await?; .await?;
mixnodes.append(&mut paged_response.nodes); mixnodes.append(&mut paged_response.nodes);
@@ -331,7 +331,7 @@ impl<C> Client<C> {
Ok(mixnodes) Ok(mixnodes)
} }
pub async fn get_all_nymd_mixnodes_detailed( pub async fn get_all_nyxd_mixnodes_detailed(
&self, &self,
) -> Result<Vec<MixNodeDetails>, ValidatorClientError> ) -> Result<Vec<MixNodeDetails>, ValidatorClientError>
where where
@@ -341,7 +341,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_mixnodes_detailed_paged(self.mixnode_page_limit, start_after.take()) .get_mixnodes_detailed_paged(self.mixnode_page_limit, start_after.take())
.await?; .await?;
mixnodes.append(&mut paged_response.nodes); mixnodes.append(&mut paged_response.nodes);
@@ -356,7 +356,7 @@ impl<C> Client<C> {
Ok(mixnodes) Ok(mixnodes)
} }
pub async fn get_all_nymd_unbonded_mixnodes( pub async fn get_all_nyxd_unbonded_mixnodes(
&self, &self,
) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError> ) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError>
where where
@@ -366,7 +366,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_unbonded_paged(self.mixnode_page_limit, start_after.take()) .get_unbonded_paged(self.mixnode_page_limit, start_after.take())
.await?; .await?;
mixnodes.append(&mut paged_response.nodes); mixnodes.append(&mut paged_response.nodes);
@@ -381,7 +381,7 @@ impl<C> Client<C> {
Ok(mixnodes) Ok(mixnodes)
} }
pub async fn get_all_nymd_unbonded_mixnodes_by_owner( pub async fn get_all_nyxd_unbonded_mixnodes_by_owner(
&self, &self,
owner: &cosmrs::AccountId, owner: &cosmrs::AccountId,
) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError> ) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError>
@@ -392,7 +392,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_unbonded_by_owner_paged(owner, self.mixnode_page_limit, start_after.take()) .get_unbonded_by_owner_paged(owner, self.mixnode_page_limit, start_after.take())
.await?; .await?;
mixnodes.append(&mut paged_response.nodes); mixnodes.append(&mut paged_response.nodes);
@@ -407,7 +407,7 @@ impl<C> Client<C> {
Ok(mixnodes) Ok(mixnodes)
} }
pub async fn get_all_nymd_unbonded_mixnodes_by_identity( pub async fn get_all_nyxd_unbonded_mixnodes_by_identity(
&self, &self,
identity_key: String, identity_key: String,
) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError> ) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError>
@@ -418,7 +418,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_unbonded_by_identity_paged( .get_unbonded_by_identity_paged(
identity_key.clone(), identity_key.clone(),
self.mixnode_page_limit, self.mixnode_page_limit,
@@ -437,7 +437,7 @@ impl<C> Client<C> {
Ok(mixnodes) Ok(mixnodes)
} }
pub async fn get_all_nymd_gateways(&self) -> Result<Vec<GatewayBond>, ValidatorClientError> pub async fn get_all_nyxd_gateways(&self) -> Result<Vec<GatewayBond>, ValidatorClientError>
where where
C: CosmWasmClient + Sync + Send, C: CosmWasmClient + Sync + Send,
{ {
@@ -445,7 +445,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_gateways_paged(start_after.take(), self.gateway_page_limit) .get_gateways_paged(start_after.take(), self.gateway_page_limit)
.await?; .await?;
gateways.append(&mut paged_response.nodes); gateways.append(&mut paged_response.nodes);
@@ -460,7 +460,7 @@ impl<C> Client<C> {
Ok(gateways) Ok(gateways)
} }
pub async fn get_all_nymd_single_mixnode_delegations( pub async fn get_all_nyxd_single_mixnode_delegations(
&self, &self,
mix_id: MixId, mix_id: MixId,
) -> Result<Vec<Delegation>, ValidatorClientError> ) -> Result<Vec<Delegation>, ValidatorClientError>
@@ -471,7 +471,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_mixnode_delegations_paged( .get_mixnode_delegations_paged(
mix_id, mix_id,
start_after.take(), start_after.take(),
@@ -501,7 +501,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_delegator_delegations_paged( .get_delegator_delegations_paged(
delegation_owner.to_string(), delegation_owner.to_string(),
start_after.take(), start_after.take(),
@@ -528,7 +528,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_all_network_delegations_paged( .get_all_network_delegations_paged(
start_after.take(), start_after.take(),
self.mixnode_delegations_page_limit, self.mixnode_delegations_page_limit,
@@ -546,7 +546,7 @@ impl<C> Client<C> {
Ok(delegations) Ok(delegations)
} }
pub async fn get_all_nymd_pending_epoch_events( pub async fn get_all_nyxd_pending_epoch_events(
&self, &self,
) -> Result<Vec<PendingEpochEvent>, ValidatorClientError> ) -> Result<Vec<PendingEpochEvent>, ValidatorClientError>
where where
@@ -557,7 +557,7 @@ impl<C> Client<C> {
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_pending_epoch_events_paged(start_after.take(), self.rewarded_set_page_limit) .get_pending_epoch_events_paged(start_after.take(), self.rewarded_set_page_limit)
.await?; .await?;
events.append(&mut paged_response.events); events.append(&mut paged_response.events);
@@ -572,7 +572,7 @@ impl<C> Client<C> {
Ok(events) Ok(events)
} }
pub async fn get_all_nymd_pending_interval_events( pub async fn get_all_nyxd_pending_interval_events(
&self, &self,
) -> Result<Vec<PendingIntervalEvent>, ValidatorClientError> ) -> Result<Vec<PendingIntervalEvent>, ValidatorClientError>
where where
@@ -583,7 +583,7 @@ impl<C> Client<C> {
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_pending_interval_events_paged(start_after.take(), self.rewarded_set_page_limit) .get_pending_interval_events_paged(start_after.take(), self.rewarded_set_page_limit)
.await?; .await?;
events.append(&mut paged_response.events); events.append(&mut paged_response.events);
@@ -598,7 +598,7 @@ impl<C> Client<C> {
Ok(events) Ok(events)
} }
pub async fn get_all_nymd_current_dealers( pub async fn get_all_nyxd_current_dealers(
&self, &self,
) -> Result<Vec<DealerDetails>, ValidatorClientError> ) -> Result<Vec<DealerDetails>, ValidatorClientError>
where where
@@ -608,7 +608,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_current_dealers_paged(start_after.take(), self.dealers_page_limit) .get_current_dealers_paged(start_after.take(), self.dealers_page_limit)
.await?; .await?;
dealers.append(&mut paged_response.dealers); dealers.append(&mut paged_response.dealers);
@@ -623,7 +623,7 @@ impl<C> Client<C> {
Ok(dealers) Ok(dealers)
} }
pub async fn get_all_nymd_past_dealers( pub async fn get_all_nyxd_past_dealers(
&self, &self,
) -> Result<Vec<DealerDetails>, ValidatorClientError> ) -> Result<Vec<DealerDetails>, ValidatorClientError>
where where
@@ -633,7 +633,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_past_dealers_paged(start_after.take(), self.dealers_page_limit) .get_past_dealers_paged(start_after.take(), self.dealers_page_limit)
.await?; .await?;
dealers.append(&mut paged_response.dealers); dealers.append(&mut paged_response.dealers);
@@ -648,7 +648,7 @@ impl<C> Client<C> {
Ok(dealers) Ok(dealers)
} }
pub async fn get_all_nymd_epoch_dealings( pub async fn get_all_nyxd_epoch_dealings(
&self, &self,
idx: usize, idx: usize,
) -> Result<Vec<ContractDealing>, ValidatorClientError> ) -> Result<Vec<ContractDealing>, ValidatorClientError>
@@ -659,7 +659,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_dealings_paged(idx, start_after.take(), self.dealers_page_limit) .get_dealings_paged(idx, start_after.take(), self.dealers_page_limit)
.await?; .await?;
dealings.append(&mut paged_response.dealings); dealings.append(&mut paged_response.dealings);
@@ -674,7 +674,7 @@ impl<C> Client<C> {
Ok(dealings) Ok(dealings)
} }
pub async fn get_all_nymd_verification_key_shares( pub async fn get_all_nyxd_verification_key_shares(
&self, &self,
) -> Result<Vec<ContractVKShare>, ValidatorClientError> ) -> Result<Vec<ContractVKShare>, ValidatorClientError>
where where
@@ -684,7 +684,7 @@ impl<C> Client<C> {
let mut start_after = None; let mut start_after = None;
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.get_vk_shares_paged(start_after.take(), self.verification_key_page_limit) .get_vk_shares_paged(start_after.take(), self.verification_key_page_limit)
.await?; .await?;
shares.append(&mut paged_response.shares); shares.append(&mut paged_response.shares);
@@ -699,7 +699,7 @@ impl<C> Client<C> {
Ok(shares) Ok(shares)
} }
pub async fn get_all_nymd_proposals( pub async fn get_all_nyxd_proposals(
&self, &self,
) -> Result<Vec<ProposalResponse>, ValidatorClientError> ) -> Result<Vec<ProposalResponse>, ValidatorClientError>
where where
@@ -710,7 +710,7 @@ impl<C> Client<C> {
loop { loop {
let mut paged_response = self let mut paged_response = self
.nymd .nyxd
.list_proposals(start_after.take(), self.proposals_page_limit) .list_proposals(start_after.take(), self.proposals_page_limit)
.await?; .await?;
@@ -729,7 +729,7 @@ impl<C> Client<C> {
} }
// validator-api wrappers // validator-api wrappers
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
impl<C> Client<C> { impl<C> Client<C> {
pub fn change_nym_api(&mut self, new_endpoint: Url) { pub fn change_nym_api(&mut self, new_endpoint: Url) {
self.nym_api.change_url(new_endpoint) self.nym_api.change_url(new_endpoint)
@@ -783,23 +783,23 @@ impl<C> Client<C> {
#[derive(Clone)] #[derive(Clone)]
pub struct CoconutApiClient { pub struct CoconutApiClient {
pub api_client: ApiClient, pub api_client: NymApiClient,
pub verification_key: VerificationKey, pub verification_key: VerificationKey,
pub node_id: NodeIndex, pub node_id: NodeIndex,
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
pub cosmos_address: cosmrs::AccountId, pub cosmos_address: cosmrs::AccountId,
} }
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
impl CoconutApiClient { impl CoconutApiClient {
pub async fn all_coconut_api_clients<C>( pub async fn all_coconut_api_clients<C>(
nymd_client: &Client<C>, nyxd_client: &Client<C>,
) -> Result<Vec<Self>, ValidatorClientError> ) -> Result<Vec<Self>, ValidatorClientError>
where where
C: CosmWasmClient + Sync + Send, C: CosmWasmClient + Sync + Send,
{ {
Ok(nymd_client Ok(nyxd_client
.get_all_nymd_verification_key_shares() .get_all_nyxd_verification_key_shares()
.await? .await?
.into_iter() .into_iter()
.filter_map(Self::try_from) .filter_map(Self::try_from)
@@ -812,7 +812,7 @@ impl CoconutApiClient {
if let Ok(verification_key) = VerificationKey::try_from_bs58(&share.share) { if let Ok(verification_key) = VerificationKey::try_from_bs58(&share.share) {
if let Ok(cosmos_address) = cosmrs::AccountId::from_str(share.owner.as_str()) { if let Ok(cosmos_address) = cosmrs::AccountId::from_str(share.owner.as_str()) {
return Some(CoconutApiClient { return Some(CoconutApiClient {
api_client: ApiClient::new(url_address), api_client: NymApiClient::new(url_address),
verification_key, verification_key,
node_id: share.node_index, node_id: share.node_index,
cosmos_address, cosmos_address,
@@ -826,17 +826,17 @@ impl CoconutApiClient {
} }
#[derive(Clone)] #[derive(Clone)]
pub struct ApiClient { pub struct NymApiClient {
pub nym_api_client: nym_api::Client, pub nym_api_client: nym_api::Client,
// TODO: perhaps if we really need it at some (currently I don't see any reasons for it) // TODO: perhaps if we really need it at some (currently I don't see any reasons for it)
// we could re-implement the communication with the REST API on port 1317 // we could re-implement the communication with the REST API on port 1317
} }
impl ApiClient { impl NymApiClient {
pub fn new(api_url: Url) -> Self { pub fn new(api_url: Url) -> Self {
let nym_api_client = nym_api::Client::new(api_url); let nym_api_client = nym_api::Client::new(api_url);
ApiClient { nym_api_client } NymApiClient { nym_api_client }
} }
pub fn change_nym_api(&mut self, new_endpoint: Url) { pub fn change_nym_api(&mut self, new_endpoint: Url) {
@@ -1,8 +1,8 @@
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::{Config as ClientConfig, NymdClient, QueryNymdClient}; use crate::nyxd::{Config as ClientConfig, NyxdClient, QueryNyxdClient};
use crate::ApiClient; use crate::NymApiClient;
use crate::nymd::traits::MixnetQueryClient; use crate::nyxd::traits::MixnetQueryClient;
use colored::Colorize; use colored::Colorize;
use core::fmt; use core::fmt;
use itertools::Itertools; use itertools::Itertools;
@@ -16,9 +16,9 @@ use url::Url;
const MAX_URLS_TESTED: usize = 200; const MAX_URLS_TESTED: usize = 200;
const CONNECTION_TEST_TIMEOUT_SEC: u64 = 2; const CONNECTION_TEST_TIMEOUT_SEC: u64 = 2;
// Run connection tests for all specified nymd and api urls. These are all run concurrently. /// Run connection tests for all specified nyxd and api urls. These are all run concurrently.
pub async fn run_validator_connection_test<H: BuildHasher + 'static>( pub async fn run_validator_connection_test<H: BuildHasher + 'static>(
nymd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>, nyxd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
api_urls: impl Iterator<Item = (NymNetworkDetails, Url)>, api_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
mixnet_contract_address: HashMap<NymNetworkDetails, cosmrs::AccountId, H>, mixnet_contract_address: HashMap<NymNetworkDetails, cosmrs::AccountId, H>,
) -> ( ) -> (
@@ -27,7 +27,7 @@ pub async fn run_validator_connection_test<H: BuildHasher + 'static>(
) { ) {
// Setup all the clients for the connection tests // Setup all the clients for the connection tests
let connection_test_clients = let connection_test_clients =
setup_connection_tests(nymd_urls, api_urls, mixnet_contract_address); setup_connection_tests(nyxd_urls, api_urls, mixnet_contract_address);
// Run all tests concurrently // Run all tests concurrently
let connection_results = futures::future::join_all( let connection_results = futures::future::join_all(
@@ -40,28 +40,28 @@ pub async fn run_validator_connection_test<H: BuildHasher + 'static>(
// Seperate and collect results into HashMaps // Seperate and collect results into HashMaps
( (
extract_and_collect_results_into_map(&connection_results, &UrlType::Nymd), extract_and_collect_results_into_map(&connection_results, &UrlType::Nyxd),
extract_and_collect_results_into_map(&connection_results, &UrlType::Api), extract_and_collect_results_into_map(&connection_results, &UrlType::NymApi),
) )
} }
fn setup_connection_tests<H: BuildHasher + 'static>( fn setup_connection_tests<H: BuildHasher + 'static>(
nymd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>, nyxd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
api_urls: impl Iterator<Item = (NymNetworkDetails, Url)>, api_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
mixnet_contract_address: HashMap<NymNetworkDetails, cosmrs::AccountId, H>, mixnet_contract_address: HashMap<NymNetworkDetails, cosmrs::AccountId, H>,
) -> impl Iterator<Item = ClientForConnectionTest> { ) -> impl Iterator<Item = ClientForConnectionTest> {
let nymd_connection_test_clients = nymd_urls.filter_map(move |(network, url)| { let nyxd_connection_test_clients = nyxd_urls.filter_map(move |(network, url)| {
let address = mixnet_contract_address let address = mixnet_contract_address
.get(&network) .get(&network)
.expect("No configured contract address") .expect("No configured contract address")
.clone(); .clone();
let config = ClientConfig::try_from_nym_network_details(&network) let config = ClientConfig::try_from_nym_network_details(&network)
.expect("failed to create valid nymd client config"); .expect("failed to create valid nyxd client config");
if let Ok(mut client) = NymdClient::<QueryNymdClient>::connect(config, url.as_str()) { if let Ok(mut client) = NyxdClient::<QueryNyxdClient>::connect(config, url.as_str()) {
// possibly redundant, but lets just leave it here // possibly redundant, but lets just leave it here
client.set_mixnet_contract_address(address); client.set_mixnet_contract_address(address);
Some(ClientForConnectionTest::Nymd( Some(ClientForConnectionTest::Nyxd(
network, network,
url, url,
Box::new(client), Box::new(client),
@@ -72,10 +72,10 @@ fn setup_connection_tests<H: BuildHasher + 'static>(
}); });
let api_connection_test_clients = api_urls.map(|(network, url)| { let api_connection_test_clients = api_urls.map(|(network, url)| {
ClientForConnectionTest::Api(network, url.clone(), ApiClient::new(url)) ClientForConnectionTest::Api(network, url.clone(), NymApiClient::new(url))
}); });
nymd_connection_test_clients.chain(api_connection_test_clients) nyxd_connection_test_clients.chain(api_connection_test_clients)
} }
fn extract_and_collect_results_into_map( fn extract_and_collect_results_into_map(
@@ -92,10 +92,10 @@ fn extract_and_collect_results_into_map(
.into_group_map() .into_group_map()
} }
async fn test_nymd_connection( async fn test_nyxd_connection(
network: NymNetworkDetails, network: NymNetworkDetails,
url: &Url, url: &Url,
client: &NymdClient<QueryNymdClient>, client: &NyxdClient<QueryNyxdClient>,
) -> ConnectionResult { ) -> ConnectionResult {
let result = match timeout( let result = match timeout(
Duration::from_secs(CONNECTION_TEST_TIMEOUT_SEC), Duration::from_secs(CONNECTION_TEST_TIMEOUT_SEC),
@@ -103,48 +103,48 @@ async fn test_nymd_connection(
) )
.await .await
{ {
Ok(Err(NymdError::TendermintError(e))) => { Ok(Err(NyxdError::TendermintError(e))) => {
// If we get a tendermint-rpc error, we classify the node as not contactable // If we get a tendermint-rpc error, we classify the node as not contactable
log::debug!("Checking: nymd_url: {url}: {}: {}", "failed".red(), e); log::debug!("Checking: nyxd url: {url}: {}: {}", "failed".red(), e);
false false
} }
Ok(Err(NymdError::AbciError { code, log, .. })) => { Ok(Err(NyxdError::AbciError { code, log, .. })) => {
// We accept the mixnet contract not found as ok from a connection standpoint. This happens // We accept the mixnet contract not found as ok from a connection standpoint. This happens
// for example on a pre-launch network. // for example on a pre-launch network.
log::debug!( log::debug!(
"Checking: nymd_url: {url}: {}, but with abci error: {code}: {log}", "Checking: nyxd url: {url}: {}, but with abci error: {code}: {log}",
"success".green() "success".green()
); );
code == 18 code == 18
} }
Ok(Err(error @ NymdError::NoContractAddressAvailable)) => { Ok(Err(error @ NyxdError::NoContractAddressAvailable)) => {
log::debug!("Checking: nymd_url: {url}: {}: {error}", "failed".red()); log::debug!("Checking: nyxd url: {url}: {}: {error}", "failed".red());
false false
} }
Ok(Err(e)) => { Ok(Err(e)) => {
// For any other error, we're optimistic and just try anyway. // For any other error, we're optimistic and just try anyway.
log::debug!( log::debug!(
"Checking: nymd_url: {url}: {}, but with error: {e}", "Checking: nyxd_url: {url}: {}, but with error: {e}",
"success".green() "success".green()
); );
true true
} }
Ok(Ok(_)) => { Ok(Ok(_)) => {
log::debug!("Checking: nymd_url: {url}: {}", "success".green()); log::debug!("Checking: nyxd_url: {url}: {}", "success".green());
true true
} }
Err(e) => { Err(e) => {
log::debug!("Checking: nymd_url: {url}: {}: {e}", "failed".red()); log::debug!("Checking: nyxd_url: {url}: {}: {e}", "failed".red());
false false
} }
}; };
ConnectionResult::Nymd(network, url.clone(), result) ConnectionResult::Nyxd(network, url.clone(), result)
} }
async fn test_api_connection( async fn test_nym_api_connection(
network: NymNetworkDetails, network: NymNetworkDetails,
url: &Url, url: &Url,
client: &ApiClient, client: &NymApiClient,
) -> ConnectionResult { ) -> ConnectionResult {
let result = match timeout( let result = match timeout(
Duration::from_secs(CONNECTION_TEST_TIMEOUT_SEC), Duration::from_secs(CONNECTION_TEST_TIMEOUT_SEC),
@@ -169,18 +169,18 @@ async fn test_api_connection(
} }
enum ClientForConnectionTest { enum ClientForConnectionTest {
Nymd(NymNetworkDetails, Url, Box<NymdClient<QueryNymdClient>>), Nyxd(NymNetworkDetails, Url, Box<NyxdClient<QueryNyxdClient>>),
Api(NymNetworkDetails, Url, ApiClient), Api(NymNetworkDetails, Url, NymApiClient),
} }
impl ClientForConnectionTest { impl ClientForConnectionTest {
async fn run_connection_check(self) -> ConnectionResult { async fn run_connection_check(self) -> ConnectionResult {
match self { match self {
ClientForConnectionTest::Nymd(network, ref url, ref client) => { ClientForConnectionTest::Nyxd(network, ref url, ref client) => {
test_nymd_connection(network, url, client).await test_nyxd_connection(network, url, client).await
} }
ClientForConnectionTest::Api(network, ref url, ref client) => { ClientForConnectionTest::Api(network, ref url, ref client) => {
test_api_connection(network, url, client).await test_nym_api_connection(network, url, client).await
} }
} }
} }
@@ -188,37 +188,37 @@ impl ClientForConnectionTest {
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
enum UrlType { enum UrlType {
Nymd, Nyxd,
Api, NymApi,
} }
impl fmt::Display for UrlType { impl fmt::Display for UrlType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
UrlType::Nymd => write!(f, "nymd"), UrlType::Nyxd => write!(f, "nyxd"),
UrlType::Api => write!(f, "api"), UrlType::NymApi => write!(f, "api"),
} }
} }
} }
#[derive(Debug)] #[derive(Debug)]
enum ConnectionResult { enum ConnectionResult {
Nymd(NymNetworkDetails, Url, bool), Nyxd(NymNetworkDetails, Url, bool),
Api(NymNetworkDetails, Url, bool), Api(NymNetworkDetails, Url, bool),
} }
impl ConnectionResult { impl ConnectionResult {
fn result(&self) -> (&NymNetworkDetails, &Url, &bool) { fn result(&self) -> (&NymNetworkDetails, &Url, &bool) {
match self { match self {
ConnectionResult::Nymd(network, url, result) ConnectionResult::Nyxd(network, url, result)
| ConnectionResult::Api(network, url, result) => (network, url, result), | ConnectionResult::Api(network, url, result) => (network, url, result),
} }
} }
fn url_type(&self) -> UrlType { fn url_type(&self) -> UrlType {
match self { match self {
ConnectionResult::Nymd(..) => UrlType::Nymd, ConnectionResult::Nyxd(..) => UrlType::Nyxd,
ConnectionResult::Api(..) => UrlType::Api, ConnectionResult::Api(..) => UrlType::NymApi,
} }
} }
} }
@@ -15,9 +15,9 @@ pub enum ValidatorClientError {
#[error("One of the provided URLs was malformed - {0}")] #[error("One of the provided URLs was malformed - {0}")]
MalformedUrlProvided(#[from] url::ParseError), MalformedUrlProvided(#[from] url::ParseError),
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
#[error("There was an issue with the Nymd client - {0}")] #[error("There was an issue with the Nyxd client - {0}")]
NymdError(#[from] crate::nymd::error::NymdError), NyxdError(#[from] crate::nyxd::error::NyxdError),
#[error("No validator API url has been provided")] #[error("No validator API url has been provided")]
NoAPIUrlAvailable, NoAPIUrlAvailable,
@@ -2,17 +2,17 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
pub mod client; pub mod client;
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
pub mod connection_tester; pub mod connection_tester;
mod error; mod error;
pub mod nym_api; pub mod nym_api;
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
pub mod nymd; pub mod nyxd;
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
pub use crate::client::{ApiClient, CoconutApiClient}; pub use crate::client::{CoconutApiClient, NymApiClient};
pub use crate::error::ValidatorClientError; pub use crate::error::ValidatorClientError;
pub use nym_api_requests::*; pub use nym_api_requests::*;
#[cfg(feature = "nymd-client")] #[cfg(feature = "nyxd-client")]
pub use client::{Client, Config}; pub use client::{Client, Config};
@@ -1,14 +1,14 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd; use crate::nyxd;
use crate::nymd::coin::Coin; use crate::nyxd::coin::Coin;
use crate::nymd::cosmwasm_client::helpers::{create_pagination, next_page_key}; use crate::nyxd::cosmwasm_client::helpers::{create_pagination, next_page_key};
use crate::nymd::cosmwasm_client::types::{ use crate::nyxd::cosmwasm_client::types::{
Account, Code, CodeDetails, Contract, ContractCodeHistoryEntry, ContractCodeId, Account, Code, CodeDetails, Contract, ContractCodeHistoryEntry, ContractCodeId,
SequenceResponse, SimulateResponse, SequenceResponse, SimulateResponse,
}; };
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use async_trait::async_trait; use async_trait::async_trait;
use cosmrs::proto::cosmos::auth::v1beta1::{QueryAccountRequest, QueryAccountResponse}; use cosmrs::proto::cosmos::auth::v1beta1::{QueryAccountRequest, QueryAccountResponse};
use cosmrs::proto::cosmos::bank::v1beta1::{ use cosmrs::proto::cosmos::bank::v1beta1::{
@@ -57,7 +57,7 @@ pub trait CosmWasmClient: rpc::Client {
&self, &self,
path: Option<abci::Path>, path: Option<abci::Path>,
req: Req, req: Req,
) -> Result<Res, NymdError> ) -> Result<Res, NyxdError>
where where
Req: Message, Req: Message,
Res: Message + Default, Res: Message + Default,
@@ -66,21 +66,21 @@ pub trait CosmWasmClient: rpc::Client {
req.encode(&mut buf)?; req.encode(&mut buf)?;
let res = self.abci_query(path, buf, None, false).await?; let res = self.abci_query(path, buf, None, false).await?;
let res_success = nymd::error::parse_abci_query_result(res)?; let res_success = nyxd::error::parse_abci_query_result(res)?;
Ok(Res::decode(res_success.value.as_ref())?) Ok(Res::decode(res_success.value.as_ref())?)
} }
async fn get_chain_id(&self) -> Result<chain::Id, NymdError> { async fn get_chain_id(&self) -> Result<chain::Id, NyxdError> {
Ok(self.status().await?.node_info.network) Ok(self.status().await?.node_info.network)
} }
async fn get_height(&self) -> Result<block::Height, NymdError> { async fn get_height(&self) -> Result<block::Height, NyxdError> {
Ok(self.status().await?.sync_info.latest_block_height) Ok(self.status().await?.sync_info.latest_block_height)
} }
// TODO: the return type should probably be changed to a non-proto, type-safe Account alternative // TODO: the return type should probably be changed to a non-proto, type-safe Account alternative
async fn get_account(&self, address: &AccountId) -> Result<Option<Account>, NymdError> { async fn get_account(&self, address: &AccountId) -> Result<Option<Account>, NyxdError> {
let path = Some("/cosmos.auth.v1beta1.Query/Account".parse().unwrap()); let path = Some("/cosmos.auth.v1beta1.Query/Account".parse().unwrap());
let req = QueryAccountRequest { let req = QueryAccountRequest {
@@ -94,11 +94,11 @@ pub trait CosmWasmClient: rpc::Client {
res.account.map(TryFrom::try_from).transpose() res.account.map(TryFrom::try_from).transpose()
} }
async fn get_sequence(&self, address: &AccountId) -> Result<SequenceResponse, NymdError> { async fn get_sequence(&self, address: &AccountId) -> Result<SequenceResponse, NyxdError> {
let account = self let account = self
.get_account(address) .get_account(address)
.await? .await?
.ok_or_else(|| NymdError::NonExistentAccountError(address.clone()))?; .ok_or_else(|| NyxdError::NonExistentAccountError(address.clone()))?;
let base_account = account.try_get_base_account()?; let base_account = account.try_get_base_account()?;
Ok(SequenceResponse { Ok(SequenceResponse {
@@ -107,7 +107,7 @@ pub trait CosmWasmClient: rpc::Client {
}) })
} }
async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NymdError> { async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NyxdError> {
match height { match height {
Some(height) => self.block(height).await.map_err(|err| err.into()), Some(height) => self.block(height).await.map_err(|err| err.into()),
None => self.latest_block().await.map_err(|err| err.into()), None => self.latest_block().await.map_err(|err| err.into()),
@@ -118,7 +118,7 @@ pub trait CosmWasmClient: rpc::Client {
&self, &self,
address: &AccountId, address: &AccountId,
search_denom: String, search_denom: String,
) -> Result<Option<Coin>, NymdError> { ) -> Result<Option<Coin>, NyxdError> {
let path = Some("/cosmos.bank.v1beta1.Query/Balance".parse().unwrap()); let path = Some("/cosmos.bank.v1beta1.Query/Balance".parse().unwrap());
let req = QueryBalanceRequest { let req = QueryBalanceRequest {
@@ -133,10 +133,10 @@ pub trait CosmWasmClient: rpc::Client {
res.balance res.balance
.map(|proto| CosmosCoin::try_from(proto).map(Into::into)) .map(|proto| CosmosCoin::try_from(proto).map(Into::into))
.transpose() .transpose()
.map_err(|_| NymdError::SerializationError("Coin".to_owned())) .map_err(|_| NyxdError::SerializationError("Coin".to_owned()))
} }
async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NymdError> { async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NyxdError> {
let path = Some("/cosmos.bank.v1beta1.Query/AllBalances".parse().unwrap()); let path = Some("/cosmos.bank.v1beta1.Query/AllBalances".parse().unwrap());
let mut raw_balances = Vec::new(); let mut raw_balances = Vec::new();
@@ -164,10 +164,10 @@ pub trait CosmWasmClient: rpc::Client {
.into_iter() .into_iter()
.map(|proto| CosmosCoin::try_from(proto).map(Into::into)) .map(|proto| CosmosCoin::try_from(proto).map(Into::into))
.collect::<Result<_, _>>() .collect::<Result<_, _>>()
.map_err(|_| NymdError::SerializationError("Coins".to_owned())) .map_err(|_| NyxdError::SerializationError("Coins".to_owned()))
} }
async fn get_total_supply(&self) -> Result<Vec<Coin>, NymdError> { async fn get_total_supply(&self) -> Result<Vec<Coin>, NyxdError> {
let path = Some("/cosmos.bank.v1beta1.Query/TotalSupply".parse().unwrap()); let path = Some("/cosmos.bank.v1beta1.Query/TotalSupply".parse().unwrap());
let mut supply = Vec::new(); let mut supply = Vec::new();
@@ -192,14 +192,14 @@ pub trait CosmWasmClient: rpc::Client {
.into_iter() .into_iter()
.map(|proto| CosmosCoin::try_from(proto).map(Into::into)) .map(|proto| CosmosCoin::try_from(proto).map(Into::into))
.collect::<Result<_, _>>() .collect::<Result<_, _>>()
.map_err(|_| NymdError::SerializationError("Coins".to_owned())) .map_err(|_| NyxdError::SerializationError("Coins".to_owned()))
} }
async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NymdError> { async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NyxdError> {
Ok(self.tx(id, false).await?) Ok(self.tx(id, false).await?)
} }
async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NymdError> { async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NyxdError> {
// according to https://docs.tendermint.com/master/rpc/#/Info/tx_search // according to https://docs.tendermint.com/master/rpc/#/Info/tx_search
// the maximum entries per page is 100 and the default is 30 // the maximum entries per page is 100 and the default is 30
// so let's attempt to use the maximum // so let's attempt to use the maximum
@@ -234,7 +234,7 @@ pub trait CosmWasmClient: rpc::Client {
async fn broadcast_tx_async( async fn broadcast_tx_async(
&self, &self,
tx: Transaction, tx: Transaction,
) -> Result<broadcast::tx_async::Response, NymdError> { ) -> Result<broadcast::tx_async::Response, NyxdError> {
Ok(rpc::Client::broadcast_tx_async(self, tx).await?) Ok(rpc::Client::broadcast_tx_async(self, tx).await?)
} }
@@ -242,7 +242,7 @@ pub trait CosmWasmClient: rpc::Client {
async fn broadcast_tx_sync( async fn broadcast_tx_sync(
&self, &self,
tx: Transaction, tx: Transaction,
) -> Result<broadcast::tx_sync::Response, NymdError> { ) -> Result<broadcast::tx_sync::Response, NyxdError> {
Ok(rpc::Client::broadcast_tx_sync(self, tx).await?) Ok(rpc::Client::broadcast_tx_sync(self, tx).await?)
} }
@@ -250,16 +250,16 @@ pub trait CosmWasmClient: rpc::Client {
async fn broadcast_tx_commit( async fn broadcast_tx_commit(
&self, &self,
tx: Transaction, tx: Transaction,
) -> Result<broadcast::tx_commit::Response, NymdError> { ) -> Result<broadcast::tx_commit::Response, NyxdError> {
Ok(rpc::Client::broadcast_tx_commit(self, tx).await?) Ok(rpc::Client::broadcast_tx_commit(self, tx).await?)
} }
async fn broadcast_tx(&self, tx: Transaction) -> Result<TxResponse, NymdError> { async fn broadcast_tx(&self, tx: Transaction) -> Result<TxResponse, NyxdError> {
let broadcasted = CosmWasmClient::broadcast_tx_sync(self, tx).await?; let broadcasted = CosmWasmClient::broadcast_tx_sync(self, tx).await?;
if broadcasted.code.is_err() { if broadcasted.code.is_err() {
let code_val = broadcasted.code.value(); let code_val = broadcasted.code.value();
return Err(NymdError::BroadcastTxErrorDeliverTx { return Err(NyxdError::BroadcastTxErrorDeliverTx {
hash: broadcasted.hash, hash: broadcasted.hash,
height: None, height: None,
code: code_val, code: code_val,
@@ -276,7 +276,7 @@ pub trait CosmWasmClient: rpc::Client {
broadcasted.hash broadcasted.hash
); );
if tokio::time::Instant::now().duration_since(start) >= self.broadcast_timeout() { if tokio::time::Instant::now().duration_since(start) >= self.broadcast_timeout() {
return Err(NymdError::BroadcastTimeout { return Err(NyxdError::BroadcastTimeout {
hash: tx_hash, hash: tx_hash,
timeout: self.broadcast_timeout(), timeout: self.broadcast_timeout(),
}); });
@@ -290,7 +290,7 @@ pub trait CosmWasmClient: rpc::Client {
} }
} }
async fn get_codes(&self) -> Result<Vec<Code>, NymdError> { async fn get_codes(&self) -> Result<Vec<Code>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/Codes".parse().unwrap()); let path = Some("/cosmwasm.wasm.v1.Query/Codes".parse().unwrap());
let mut raw_codes = Vec::new(); let mut raw_codes = Vec::new();
@@ -317,7 +317,7 @@ pub trait CosmWasmClient: rpc::Client {
.collect::<Result<_, _>>() .collect::<Result<_, _>>()
} }
async fn get_code_details(&self, code_id: ContractCodeId) -> Result<CodeDetails, NymdError> { async fn get_code_details(&self, code_id: ContractCodeId) -> Result<CodeDetails, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/Code".parse().unwrap()); let path = Some("/cosmwasm.wasm.v1.Query/Code".parse().unwrap());
let req = QueryCodeRequest { code_id }; let req = QueryCodeRequest { code_id };
@@ -329,10 +329,10 @@ pub trait CosmWasmClient: rpc::Client {
if let Some(code_info) = res.code_info { if let Some(code_info) = res.code_info {
Ok(CodeDetails::new(code_info.try_into()?, res.data)) Ok(CodeDetails::new(code_info.try_into()?, res.data))
} else { } else {
Err(NymdError::NoCodeInformation(code_id)) Err(NyxdError::NoCodeInformation(code_id))
} }
} }
async fn get_contracts(&self, code_id: ContractCodeId) -> Result<Vec<AccountId>, NymdError> { async fn get_contracts(&self, code_id: ContractCodeId) -> Result<Vec<AccountId>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/ContractsByCode".parse().unwrap()); let path = Some("/cosmwasm.wasm.v1.Query/ContractsByCode".parse().unwrap());
let mut raw_contracts = Vec::new(); let mut raw_contracts = Vec::new();
@@ -360,10 +360,10 @@ pub trait CosmWasmClient: rpc::Client {
.iter() .iter()
.map(|raw| raw.parse()) .map(|raw| raw.parse())
.collect::<Result<_, _>>() .collect::<Result<_, _>>()
.map_err(|_| NymdError::DeserializationError("Contract addresses".to_owned())) .map_err(|_| NyxdError::DeserializationError("Contract addresses".to_owned()))
} }
async fn get_contract(&self, address: &AccountId) -> Result<Contract, NymdError> { async fn get_contract(&self, address: &AccountId) -> Result<Contract, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/ContractInfo".parse().unwrap()); let path = Some("/cosmwasm.wasm.v1.Query/ContractInfo".parse().unwrap());
let req = QueryContractInfoRequest { let req = QueryContractInfoRequest {
@@ -378,17 +378,17 @@ pub trait CosmWasmClient: rpc::Client {
if let Some(contract_info) = res.contract_info { if let Some(contract_info) = res.contract_info {
let address = response_address let address = response_address
.parse() .parse()
.map_err(|_| NymdError::MalformedAccountAddress(response_address))?; .map_err(|_| NyxdError::MalformedAccountAddress(response_address))?;
Ok(Contract::new(address, contract_info.try_into()?)) Ok(Contract::new(address, contract_info.try_into()?))
} else { } else {
Err(NymdError::NoContractInformation(address.clone())) Err(NyxdError::NoContractInformation(address.clone()))
} }
} }
async fn get_contract_code_history( async fn get_contract_code_history(
&self, &self,
address: &AccountId, address: &AccountId,
) -> Result<Vec<ContractCodeHistoryEntry>, NymdError> { ) -> Result<Vec<ContractCodeHistoryEntry>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/ContractHistory".parse().unwrap()); let path = Some("/cosmwasm.wasm.v1.Query/ContractHistory".parse().unwrap());
let mut raw_entries = Vec::new(); let mut raw_entries = Vec::new();
@@ -422,7 +422,7 @@ pub trait CosmWasmClient: rpc::Client {
&self, &self,
address: &AccountId, address: &AccountId,
query_data: Vec<u8>, query_data: Vec<u8>,
) -> Result<Vec<u8>, NymdError> { ) -> Result<Vec<u8>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/RawContractState".parse().unwrap()); let path = Some("/cosmwasm.wasm.v1.Query/RawContractState".parse().unwrap());
let req = QueryRawContractStateRequest { let req = QueryRawContractStateRequest {
@@ -441,7 +441,7 @@ pub trait CosmWasmClient: rpc::Client {
&self, &self,
address: &AccountId, address: &AccountId,
query_msg: &M, query_msg: &M,
) -> Result<T, NymdError> ) -> Result<T, NyxdError>
where where
M: ?Sized + Serialize + Sync, M: ?Sized + Serialize + Sync,
for<'a> T: Deserialize<'a>, for<'a> T: Deserialize<'a>,
@@ -478,7 +478,7 @@ pub trait CosmWasmClient: rpc::Client {
&self, &self,
tx: Option<Tx>, tx: Option<Tx>,
tx_bytes: Vec<u8>, tx_bytes: Vec<u8>,
) -> Result<SimulateResponse, NymdError> { ) -> Result<SimulateResponse, NyxdError> {
let path = Some("/cosmos.tx.v1beta1.Service/Simulate".parse().unwrap()); let path = Some("/cosmos.tx.v1beta1.Service/Simulate".parse().unwrap());
let req = SimulateRequest { let req = SimulateRequest {
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use cosmrs::proto::cosmos::base::query::v1beta1::{PageRequest, PageResponse}; use cosmrs::proto::cosmos::base::query::v1beta1::{PageRequest, PageResponse};
use cosmrs::proto::cosmos::base::v1beta1::Coin as ProtoCoin; use cosmrs::proto::cosmos::base::v1beta1::Coin as ProtoCoin;
use cosmrs::rpc::endpoint::broadcast; use cosmrs::rpc::endpoint::broadcast;
@@ -11,13 +11,13 @@ use flate2::Compression;
use std::io::Write; use std::io::Write;
pub(crate) trait CheckResponse: Sized { pub(crate) trait CheckResponse: Sized {
fn check_response(self) -> Result<Self, NymdError>; fn check_response(self) -> Result<Self, NyxdError>;
} }
impl CheckResponse for broadcast::tx_commit::Response { impl CheckResponse for broadcast::tx_commit::Response {
fn check_response(self) -> Result<Self, NymdError> { fn check_response(self) -> Result<Self, NyxdError> {
if self.check_tx.code.is_err() { if self.check_tx.code.is_err() {
return Err(NymdError::BroadcastTxErrorCheckTx { return Err(NyxdError::BroadcastTxErrorCheckTx {
hash: self.hash, hash: self.hash,
height: Some(self.height), height: Some(self.height),
code: self.check_tx.code.value(), code: self.check_tx.code.value(),
@@ -26,7 +26,7 @@ impl CheckResponse for broadcast::tx_commit::Response {
} }
if self.deliver_tx.code.is_err() { if self.deliver_tx.code.is_err() {
return Err(NymdError::BroadcastTxErrorDeliverTx { return Err(NyxdError::BroadcastTxErrorDeliverTx {
hash: self.hash, hash: self.hash,
height: Some(self.height), height: Some(self.height),
code: self.deliver_tx.code.value(), code: self.deliver_tx.code.value(),
@@ -38,10 +38,10 @@ impl CheckResponse for broadcast::tx_commit::Response {
} }
} }
impl CheckResponse for crate::nymd::TxResponse { impl CheckResponse for crate::nyxd::TxResponse {
fn check_response(self) -> Result<Self, NymdError> { fn check_response(self) -> Result<Self, NyxdError> {
if self.tx_result.code.is_err() { if self.tx_result.code.is_err() {
return Err(NymdError::BroadcastTxErrorDeliverTx { return Err(NyxdError::BroadcastTxErrorDeliverTx {
hash: self.hash, hash: self.hash,
height: Some(self.height), height: Some(self.height),
code: self.tx_result.code.value(), code: self.tx_result.code.value(),
@@ -53,13 +53,13 @@ impl CheckResponse for crate::nymd::TxResponse {
} }
} }
pub(crate) fn compress_wasm_code(code: &[u8]) -> Result<Vec<u8>, NymdError> { pub(crate) fn compress_wasm_code(code: &[u8]) -> Result<Vec<u8>, NyxdError> {
// using compression level 9, same as cosmjs, that optimises for size // using compression level 9, same as cosmjs, that optimises for size
let mut encoder = GzEncoder::new(Vec::new(), Compression::best()); let mut encoder = GzEncoder::new(Vec::new(), Compression::best());
encoder encoder
.write_all(code) .write_all(code)
.map_err(NymdError::WasmCompressionError)?; .map_err(NyxdError::WasmCompressionError)?;
encoder.finish().map_err(NymdError::WasmCompressionError) encoder.finish().map_err(NyxdError::WasmCompressionError)
} }
pub(crate) fn create_pagination(key: Vec<u8>) -> PageRequest { pub(crate) fn create_pagination(key: Vec<u8>) -> PageRequest {
@@ -84,11 +84,11 @@ pub(crate) fn next_page_key(pagination_info: Option<PageResponse>) -> Option<Vec
None None
} }
pub(crate) fn parse_proto_coin_vec(value: Vec<ProtoCoin>) -> Result<Vec<Coin>, NymdError> { pub(crate) fn parse_proto_coin_vec(value: Vec<ProtoCoin>) -> Result<Vec<Coin>, NyxdError> {
value value
.into_iter() .into_iter()
.map(|proto_coin| { .map(|proto_coin| {
Coin::try_from(&proto_coin).map_err(|_| NymdError::MalformedCoin { Coin::try_from(&proto_coin).map_err(|_| NyxdError::MalformedCoin {
coin_representation: format!("{:?}", proto_coin), coin_representation: format!("{:?}", proto_coin),
}) })
}) })
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use cosmrs::tendermint::abci; use cosmrs::tendermint::abci;
use itertools::Itertools; use itertools::Itertools;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -39,17 +39,17 @@ pub fn find_attribute<'a>(
} }
// those two functions were separated so that the internal logic could actually be tested // those two functions were separated so that the internal logic could actually be tested
fn parse_raw_str_logs(raw: &str) -> Result<Vec<Log>, NymdError> { fn parse_raw_str_logs(raw: &str) -> Result<Vec<Log>, NyxdError> {
let logs: Vec<Log> = serde_json::from_str(raw).map_err(|_| NymdError::MalformedLogString)?; let logs: Vec<Log> = serde_json::from_str(raw).map_err(|_| NyxdError::MalformedLogString)?;
if logs.len() != logs.iter().unique_by(|log| log.msg_index).count() { if logs.len() != logs.iter().unique_by(|log| log.msg_index).count() {
// this check is only here because I don't yet fully understand raw log string generation and // this check is only here because I don't yet fully understand raw log string generation and
// the fact the first entry does not seem to have `msg_index` defined on it. // the fact the first entry does not seem to have `msg_index` defined on it.
return Err(NymdError::MalformedLogString); return Err(NyxdError::MalformedLogString);
} }
Ok(logs) Ok(logs)
} }
pub fn parse_raw_logs(raw: abci::Log) -> Result<Vec<Log>, NymdError> { pub fn parse_raw_logs(raw: abci::Log) -> Result<Vec<Log>, NyxdError> {
parse_raw_str_logs(raw.as_ref()) parse_raw_str_logs(raw.as_ref())
} }
@@ -1,9 +1,9 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::wallet::DirectSecp256k1HdWallet; use crate::nyxd::wallet::DirectSecp256k1HdWallet;
use crate::nymd::GasPrice; use crate::nyxd::GasPrice;
use cosmrs::rpc::{Error as TendermintRpcError, HttpClient, HttpClientUrl}; use cosmrs::rpc::{Error as TendermintRpcError, HttpClient, HttpClientUrl};
use std::convert::TryInto; use std::convert::TryInto;
@@ -13,7 +13,7 @@ pub mod logs;
pub mod signing_client; pub mod signing_client;
pub mod types; pub mod types;
pub fn connect<U>(endpoint: U) -> Result<HttpClient, NymdError> pub fn connect<U>(endpoint: U) -> Result<HttpClient, NyxdError>
where where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>, U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{ {
@@ -25,7 +25,7 @@ pub fn connect_with_signer<U: Clone>(
endpoint: U, endpoint: U,
signer: DirectSecp256k1HdWallet, signer: DirectSecp256k1HdWallet,
gas_price: GasPrice, gas_price: GasPrice,
) -> Result<signing_client::Client, NymdError> ) -> Result<signing_client::Client, NyxdError>
where where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>, U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{ {
@@ -1,14 +1,14 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::client::CosmWasmClient; use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::cosmwasm_client::helpers::{compress_wasm_code, CheckResponse}; use crate::nyxd::cosmwasm_client::helpers::{compress_wasm_code, CheckResponse};
use crate::nymd::cosmwasm_client::logs::{self, parse_raw_logs}; use crate::nyxd::cosmwasm_client::logs::{self, parse_raw_logs};
use crate::nymd::cosmwasm_client::types::*; use crate::nyxd::cosmwasm_client::types::*;
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::fee::{Fee, DEFAULT_SIMULATED_GAS_MULTIPLIER}; use crate::nyxd::fee::{Fee, DEFAULT_SIMULATED_GAS_MULTIPLIER};
use crate::nymd::wallet::DirectSecp256k1HdWallet; use crate::nyxd::wallet::DirectSecp256k1HdWallet;
use crate::nymd::{Coin, GasAdjustable, GasPrice, TxResponse}; use crate::nyxd::{Coin, GasAdjustable, GasPrice, TxResponse};
use async_trait::async_trait; use async_trait::async_trait;
use cosmrs::bank::MsgSend; use cosmrs::bank::MsgSend;
use cosmrs::distribution::MsgWithdrawDelegatorReward; use cosmrs::distribution::MsgWithdrawDelegatorReward;
@@ -74,7 +74,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
signer_address: &AccountId, signer_address: &AccountId,
messages: Vec<Any>, messages: Vec<Any>,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<SimulateResponse, NymdError> { ) -> Result<SimulateResponse, NyxdError> {
let public_key = self.signer_public_key(signer_address); let public_key = self.signer_public_key(signer_address);
let sequence_response = self.get_sequence(signer_address).await?; let sequence_response = self.get_sequence(signer_address).await?;
@@ -102,7 +102,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
wasm_code: Vec<u8>, wasm_code: Vec<u8>,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<UploadResult, NymdError> { ) -> Result<UploadResult, NyxdError> {
let compressed = compress_wasm_code(&wasm_code)?; let compressed = compress_wasm_code(&wasm_code)?;
let compressed_size = compressed.len(); let compressed_size = compressed.len();
let compressed_checksum = Sha256::digest(&compressed).to_vec(); let compressed_checksum = Sha256::digest(&compressed).to_vec();
@@ -115,7 +115,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
instantiate_permission: Default::default(), instantiate_permission: Default::default(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgStoreCode".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgStoreCode".to_owned()))?;
let tx_res = self let tx_res = self
.sign_and_broadcast(sender_address, vec![upload_msg], fee, memo) .sign_and_broadcast(sender_address, vec![upload_msg], fee, memo)
@@ -161,7 +161,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
mut options: Option<InstantiateOptions>, mut options: Option<InstantiateOptions>,
) -> Result<InstantiateResult, NymdError> ) -> Result<InstantiateResult, NyxdError>
where where
M: ?Sized + Serialize + Sync, M: ?Sized + Serialize + Sync,
{ {
@@ -176,7 +176,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
funds: options.map(|options| options.funds).unwrap_or_default(), funds: options.map(|options| options.funds).unwrap_or_default(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgInstantiateContract".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgInstantiateContract".to_owned()))?;
let tx_res = self let tx_res = self
.sign_and_broadcast(sender_address, vec![init_msg], fee, memo) .sign_and_broadcast(sender_address, vec![init_msg], fee, memo)
@@ -211,14 +211,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
new_admin: &AccountId, new_admin: &AccountId,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<ChangeAdminResult, NymdError> { ) -> Result<ChangeAdminResult, NyxdError> {
let change_admin_msg = cosmwasm::MsgUpdateAdmin { let change_admin_msg = cosmwasm::MsgUpdateAdmin {
sender: sender_address.clone(), sender: sender_address.clone(),
new_admin: new_admin.clone(), new_admin: new_admin.clone(),
contract: contract_address.clone(), contract: contract_address.clone(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgUpdateAdmin".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgUpdateAdmin".to_owned()))?;
let tx_res = self let tx_res = self
.sign_and_broadcast(sender_address, vec![change_admin_msg], fee, memo) .sign_and_broadcast(sender_address, vec![change_admin_msg], fee, memo)
@@ -240,13 +240,13 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
contract_address: &AccountId, contract_address: &AccountId,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<ChangeAdminResult, NymdError> { ) -> Result<ChangeAdminResult, NyxdError> {
let change_admin_msg = cosmwasm::MsgClearAdmin { let change_admin_msg = cosmwasm::MsgClearAdmin {
sender: sender_address.clone(), sender: sender_address.clone(),
contract: contract_address.clone(), contract: contract_address.clone(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgClearAdmin".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgClearAdmin".to_owned()))?;
let tx_res = self let tx_res = self
.sign_and_broadcast(sender_address, vec![change_admin_msg], fee, memo) .sign_and_broadcast(sender_address, vec![change_admin_msg], fee, memo)
@@ -270,7 +270,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: Fee, fee: Fee,
msg: &M, msg: &M,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<MigrateResult, NymdError> ) -> Result<MigrateResult, NyxdError>
where where
M: ?Sized + Serialize + Sync, M: ?Sized + Serialize + Sync,
{ {
@@ -281,7 +281,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
msg: serde_json::to_vec(msg)?, msg: serde_json::to_vec(msg)?,
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgMigrateContract".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgMigrateContract".to_owned()))?;
let tx_res = self let tx_res = self
.sign_and_broadcast(sender_address, vec![migrate_msg], fee, memo) .sign_and_broadcast(sender_address, vec![migrate_msg], fee, memo)
@@ -305,7 +305,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
funds: Vec<Coin>, funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError> ) -> Result<ExecuteResult, NyxdError>
where where
M: ?Sized + Serialize + Sync, M: ?Sized + Serialize + Sync,
{ {
@@ -316,7 +316,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
funds: funds.into_iter().map(Into::into).collect(), funds: funds.into_iter().map(Into::into).collect(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgExecuteContract".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgExecuteContract".to_owned()))?;
let tx_res = self let tx_res = self
.sign_and_broadcast(sender_address, vec![execute_msg], fee, memo) .sign_and_broadcast(sender_address, vec![execute_msg], fee, memo)
@@ -340,7 +340,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
msgs: I, msgs: I,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<ExecuteResult, NymdError> ) -> Result<ExecuteResult, NyxdError>
where where
I: IntoIterator<Item = (M, Vec<Coin>)> + Send, I: IntoIterator<Item = (M, Vec<Coin>)> + Send,
M: Serialize, M: Serialize,
@@ -355,7 +355,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
funds: funds.into_iter().map(Into::into).collect(), funds: funds.into_iter().map(Into::into).collect(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgExecuteContract".to_owned())) .map_err(|_| NyxdError::SerializationError("MsgExecuteContract".to_owned()))
}) })
.collect::<Result<_, _>>()?; .collect::<Result<_, _>>()?;
@@ -381,14 +381,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: Vec<Coin>, amount: Vec<Coin>,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> { ) -> Result<TxResponse, NyxdError> {
let send_msg = MsgSend { let send_msg = MsgSend {
from_address: sender_address.clone(), from_address: sender_address.clone(),
to_address: recipient_address.clone(), to_address: recipient_address.clone(),
amount: amount.into_iter().map(Into::into).collect(), amount: amount.into_iter().map(Into::into).collect(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgSend".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgSend".to_owned()))?;
self.sign_and_broadcast(sender_address, vec![send_msg], fee, memo) self.sign_and_broadcast(sender_address, vec![send_msg], fee, memo)
.await? .await?
@@ -401,7 +401,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
msgs: I, msgs: I,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> ) -> Result<TxResponse, NyxdError>
where where
I: IntoIterator<Item = (AccountId, Vec<Coin>)> + Send, I: IntoIterator<Item = (AccountId, Vec<Coin>)> + Send,
{ {
@@ -414,7 +414,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: amount.into_iter().map(Into::into).collect(), amount: amount.into_iter().map(Into::into).collect(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgExecuteContract".to_owned())) .map_err(|_| NyxdError::SerializationError("MsgExecuteContract".to_owned()))
}) })
.collect::<Result<_, _>>()?; .collect::<Result<_, _>>()?;
@@ -433,20 +433,20 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
allowed_messages: Vec<String>, allowed_messages: Vec<String>,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> { ) -> Result<TxResponse, NyxdError> {
let basic_allowance = BasicAllowance { let basic_allowance = BasicAllowance {
spend_limit: spend_limit.into_iter().map(Into::into).collect(), spend_limit: spend_limit.into_iter().map(Into::into).collect(),
expiration, expiration,
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("BasicAllowance".to_owned()))?; .map_err(|_| NyxdError::SerializationError("BasicAllowance".to_owned()))?;
let allowed_msg_allowance = AllowedMsgAllowance { let allowed_msg_allowance = AllowedMsgAllowance {
allowance: Some(basic_allowance), allowance: Some(basic_allowance),
allowed_messages, allowed_messages,
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("AllowedMsgAllowance".to_owned()))?; .map_err(|_| NyxdError::SerializationError("AllowedMsgAllowance".to_owned()))?;
let grant_allowance_msg = MsgGrantAllowance { let grant_allowance_msg = MsgGrantAllowance {
granter: granter.to_owned(), granter: granter.to_owned(),
@@ -454,7 +454,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
allowance: Some(allowed_msg_allowance), allowance: Some(allowed_msg_allowance),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgGrantAllowance".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgGrantAllowance".to_owned()))?;
self.sign_and_broadcast(granter, vec![grant_allowance_msg], fee, memo) self.sign_and_broadcast(granter, vec![grant_allowance_msg], fee, memo)
.await? .await?
@@ -467,13 +467,13 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
grantee: &AccountId, grantee: &AccountId,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> { ) -> Result<TxResponse, NyxdError> {
let revoke_allowance_msg = MsgRevokeAllowance { let revoke_allowance_msg = MsgRevokeAllowance {
granter: granter.to_owned(), granter: granter.to_owned(),
grantee: grantee.to_owned(), grantee: grantee.to_owned(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgRevokeAllowance".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgRevokeAllowance".to_owned()))?;
self.sign_and_broadcast(granter, vec![revoke_allowance_msg], fee, memo) self.sign_and_broadcast(granter, vec![revoke_allowance_msg], fee, memo)
.await? .await?
@@ -487,14 +487,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: Coin, amount: Coin,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> { ) -> Result<TxResponse, NyxdError> {
let delegate_msg = MsgDelegate { let delegate_msg = MsgDelegate {
delegator_address: delegator_address.to_owned(), delegator_address: delegator_address.to_owned(),
validator_address: validator_address.to_owned(), validator_address: validator_address.to_owned(),
amount: amount.into(), amount: amount.into(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgDelegate".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgDelegate".to_owned()))?;
self.sign_and_broadcast(delegator_address, vec![delegate_msg], fee, memo) self.sign_and_broadcast(delegator_address, vec![delegate_msg], fee, memo)
.await? .await?
@@ -508,14 +508,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: Coin, amount: Coin,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> { ) -> Result<TxResponse, NyxdError> {
let undelegate_msg = MsgUndelegate { let undelegate_msg = MsgUndelegate {
delegator_address: delegator_address.to_owned(), delegator_address: delegator_address.to_owned(),
validator_address: validator_address.to_owned(), validator_address: validator_address.to_owned(),
amount: amount.into(), amount: amount.into(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgUndelegate".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgUndelegate".to_owned()))?;
self.sign_and_broadcast(delegator_address, vec![undelegate_msg], fee, memo) self.sign_and_broadcast(delegator_address, vec![undelegate_msg], fee, memo)
.await? .await?
@@ -528,13 +528,13 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
validator_address: &AccountId, validator_address: &AccountId,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> { ) -> Result<TxResponse, NyxdError> {
let withdraw_msg = MsgWithdrawDelegatorReward { let withdraw_msg = MsgWithdrawDelegatorReward {
delegator_address: delegator_address.to_owned(), delegator_address: delegator_address.to_owned(),
validator_address: validator_address.to_owned(), validator_address: validator_address.to_owned(),
} }
.to_any() .to_any()
.map_err(|_| NymdError::SerializationError("MsgWithdrawDelegatorReward".to_owned()))?; .map_err(|_| NyxdError::SerializationError("MsgWithdrawDelegatorReward".to_owned()))?;
self.sign_and_broadcast(delegator_address, vec![withdraw_msg], fee, memo) self.sign_and_broadcast(delegator_address, vec![withdraw_msg], fee, memo)
.await? .await?
@@ -549,7 +549,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: &[Any], messages: &[Any],
fee: Fee, fee: Fee,
memo: &String, memo: &String,
) -> Result<tx::Fee, NymdError> { ) -> Result<tx::Fee, NyxdError> {
let auto_fee = |multiplier: Option<f32>| async move { let auto_fee = |multiplier: Option<f32>| async move {
debug!("Trying to simulate gas costs..."); debug!("Trying to simulate gas costs...");
// from what I've seen in manual testing, gas estimation does not exist if transaction // from what I've seen in manual testing, gas estimation does not exist if transaction
@@ -558,7 +558,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
.simulate(signer_address, messages.to_vec(), memo.clone()) .simulate(signer_address, messages.to_vec(), memo.clone())
.await? .await?
.gas_info .gas_info
.ok_or(NymdError::GasEstimationFailure)? .ok_or(NyxdError::GasEstimationFailure)?
.gas_used; .gas_used;
let multiplier = multiplier.unwrap_or(DEFAULT_SIMULATED_GAS_MULTIPLIER); let multiplier = multiplier.unwrap_or(DEFAULT_SIMULATED_GAS_MULTIPLIER);
@@ -569,7 +569,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
debug!("Final gas limit used: {}", gas); debug!("Final gas limit used: {}", gas);
let fee = self.gas_price() * gas; let fee = self.gas_price() * gas;
Ok::<tx::Fee, NymdError>(tx::Fee::from_amount_and_gas(fee, gas)) Ok::<tx::Fee, NyxdError>(tx::Fee::from_amount_and_gas(fee, gas))
}; };
let fee = match fee { let fee = match fee {
Fee::Manual(fee) => fee, Fee::Manual(fee) => fee,
@@ -592,7 +592,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>, messages: Vec<Any>,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<broadcast::tx_async::Response, NymdError> { ) -> Result<broadcast::tx_async::Response, NyxdError> {
let memo = memo.into(); let memo = memo.into();
let fee = self let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo) .determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -600,7 +600,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?; let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw let tx_bytes = tx_raw
.to_bytes() .to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?; .map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
CosmWasmClient::broadcast_tx_async(self, tx_bytes.into()).await CosmWasmClient::broadcast_tx_async(self, tx_bytes.into()).await
} }
@@ -612,7 +612,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>, messages: Vec<Any>,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<broadcast::tx_sync::Response, NymdError> { ) -> Result<broadcast::tx_sync::Response, NyxdError> {
let memo = memo.into(); let memo = memo.into();
let fee = self let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo) .determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -620,7 +620,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?; let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw let tx_bytes = tx_raw
.to_bytes() .to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?; .map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
CosmWasmClient::broadcast_tx_sync(self, tx_bytes.into()).await CosmWasmClient::broadcast_tx_sync(self, tx_bytes.into()).await
} }
@@ -632,7 +632,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>, messages: Vec<Any>,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<broadcast::tx_commit::Response, NymdError> { ) -> Result<broadcast::tx_commit::Response, NyxdError> {
let memo = memo.into(); let memo = memo.into();
let fee = self let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo) .determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -641,7 +641,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?; let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw let tx_bytes = tx_raw
.to_bytes() .to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?; .map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
CosmWasmClient::broadcast_tx_commit(self, tx_bytes.into()).await CosmWasmClient::broadcast_tx_commit(self, tx_bytes.into()).await
} }
@@ -653,7 +653,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>, messages: Vec<Any>,
fee: Fee, fee: Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> { ) -> Result<TxResponse, NyxdError> {
let memo = memo.into(); let memo = memo.into();
let fee = self let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo) .determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -662,7 +662,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?; let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw let tx_bytes = tx_raw
.to_bytes() .to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?; .map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
self.broadcast_tx(tx_bytes.into()).await self.broadcast_tx(tx_bytes.into()).await
} }
@@ -674,12 +674,12 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: tx::Fee, fee: tx::Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
signer_data: SignerData, signer_data: SignerData,
) -> Result<tx::Raw, NymdError> { ) -> Result<tx::Raw, NyxdError> {
let signer_accounts = self.signer().try_derive_accounts()?; let signer_accounts = self.signer().try_derive_accounts()?;
let account_from_signer = signer_accounts let account_from_signer = signer_accounts
.iter() .iter()
.find(|account| &account.address == signer_address) .find(|account| &account.address == signer_address)
.ok_or_else(|| NymdError::SigningAccountNotFound(signer_address.clone()))?; .ok_or_else(|| NyxdError::SigningAccountNotFound(signer_address.clone()))?;
// TODO: WTF HOW IS TIMEOUT_HEIGHT SUPPOSED TO GET DETERMINED? // TODO: WTF HOW IS TIMEOUT_HEIGHT SUPPOSED TO GET DETERMINED?
// IT DOESNT EXIST IN COSMJS!! // IT DOESNT EXIST IN COSMJS!!
@@ -691,7 +691,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
SignerInfo::single_direct(Some(account_from_signer.public_key), signer_data.sequence); SignerInfo::single_direct(Some(account_from_signer.public_key), signer_data.sequence);
let auth_info = signer_info.auth_info(fee); let auth_info = signer_info.auth_info(fee);
// ideally I'd prefer to have the entire error put into the NymdError::SigningFailure // ideally I'd prefer to have the entire error put into the NyxdError::SigningFailure
// but I'm super hesitant to trying to downcast the eyre::Report to cosmrs::error::Error // but I'm super hesitant to trying to downcast the eyre::Report to cosmrs::error::Error
let sign_doc = SignDoc::new( let sign_doc = SignDoc::new(
&tx_body, &tx_body,
@@ -699,7 +699,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
&signer_data.chain_id, &signer_data.chain_id,
signer_data.account_number, signer_data.account_number,
) )
.map_err(|_| NymdError::SigningFailure)?; .map_err(|_| NyxdError::SigningFailure)?;
self.signer() self.signer()
.sign_direct_with_account(account_from_signer, sign_doc) .sign_direct_with_account(account_from_signer, sign_doc)
@@ -711,7 +711,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>, messages: Vec<Any>,
fee: tx::Fee, fee: tx::Fee,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<tx::Raw, NymdError> { ) -> Result<tx::Raw, NyxdError> {
// TODO: Future optimisation: rather than grabbing current account_number and sequence // TODO: Future optimisation: rather than grabbing current account_number and sequence
// on every sign request -> just keep them cached on the struct and increment as required // on every sign request -> just keep them cached on the struct and increment as required
let sequence_response = self.get_sequence(signer_address).await?; let sequence_response = self.get_sequence(signer_address).await?;
@@ -742,7 +742,7 @@ impl Client {
endpoint: U, endpoint: U,
signer: DirectSecp256k1HdWallet, signer: DirectSecp256k1HdWallet,
gas_price: GasPrice, gas_price: GasPrice,
) -> Result<Self, NymdError> ) -> Result<Self, NyxdError>
where where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>, U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{ {
@@ -3,9 +3,9 @@
// TODO: There's a significant argument to pull those out of the package and make a PR on https://github.com/cosmos/cosmos-rust/ // TODO: There's a significant argument to pull those out of the package and make a PR on https://github.com/cosmos/cosmos-rust/
use crate::nymd::cosmwasm_client::helpers::parse_proto_coin_vec; use crate::nyxd::cosmwasm_client::helpers::parse_proto_coin_vec;
use crate::nymd::cosmwasm_client::logs::Log; use crate::nyxd::cosmwasm_client::logs::Log;
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use cosmrs::crypto::PublicKey; use cosmrs::crypto::PublicKey;
use cosmrs::proto::cosmos::auth::v1beta1::{ use cosmrs::proto::cosmos::auth::v1beta1::{
BaseAccount as ProtoBaseAccount, ModuleAccount as ProtoModuleAccount, BaseAccount as ProtoBaseAccount, ModuleAccount as ProtoModuleAccount,
@@ -57,19 +57,19 @@ pub struct BaseAccount {
} }
impl TryFrom<ProtoBaseAccount> for BaseAccount { impl TryFrom<ProtoBaseAccount> for BaseAccount {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoBaseAccount) -> Result<Self, Self::Error> { fn try_from(value: ProtoBaseAccount) -> Result<Self, Self::Error> {
let address: AccountId = value let address: AccountId = value
.address .address
.parse() .parse()
.map_err(|_| NymdError::MalformedAccountAddress(value.address.clone()))?; .map_err(|_| NyxdError::MalformedAccountAddress(value.address.clone()))?;
let pubkey = value let pubkey = value
.pub_key .pub_key
.map(PublicKey::try_from) .map(PublicKey::try_from)
.transpose() .transpose()
.map_err(|_| NymdError::InvalidPublicKey(address.clone()))?; .map_err(|_| NyxdError::InvalidPublicKey(address.clone()))?;
Ok(BaseAccount { Ok(BaseAccount {
address, address,
@@ -89,7 +89,7 @@ pub struct ModuleAccount {
} }
impl TryFrom<ProtoModuleAccount> for ModuleAccount { impl TryFrom<ProtoModuleAccount> for ModuleAccount {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoModuleAccount) -> Result<Self, Self::Error> { fn try_from(value: ProtoModuleAccount) -> Result<Self, Self::Error> {
let base_account = value.base_account.map(TryFrom::try_from).transpose()?; let base_account = value.base_account.map(TryFrom::try_from).transpose()?;
@@ -114,7 +114,7 @@ pub struct BaseVestingAccount {
} }
impl TryFrom<ProtoBaseVestingAccount> for BaseVestingAccount { impl TryFrom<ProtoBaseVestingAccount> for BaseVestingAccount {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoBaseVestingAccount) -> Result<Self, Self::Error> { fn try_from(value: ProtoBaseVestingAccount) -> Result<Self, Self::Error> {
let base_account = value.base_account.map(TryFrom::try_from).transpose()?; let base_account = value.base_account.map(TryFrom::try_from).transpose()?;
@@ -142,7 +142,7 @@ pub struct ContinuousVestingAccount {
} }
impl TryFrom<ProtoContinuousVestingAccount> for ContinuousVestingAccount { impl TryFrom<ProtoContinuousVestingAccount> for ContinuousVestingAccount {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoContinuousVestingAccount) -> Result<Self, Self::Error> { fn try_from(value: ProtoContinuousVestingAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value let base_vesting_account = value
@@ -166,7 +166,7 @@ pub struct DelayedVestingAccount {
} }
impl TryFrom<ProtoDelayedVestingAccount> for DelayedVestingAccount { impl TryFrom<ProtoDelayedVestingAccount> for DelayedVestingAccount {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoDelayedVestingAccount) -> Result<Self, Self::Error> { fn try_from(value: ProtoDelayedVestingAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value let base_vesting_account = value
@@ -188,7 +188,7 @@ pub struct Period {
} }
impl TryFrom<ProtoPeriod> for Period { impl TryFrom<ProtoPeriod> for Period {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoPeriod) -> Result<Self, Self::Error> { fn try_from(value: ProtoPeriod) -> Result<Self, Self::Error> {
Ok(Period { Ok(Period {
@@ -208,7 +208,7 @@ pub struct PeriodicVestingAccount {
} }
impl TryFrom<ProtoPeriodicVestingAccount> for PeriodicVestingAccount { impl TryFrom<ProtoPeriodicVestingAccount> for PeriodicVestingAccount {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoPeriodicVestingAccount) -> Result<Self, Self::Error> { fn try_from(value: ProtoPeriodicVestingAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value let base_vesting_account = value
@@ -239,7 +239,7 @@ pub struct PermanentLockedAccount {
} }
impl TryFrom<ProtoPermanentLockedAccount> for PermanentLockedAccount { impl TryFrom<ProtoPermanentLockedAccount> for PermanentLockedAccount {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoPermanentLockedAccount) -> Result<Self, Self::Error> { fn try_from(value: ProtoPermanentLockedAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value let base_vesting_account = value
@@ -265,43 +265,43 @@ pub enum Account {
} }
impl Account { impl Account {
pub fn try_get_base_account(&self) -> Result<&BaseAccount, NymdError> { pub fn try_get_base_account(&self) -> Result<&BaseAccount, NyxdError> {
match self { match self {
Account::Base(acc) => Ok(acc), Account::Base(acc) => Ok(acc),
Account::Module(acc) => acc Account::Module(acc) => acc
.base_account .base_account
.as_ref() .as_ref()
.ok_or(NymdError::NoBaseAccountInformationAvailable), .ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::BaseVesting(acc) => acc Account::BaseVesting(acc) => acc
.base_account .base_account
.as_ref() .as_ref()
.ok_or(NymdError::NoBaseAccountInformationAvailable), .ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::ContinuousVesting(acc) => acc Account::ContinuousVesting(acc) => acc
.base_vesting_account .base_vesting_account
.as_ref() .as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref()) .and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable), .ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::DelayedVesting(acc) => acc Account::DelayedVesting(acc) => acc
.base_vesting_account .base_vesting_account
.as_ref() .as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref()) .and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable), .ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::PeriodicVesting(acc) => acc Account::PeriodicVesting(acc) => acc
.base_vesting_account .base_vesting_account
.as_ref() .as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref()) .and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable), .ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::PermanentLockedVesting(acc) => acc Account::PermanentLockedVesting(acc) => acc
.base_vesting_account .base_vesting_account
.as_ref() .as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref()) .and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable), .ok_or(NyxdError::NoBaseAccountInformationAvailable),
} }
} }
} }
impl TryFrom<Any> for Account { impl TryFrom<Any> for Account {
type Error = NymdError; type Error = NyxdError;
fn try_from(raw_account: Any) -> Result<Self, Self::Error> { fn try_from(raw_account: Any) -> Result<Self, Self::Error> {
match raw_account.type_url.as_ref() { match raw_account.type_url.as_ref() {
@@ -328,7 +328,7 @@ impl TryFrom<Any> for Account {
ProtoPermanentLockedAccount::decode(raw_account.value.as_ref())?.try_into()?, ProtoPermanentLockedAccount::decode(raw_account.value.as_ref())?.try_into()?,
)) ))
} }
_ => Err(NymdError::UnsupportedAccountType { _ => Err(NyxdError::UnsupportedAccountType {
type_url: raw_account.type_url, type_url: raw_account.type_url,
}), }),
} }
@@ -347,7 +347,7 @@ pub struct Code {
} }
impl TryFrom<CodeInfoResponse> for Code { impl TryFrom<CodeInfoResponse> for Code {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: CodeInfoResponse) -> Result<Self, Self::Error> { fn try_from(value: CodeInfoResponse) -> Result<Self, Self::Error> {
let CodeInfoResponse { let CodeInfoResponse {
@@ -358,7 +358,7 @@ impl TryFrom<CodeInfoResponse> for Code {
let creator = creator let creator = creator
.parse() .parse()
.map_err(|_| NymdError::MalformedAccountAddress(creator))?; .map_err(|_| NyxdError::MalformedAccountAddress(creator))?;
Ok(Code { Ok(Code {
code_id, code_id,
@@ -391,7 +391,7 @@ pub(crate) struct ContractInfo {
} }
impl TryFrom<ProtoContractInfo> for ContractInfo { impl TryFrom<ProtoContractInfo> for ContractInfo {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoContractInfo) -> Result<Self, Self::Error> { fn try_from(value: ProtoContractInfo) -> Result<Self, Self::Error> {
let ProtoContractInfo { let ProtoContractInfo {
@@ -408,7 +408,7 @@ impl TryFrom<ProtoContractInfo> for ContractInfo {
Some( Some(
admin admin
.parse() .parse()
.map_err(|_| NymdError::MalformedAccountAddress(admin))?, .map_err(|_| NyxdError::MalformedAccountAddress(admin))?,
) )
}; };
@@ -416,7 +416,7 @@ impl TryFrom<ProtoContractInfo> for ContractInfo {
code_id, code_id,
creator: creator creator: creator
.parse() .parse()
.map_err(|_| NymdError::MalformedAccountAddress(creator))?, .map_err(|_| NyxdError::MalformedAccountAddress(creator))?,
admin, admin,
label, label,
}) })
@@ -466,14 +466,14 @@ pub struct ContractCodeHistoryEntry {
} }
impl TryFrom<ProtoContractCodeHistoryEntry> for ContractCodeHistoryEntry { impl TryFrom<ProtoContractCodeHistoryEntry> for ContractCodeHistoryEntry {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoContractCodeHistoryEntry) -> Result<Self, Self::Error> { fn try_from(value: ProtoContractCodeHistoryEntry) -> Result<Self, Self::Error> {
let operation = match ContractCodeHistoryOperationType::from_i32(value.operation) let operation = match ContractCodeHistoryOperationType::from_i32(value.operation)
.ok_or(NymdError::InvalidContractHistoryOperation)? .ok_or(NyxdError::InvalidContractHistoryOperation)?
{ {
ContractCodeHistoryOperationType::Unspecified => { ContractCodeHistoryOperationType::Unspecified => {
return Err(NymdError::InvalidContractHistoryOperation) return Err(NyxdError::InvalidContractHistoryOperation)
} }
ContractCodeHistoryOperationType::Init => ContractCodeHistoryEntryOperation::Init, ContractCodeHistoryOperationType::Init => ContractCodeHistoryEntryOperation::Init,
ContractCodeHistoryOperationType::Genesis => ContractCodeHistoryEntryOperation::Genesis, ContractCodeHistoryOperationType::Genesis => ContractCodeHistoryEntryOperation::Genesis,
@@ -484,7 +484,7 @@ impl TryFrom<ProtoContractCodeHistoryEntry> for ContractCodeHistoryEntry {
operation, operation,
code_id: value.code_id, code_id: value.code_id,
msg_json: String::from_utf8(value.msg) msg_json: String::from_utf8(value.msg)
.map_err(|_| NymdError::DeserializationError("Contract history msg".to_owned()))?, .map_err(|_| NyxdError::DeserializationError("Contract history msg".to_owned()))?,
}) })
} }
} }
@@ -532,7 +532,7 @@ pub struct AbciResult {
} }
impl TryFrom<ProtoAbciResult> for AbciResult { impl TryFrom<ProtoAbciResult> for AbciResult {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoAbciResult) -> Result<Self, Self::Error> { fn try_from(value: ProtoAbciResult) -> Result<Self, Self::Error> {
let mut events = Vec::with_capacity(value.events.len()); let mut events = Vec::with_capacity(value.events.len());
@@ -543,9 +543,9 @@ impl TryFrom<ProtoAbciResult> for AbciResult {
let mut attributes = Vec::with_capacity(proto_event.attributes.len()); let mut attributes = Vec::with_capacity(proto_event.attributes.len());
for proto_attribute in proto_event.attributes.into_iter() { for proto_attribute in proto_event.attributes.into_iter() {
let stringified_ked = String::from_utf8(proto_attribute.key) let stringified_ked = String::from_utf8(proto_attribute.key)
.map_err(|_| NymdError::DeserializationError("EventAttributeKey".to_owned()))?; .map_err(|_| NyxdError::DeserializationError("EventAttributeKey".to_owned()))?;
let stringified_value = String::from_utf8(proto_attribute.value) let stringified_value = String::from_utf8(proto_attribute.value)
.map_err(|_| NymdError::DeserializationError("EventAttributeKey".to_owned()))?; .map_err(|_| NyxdError::DeserializationError("EventAttributeKey".to_owned()))?;
attributes.push(abci::tag::Tag { attributes.push(abci::tag::Tag {
key: stringified_ked.parse().unwrap(), key: stringified_ked.parse().unwrap(),
@@ -574,7 +574,7 @@ pub struct SimulateResponse {
} }
impl TryFrom<ProtoSimulateResponse> for SimulateResponse { impl TryFrom<ProtoSimulateResponse> for SimulateResponse {
type Error = NymdError; type Error = NyxdError;
fn try_from(value: ProtoSimulateResponse) -> Result<Self, Self::Error> { fn try_from(value: ProtoSimulateResponse) -> Result<Self, Self::Error> {
Ok(SimulateResponse { Ok(SimulateResponse {
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::types::ContractCodeId; use crate::nyxd::cosmwasm_client::types::ContractCodeId;
use cosmrs::{ use cosmrs::{
bip32, bip32,
rpc::endpoint::abci_query::AbciQuery, rpc::endpoint::abci_query::AbciQuery,
@@ -21,7 +21,7 @@ pub use cosmrs::rpc::{
}; };
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum NymdError { pub enum NyxdError {
#[error("No contract address is available to perform the call")] #[error("No contract address is available to perform the call")]
NoContractAddressAvailable, NoContractAddressAvailable,
@@ -148,10 +148,10 @@ pub enum NymdError {
// The purpose of parsing the abci query result is that we want to generate the `pretty_log` if // The purpose of parsing the abci query result is that we want to generate the `pretty_log` if
// possible. // possible.
pub fn parse_abci_query_result(query_result: AbciQuery) -> Result<AbciQuery, NymdError> { pub fn parse_abci_query_result(query_result: AbciQuery) -> Result<AbciQuery, NyxdError> {
match query_result.code { match query_result.code {
AbciCode::Ok => Ok(query_result), AbciCode::Ok => Ok(query_result),
AbciCode::Err(code) => Err(NymdError::AbciError { AbciCode::Err(code) => Err(NyxdError::AbciError {
code, code,
log: query_result.log.clone(), log: query_result.log.clone(),
pretty_log: try_parse_abci_log(&query_result.log), pretty_log: try_parse_abci_log(&query_result.log),
@@ -172,10 +172,10 @@ fn try_parse_abci_log(log: &abci::Log) -> Option<String> {
} }
} }
impl NymdError { impl NyxdError {
pub fn is_tendermint_response_timeout(&self) -> bool { pub fn is_tendermint_response_timeout(&self) -> bool {
match &self { match &self {
NymdError::TendermintError(TendermintRpcError( NyxdError::TendermintError(TendermintRpcError(
TendermintRpcErrorDetail::Response(err), TendermintRpcErrorDetail::Response(err),
_, _,
)) => { )) => {
@@ -202,7 +202,7 @@ impl NymdError {
pub fn is_tendermint_response_duplicate(&self) -> bool { pub fn is_tendermint_response_duplicate(&self) -> bool {
match &self { match &self {
NymdError::TendermintError(TendermintRpcError( NyxdError::TendermintError(TendermintRpcError(
TendermintRpcErrorDetail::Response(err), TendermintRpcErrorDetail::Response(err),
_, _,
)) => { )) => {
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use config::defaults; use config::defaults;
use cosmrs::tx::Gas; use cosmrs::tx::Gas;
use cosmrs::Coin; use cosmrs::Coin;
@@ -55,7 +55,7 @@ impl<'a> Mul<Gas> for &'a GasPrice {
} }
impl FromStr for GasPrice { impl FromStr for GasPrice {
type Err = NymdError; type Err = NyxdError;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
let possible_amount = s let possible_amount = s
@@ -65,7 +65,7 @@ impl FromStr for GasPrice {
let amount_len = possible_amount.len(); let amount_len = possible_amount.len();
let amount = possible_amount let amount = possible_amount
.parse() .parse()
.map_err(|_| NymdError::MalformedGasPrice)?; .map_err(|_| NyxdError::MalformedGasPrice)?;
let possible_denom = s.chars().skip(amount_len).collect::<String>(); let possible_denom = s.chars().skip(amount_len).collect::<String>();
let denom = possible_denom.trim().to_string(); let denom = possible_denom.trim().to_string();
@@ -74,7 +74,7 @@ impl FromStr for GasPrice {
} }
impl GasPrice { impl GasPrice {
pub fn new_with_default_price(denom: &str) -> Result<Self, NymdError> { pub fn new_with_default_price(denom: &str) -> Result<Self, NyxdError> {
format!("{}{}", defaults::GAS_PRICE_AMOUNT, denom).parse() format!("{}{}", defaults::GAS_PRICE_AMOUNT, denom).parse()
} }
} }
@@ -1,8 +1,8 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::Coin; use crate::nyxd::Coin;
use crate::nymd::Gas; use crate::nyxd::Gas;
use cosmrs::{tx, AccountId}; use cosmrs::{tx, AccountId};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
@@ -1,14 +1,14 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::signing_client; use crate::nyxd::cosmwasm_client::signing_client;
use crate::nymd::cosmwasm_client::types::{ use crate::nyxd::cosmwasm_client::types::{
Account, ChangeAdminResult, ContractCodeId, ExecuteResult, InstantiateOptions, Account, ChangeAdminResult, ContractCodeId, ExecuteResult, InstantiateOptions,
InstantiateResult, MigrateResult, SequenceResponse, SimulateResponse, UploadResult, InstantiateResult, MigrateResult, SequenceResponse, SimulateResponse, UploadResult,
}; };
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::fee::DEFAULT_SIMULATED_GAS_MULTIPLIER; use crate::nyxd::fee::DEFAULT_SIMULATED_GAS_MULTIPLIER;
use crate::nymd::wallet::DirectSecp256k1HdWallet; use crate::nyxd::wallet::DirectSecp256k1HdWallet;
use cosmrs::cosmwasm; use cosmrs::cosmwasm;
use cosmrs::rpc::endpoint::block::Response as BlockResponse; use cosmrs::rpc::endpoint::block::Response as BlockResponse;
use cosmrs::rpc::query::Query; use cosmrs::rpc::query::Query;
@@ -22,14 +22,14 @@ use std::convert::TryInto;
use std::time::SystemTime; use std::time::SystemTime;
use vesting_contract_common::ExecuteMsg as VestingExecuteMsg; use vesting_contract_common::ExecuteMsg as VestingExecuteMsg;
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient; pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient; pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
pub use crate::nymd::fee::Fee; pub use crate::nyxd::fee::Fee;
pub use coin::Coin; pub use coin::Coin;
pub use cosmrs::bank::MsgSend; pub use cosmrs::bank::MsgSend;
pub use cosmrs::rpc::endpoint::tx::Response as TxResponse; pub use cosmrs::rpc::endpoint::tx::Response as TxResponse;
pub use cosmrs::rpc::endpoint::validators::Response as ValidatorResponse; pub use cosmrs::rpc::endpoint::validators::Response as ValidatorResponse;
pub use cosmrs::rpc::HttpClient as QueryNymdClient; pub use cosmrs::rpc::HttpClient as QueryNyxdClient;
pub use cosmrs::rpc::Paging; pub use cosmrs::rpc::Paging;
pub use cosmrs::tendermint::abci::responses::{DeliverTx, Event}; pub use cosmrs::tendermint::abci::responses::{DeliverTx, Event};
pub use cosmrs::tendermint::abci::tag::Tag; pub use cosmrs::tendermint::abci::tag::Tag;
@@ -43,7 +43,7 @@ pub use cosmrs::{bip32, AccountId, Decimal, Denom};
pub use cosmwasm_std::Coin as CosmWasmCoin; pub use cosmwasm_std::Coin as CosmWasmCoin;
pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment}; pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment};
use mixnet_contract_common::MixId; use mixnet_contract_common::MixId;
pub use signing_client::Client as SigningNymdClient; pub use signing_client::Client as SigningNyxdClient;
pub use traits::{VestingQueryClient, VestingSigningClient}; pub use traits::{VestingQueryClient, VestingSigningClient};
use vesting_contract_common::PledgeCap; use vesting_contract_common::PledgeCap;
@@ -74,13 +74,13 @@ impl Config {
fn parse_optional_account( fn parse_optional_account(
raw: Option<&String>, raw: Option<&String>,
expected_prefix: &str, expected_prefix: &str,
) -> Result<Option<AccountId>, NymdError> { ) -> Result<Option<AccountId>, NyxdError> {
if let Some(address) = raw { if let Some(address) = raw {
let parsed: AccountId = address let parsed: AccountId = address
.parse() .parse()
.map_err(|_| NymdError::MalformedAccountAddress(address.clone()))?; .map_err(|_| NyxdError::MalformedAccountAddress(address.clone()))?;
if parsed.prefix() != expected_prefix { if parsed.prefix() != expected_prefix {
Err(NymdError::UnexpectedBech32Prefix { Err(NyxdError::UnexpectedBech32Prefix {
got: parsed.prefix().into(), got: parsed.prefix().into(),
expected: expected_prefix.into(), expected: expected_prefix.into(),
}) })
@@ -92,7 +92,7 @@ impl Config {
} }
} }
pub fn try_from_nym_network_details(details: &NymNetworkDetails) -> Result<Self, NymdError> { pub fn try_from_nym_network_details(details: &NymNetworkDetails) -> Result<Self, NyxdError> {
let prefix = &details.chain_details.bech32_account_prefix; let prefix = &details.chain_details.bech32_account_prefix;
Ok(Config { Ok(Config {
chain_details: details.chain_details.clone(), chain_details: details.chain_details.clone(),
@@ -128,20 +128,20 @@ impl Config {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct NymdClient<C> { pub struct NyxdClient<C> {
client: C, client: C,
config: Config, config: Config,
client_address: Option<Vec<AccountId>>, client_address: Option<Vec<AccountId>>,
simulated_gas_multiplier: f32, simulated_gas_multiplier: f32,
} }
impl NymdClient<QueryNymdClient> { impl NyxdClient<QueryNyxdClient> {
pub fn connect<U>(config: Config, endpoint: U) -> Result<NymdClient<QueryNymdClient>, NymdError> pub fn connect<U>(config: Config, endpoint: U) -> Result<NyxdClient<QueryNyxdClient>, NyxdError>
where where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>, U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{ {
Ok(NymdClient { Ok(NyxdClient {
client: QueryNymdClient::new(endpoint)?, client: QueryNyxdClient::new(endpoint)?,
config, config,
client_address: None, client_address: None,
simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER, simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER,
@@ -149,7 +149,7 @@ impl NymdClient<QueryNymdClient> {
} }
} }
impl NymdClient<SigningNymdClient> { impl NyxdClient<SigningNyxdClient> {
// maybe the wallet could be made into a generic, but for now, let's just have this one implementation // maybe the wallet could be made into a generic, but for now, let's just have this one implementation
pub fn connect_with_signer<U: Clone>( pub fn connect_with_signer<U: Clone>(
config: Config, config: Config,
@@ -157,7 +157,7 @@ impl NymdClient<SigningNymdClient> {
endpoint: U, endpoint: U,
signer: DirectSecp256k1HdWallet, signer: DirectSecp256k1HdWallet,
gas_price: Option<GasPrice>, gas_price: Option<GasPrice>,
) -> Result<NymdClient<SigningNymdClient>, NymdError> ) -> Result<NyxdClient<SigningNyxdClient>, NyxdError>
where where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>, U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{ {
@@ -169,8 +169,8 @@ impl NymdClient<SigningNymdClient> {
.collect(); .collect();
let gas_price = gas_price.unwrap_or(GasPrice::new_with_default_price(&denom)?); let gas_price = gas_price.unwrap_or(GasPrice::new_with_default_price(&denom)?);
Ok(NymdClient { Ok(NyxdClient {
client: SigningNymdClient::connect_with_signer(endpoint, signer, gas_price)?, client: SigningNyxdClient::connect_with_signer(endpoint, signer, gas_price)?,
config, config,
client_address: Some(client_address), client_address: Some(client_address),
simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER, simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER,
@@ -182,7 +182,7 @@ impl NymdClient<SigningNymdClient> {
endpoint: U, endpoint: U,
mnemonic: bip39::Mnemonic, mnemonic: bip39::Mnemonic,
gas_price: Option<GasPrice>, gas_price: Option<GasPrice>,
) -> Result<NymdClient<SigningNymdClient>, NymdError> ) -> Result<NyxdClient<SigningNyxdClient>, NyxdError>
where where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>, U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{ {
@@ -196,8 +196,8 @@ impl NymdClient<SigningNymdClient> {
.collect(); .collect();
let gas_price = gas_price.unwrap_or(GasPrice::new_with_default_price(denom)?); let gas_price = gas_price.unwrap_or(GasPrice::new_with_default_price(denom)?);
Ok(NymdClient { Ok(NyxdClient {
client: SigningNymdClient::connect_with_signer(endpoint, wallet, gas_price)?, client: SigningNyxdClient::connect_with_signer(endpoint, wallet, gas_price)?,
config, config,
client_address: Some(client_address), client_address: Some(client_address),
simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER, simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER,
@@ -205,7 +205,7 @@ impl NymdClient<SigningNymdClient> {
} }
} }
impl<C> NymdClient<C> { impl<C> NyxdClient<C> {
pub fn current_config(&self) -> &Config { pub fn current_config(&self) -> &Config {
&self.config &self.config
} }
@@ -234,7 +234,7 @@ impl<C> NymdClient<C> {
self.config.multisig_contract_address = Some(address); self.config.multisig_contract_address = Some(address);
} }
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits // TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally // note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address, // occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it) // so it's not introducing new source of failure (just moves it)
@@ -242,7 +242,7 @@ impl<C> NymdClient<C> {
self.config.mixnet_contract_address.as_ref().unwrap() self.config.mixnet_contract_address.as_ref().unwrap()
} }
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits // TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally // note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address, // occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it) // so it's not introducing new source of failure (just moves it)
@@ -250,7 +250,7 @@ impl<C> NymdClient<C> {
self.config.vesting_contract_address.as_ref().unwrap() self.config.vesting_contract_address.as_ref().unwrap()
} }
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits // TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally // note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address, // occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it) // so it's not introducing new source of failure (just moves it)
@@ -261,7 +261,7 @@ impl<C> NymdClient<C> {
.unwrap() .unwrap()
} }
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits // TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally // note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address, // occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it) // so it's not introducing new source of failure (just moves it)
@@ -272,7 +272,7 @@ impl<C> NymdClient<C> {
.unwrap() .unwrap()
} }
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits // TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally // note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address, // occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it) // so it's not introducing new source of failure (just moves it)
@@ -280,7 +280,7 @@ impl<C> NymdClient<C> {
self.config.multisig_contract_address.as_ref().unwrap() self.config.multisig_contract_address.as_ref().unwrap()
} }
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits // TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally // note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address, // occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it) // so it's not introducing new source of failure (just moves it)
@@ -296,7 +296,7 @@ impl<C> NymdClient<C> {
&self, &self,
contract: &AccountId, contract: &AccountId,
query_msg: &M, query_msg: &M,
) -> Result<T, NymdError> ) -> Result<T, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
M: ?Sized + Serialize + Sync, M: ?Sized + Serialize + Sync,
@@ -309,7 +309,7 @@ impl<C> NymdClient<C> {
&self, &self,
contract: &AccountId, contract: &AccountId,
query_data: Vec<u8>, query_data: Vec<u8>,
) -> Result<Vec<u8>, NymdError> ) -> Result<Vec<u8>, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
@@ -321,7 +321,7 @@ impl<C> NymdClient<C> {
contract_address: &AccountId, contract_address: &AccountId,
msg: &M, msg: &M,
funds: Vec<Coin>, funds: Vec<Coin>,
) -> Result<cosmwasm::MsgExecuteContract, NymdError> ) -> Result<cosmwasm::MsgExecuteContract, NyxdError>
where where
C: SigningCosmWasmClient, C: SigningCosmWasmClient,
M: ?Sized + Serialize, M: ?Sized + Serialize,
@@ -366,7 +366,7 @@ impl<C> NymdClient<C> {
// CHAIN QUERIES // CHAIN QUERIES
pub async fn account_sequence(&self) -> Result<SequenceResponse, NymdError> pub async fn account_sequence(&self) -> Result<SequenceResponse, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
{ {
@@ -376,7 +376,7 @@ impl<C> NymdClient<C> {
pub async fn get_account_details( pub async fn get_account_details(
&self, &self,
address: &AccountId, address: &AccountId,
) -> Result<Option<Account>, NymdError> ) -> Result<Option<Account>, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
@@ -386,7 +386,7 @@ impl<C> NymdClient<C> {
pub async fn get_account_public_key( pub async fn get_account_public_key(
&self, &self,
address: &AccountId, address: &AccountId,
) -> Result<Option<cosmrs::crypto::PublicKey>, NymdError> ) -> Result<Option<cosmrs::crypto::PublicKey>, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
@@ -398,7 +398,7 @@ impl<C> NymdClient<C> {
Ok(None) Ok(None)
} }
pub async fn get_current_block_timestamp(&self) -> Result<TendermintTime, NymdError> pub async fn get_current_block_timestamp(&self) -> Result<TendermintTime, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
@@ -408,21 +408,21 @@ impl<C> NymdClient<C> {
pub async fn get_block_timestamp( pub async fn get_block_timestamp(
&self, &self,
height: Option<u32>, height: Option<u32>,
) -> Result<TendermintTime, NymdError> ) -> Result<TendermintTime, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
Ok(self.client.get_block(height).await?.block.header.time) Ok(self.client.get_block(height).await?.block.header.time)
} }
pub async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NymdError> pub async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
self.client.get_block(height).await self.client.get_block(height).await
} }
pub async fn get_current_block_height(&self) -> Result<Height, NymdError> pub async fn get_current_block_height(&self) -> Result<Height, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
@@ -434,7 +434,7 @@ impl<C> NymdClient<C> {
/// # Arguments /// # Arguments
/// ///
/// * `height`: height of the block for which we want to obtain the hash. /// * `height`: height of the block for which we want to obtain the hash.
pub async fn get_block_hash(&self, height: u32) -> Result<hash::Hash, NymdError> pub async fn get_block_hash(&self, height: u32) -> Result<hash::Hash, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
@@ -448,7 +448,7 @@ impl<C> NymdClient<C> {
&self, &self,
height: u64, height: u64,
paging: Paging, paging: Paging,
) -> Result<ValidatorResponse, NymdError> ) -> Result<ValidatorResponse, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
@@ -459,42 +459,42 @@ impl<C> NymdClient<C> {
&self, &self,
address: &AccountId, address: &AccountId,
denom: String, denom: String,
) -> Result<Option<Coin>, NymdError> ) -> Result<Option<Coin>, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
self.client.get_balance(address, denom).await self.client.get_balance(address, denom).await
} }
pub async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NymdError> pub async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
self.client.get_all_balances(address).await self.client.get_all_balances(address).await
} }
pub async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NymdError> pub async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
self.client.get_tx(id).await self.client.get_tx(id).await
} }
pub async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NymdError> pub async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
self.client.search_tx(query).await self.client.search_tx(query).await
} }
pub async fn get_total_supply(&self) -> Result<Vec<Coin>, NymdError> pub async fn get_total_supply(&self) -> Result<Vec<Coin>, NyxdError>
where where
C: CosmWasmClient + Sync, C: CosmWasmClient + Sync,
{ {
self.client.get_total_supply().await self.client.get_total_supply().await
} }
pub async fn simulate<I, M>(&self, messages: I) -> Result<SimulateResponse, NymdError> pub async fn simulate<I, M>(&self, messages: I) -> Result<SimulateResponse, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
I: IntoIterator<Item = M> + Send, I: IntoIterator<Item = M> + Send,
@@ -508,7 +508,7 @@ impl<C> NymdClient<C> {
.map(|msg| msg.into_any()) .map(|msg| msg.into_any())
.collect::<Result<Vec<_>, _>>() .collect::<Result<Vec<_>, _>>()
.map_err(|_| { .map_err(|_| {
NymdError::SerializationError("custom simulate messages".to_owned()) NyxdError::SerializationError("custom simulate messages".to_owned())
})?, })?,
"simulating execution of transactions", "simulating execution of transactions",
) )
@@ -522,7 +522,7 @@ impl<C> NymdClient<C> {
amount: Vec<Coin>, amount: Vec<Coin>,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<TxResponse, NymdError> ) -> Result<TxResponse, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
{ {
@@ -538,7 +538,7 @@ impl<C> NymdClient<C> {
msgs: Vec<(AccountId, Vec<Coin>)>, msgs: Vec<(AccountId, Vec<Coin>)>,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<TxResponse, NymdError> ) -> Result<TxResponse, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
{ {
@@ -557,7 +557,7 @@ impl<C> NymdClient<C> {
allowed_messages: Vec<String>, allowed_messages: Vec<String>,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<TxResponse, NymdError> ) -> Result<TxResponse, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
{ {
@@ -581,7 +581,7 @@ impl<C> NymdClient<C> {
grantee: &AccountId, grantee: &AccountId,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<TxResponse, NymdError> ) -> Result<TxResponse, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
{ {
@@ -598,7 +598,7 @@ impl<C> NymdClient<C> {
fee: Option<Fee>, fee: Option<Fee>,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
funds: Vec<Coin>, funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError> ) -> Result<ExecuteResult, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
M: ?Sized + Serialize + Sync, M: ?Sized + Serialize + Sync,
@@ -615,7 +615,7 @@ impl<C> NymdClient<C> {
msgs: I, msgs: I,
fee: Option<Fee>, fee: Option<Fee>,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
) -> Result<ExecuteResult, NymdError> ) -> Result<ExecuteResult, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
I: IntoIterator<Item = (M, Vec<Coin>)> + Send, I: IntoIterator<Item = (M, Vec<Coin>)> + Send,
@@ -632,7 +632,7 @@ impl<C> NymdClient<C> {
wasm_code: Vec<u8>, wasm_code: Vec<u8>,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<UploadResult, NymdError> ) -> Result<UploadResult, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
{ {
@@ -650,7 +650,7 @@ impl<C> NymdClient<C> {
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
options: Option<InstantiateOptions>, options: Option<InstantiateOptions>,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<InstantiateResult, NymdError> ) -> Result<InstantiateResult, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
M: ?Sized + Serialize + Sync, M: ?Sized + Serialize + Sync,
@@ -667,7 +667,7 @@ impl<C> NymdClient<C> {
new_admin: &AccountId, new_admin: &AccountId,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ChangeAdminResult, NymdError> ) -> Result<ChangeAdminResult, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
{ {
@@ -682,7 +682,7 @@ impl<C> NymdClient<C> {
contract_address: &AccountId, contract_address: &AccountId,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ChangeAdminResult, NymdError> ) -> Result<ChangeAdminResult, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
{ {
@@ -699,7 +699,7 @@ impl<C> NymdClient<C> {
msg: &M, msg: &M,
memo: impl Into<String> + Send + 'static, memo: impl Into<String> + Send + 'static,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<MigrateResult, NymdError> ) -> Result<MigrateResult, NyxdError>
where where
C: SigningCosmWasmClient + Sync, C: SigningCosmWasmClient + Sync,
M: ?Sized + Serialize + Sync, M: ?Sized + Serialize + Sync,
@@ -1,8 +1,8 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net> // Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::{CosmWasmClient, NymdClient}; use crate::nyxd::{CosmWasmClient, NyxdClient};
use coconut_bandwidth_contract_common::msg::QueryMsg; use coconut_bandwidth_contract_common::msg::QueryMsg;
use coconut_bandwidth_contract_common::spend_credential::SpendCredentialResponse; use coconut_bandwidth_contract_common::spend_credential::SpendCredentialResponse;
@@ -14,15 +14,15 @@ pub trait CoconutBandwidthQueryClient {
async fn get_spent_credential( async fn get_spent_credential(
&self, &self,
blinded_serial_number: String, blinded_serial_number: String,
) -> Result<SpendCredentialResponse, NymdError>; ) -> Result<SpendCredentialResponse, NyxdError>;
} }
#[async_trait] #[async_trait]
impl<C: CosmWasmClient + Sync + Send> CoconutBandwidthQueryClient for NymdClient<C> { impl<C: CosmWasmClient + Sync + Send> CoconutBandwidthQueryClient for NyxdClient<C> {
async fn get_spent_credential( async fn get_spent_credential(
&self, &self,
blinded_serial_number: String, blinded_serial_number: String,
) -> Result<SpendCredentialResponse, NymdError> { ) -> Result<SpendCredentialResponse, NyxdError> {
let request = QueryMsg::GetSpentCredential { let request = QueryMsg::GetSpentCredential {
blinded_serial_number, blinded_serial_number,
}; };
@@ -1,10 +1,10 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net> // Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient; pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult; use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::{Coin, Fee, NymdClient}; use crate::nyxd::{Coin, Fee, NyxdClient};
use coconut_bandwidth_contract_common::spend_credential::SpendCredentialData; use coconut_bandwidth_contract_common::spend_credential::SpendCredentialData;
use coconut_bandwidth_contract_common::{deposit::DepositData, msg::ExecuteMsg}; use coconut_bandwidth_contract_common::{deposit::DepositData, msg::ExecuteMsg};
@@ -19,18 +19,18 @@ pub trait CoconutBandwidthSigningClient {
verification_key: String, verification_key: String,
encryption_key: String, encryption_key: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn spend_credential( async fn spend_credential(
&self, &self,
funds: Coin, funds: Coin,
blinded_serial_number: String, blinded_serial_number: String,
gateway_cosmos_address: String, gateway_cosmos_address: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
} }
#[async_trait] #[async_trait]
impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for NymdClient<C> { impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for NyxdClient<C> {
async fn deposit( async fn deposit(
&self, &self,
amount: Coin, amount: Coin,
@@ -38,7 +38,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for N
verification_key: String, verification_key: String,
encryption_key: String, encryption_key: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = ExecuteMsg::DepositFunds { let req = ExecuteMsg::DepositFunds {
data: DepositData::new(info.to_string(), verification_key, encryption_key), data: DepositData::new(info.to_string(), verification_key, encryption_key),
@@ -60,7 +60,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for N
blinded_serial_number: String, blinded_serial_number: String,
gateway_cosmos_address: String, gateway_cosmos_address: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = ExecuteMsg::SpendCredential { let req = ExecuteMsg::SpendCredential {
data: SpendCredentialData::new( data: SpendCredentialData::new(
@@ -1,8 +1,8 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net> // Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::{CosmWasmClient, NymdClient}; use crate::nyxd::{CosmWasmClient, NyxdClient};
use async_trait::async_trait; use async_trait::async_trait;
use coconut_dkg_common::dealer::{ use coconut_dkg_common::dealer::{
DealerDetailsResponse, PagedDealerResponse, PagedDealingsResponse, DealerDetailsResponse, PagedDealerResponse, PagedDealingsResponse,
@@ -14,48 +14,48 @@ use cosmrs::AccountId;
#[async_trait] #[async_trait]
pub trait DkgQueryClient { pub trait DkgQueryClient {
async fn get_current_epoch(&self) -> Result<Epoch, NymdError>; async fn get_current_epoch(&self) -> Result<Epoch, NyxdError>;
async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NymdError>; async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NyxdError>;
async fn get_dealer_details( async fn get_dealer_details(
&self, &self,
address: &AccountId, address: &AccountId,
) -> Result<DealerDetailsResponse, NymdError>; ) -> Result<DealerDetailsResponse, NyxdError>;
async fn get_current_dealers_paged( async fn get_current_dealers_paged(
&self, &self,
start_after: Option<String>, start_after: Option<String>,
page_limit: Option<u32>, page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError>; ) -> Result<PagedDealerResponse, NyxdError>;
async fn get_past_dealers_paged( async fn get_past_dealers_paged(
&self, &self,
start_after: Option<String>, start_after: Option<String>,
page_limit: Option<u32>, page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError>; ) -> Result<PagedDealerResponse, NyxdError>;
async fn get_dealings_paged( async fn get_dealings_paged(
&self, &self,
idx: usize, idx: usize,
start_after: Option<String>, start_after: Option<String>,
page_limit: Option<u32>, page_limit: Option<u32>,
) -> Result<PagedDealingsResponse, NymdError>; ) -> Result<PagedDealingsResponse, NyxdError>;
async fn get_vk_shares_paged( async fn get_vk_shares_paged(
&self, &self,
start_after: Option<String>, start_after: Option<String>,
page_limit: Option<u32>, page_limit: Option<u32>,
) -> Result<PagedVKSharesResponse, NymdError>; ) -> Result<PagedVKSharesResponse, NyxdError>;
} }
#[async_trait] #[async_trait]
impl<C> DkgQueryClient for NymdClient<C> impl<C> DkgQueryClient for NyxdClient<C>
where where
C: CosmWasmClient + Send + Sync, C: CosmWasmClient + Send + Sync,
{ {
async fn get_current_epoch(&self) -> Result<Epoch, NymdError> { async fn get_current_epoch(&self) -> Result<Epoch, NyxdError> {
let request = DkgQueryMsg::GetCurrentEpochState {}; let request = DkgQueryMsg::GetCurrentEpochState {};
self.client self.client
.query_contract_smart(self.coconut_dkg_contract_address(), &request) .query_contract_smart(self.coconut_dkg_contract_address(), &request)
.await .await
} }
async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NymdError> { async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NyxdError> {
let request = DkgQueryMsg::GetCurrentEpochThreshold {}; let request = DkgQueryMsg::GetCurrentEpochThreshold {};
self.client self.client
.query_contract_smart(self.coconut_dkg_contract_address(), &request) .query_contract_smart(self.coconut_dkg_contract_address(), &request)
@@ -64,7 +64,7 @@ where
async fn get_dealer_details( async fn get_dealer_details(
&self, &self,
address: &AccountId, address: &AccountId,
) -> Result<DealerDetailsResponse, NymdError> { ) -> Result<DealerDetailsResponse, NyxdError> {
let request = DkgQueryMsg::GetDealerDetails { let request = DkgQueryMsg::GetDealerDetails {
dealer_address: address.to_string(), dealer_address: address.to_string(),
}; };
@@ -77,7 +77,7 @@ where
&self, &self,
start_after: Option<String>, start_after: Option<String>,
page_limit: Option<u32>, page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError> { ) -> Result<PagedDealerResponse, NyxdError> {
let request = DkgQueryMsg::GetCurrentDealers { let request = DkgQueryMsg::GetCurrentDealers {
start_after, start_after,
limit: page_limit, limit: page_limit,
@@ -91,7 +91,7 @@ where
&self, &self,
start_after: Option<String>, start_after: Option<String>,
page_limit: Option<u32>, page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError> { ) -> Result<PagedDealerResponse, NyxdError> {
let request = DkgQueryMsg::GetPastDealers { let request = DkgQueryMsg::GetPastDealers {
start_after, start_after,
limit: page_limit, limit: page_limit,
@@ -106,7 +106,7 @@ where
idx: usize, idx: usize,
start_after: Option<String>, start_after: Option<String>,
page_limit: Option<u32>, page_limit: Option<u32>,
) -> Result<PagedDealingsResponse, NymdError> { ) -> Result<PagedDealingsResponse, NyxdError> {
let request = DkgQueryMsg::GetDealing { let request = DkgQueryMsg::GetDealing {
idx: idx as u64, idx: idx as u64,
limit: page_limit, limit: page_limit,
@@ -121,7 +121,7 @@ where
&self, &self,
start_after: Option<String>, start_after: Option<String>,
page_limit: Option<u32>, page_limit: Option<u32>,
) -> Result<PagedVKSharesResponse, NymdError> { ) -> Result<PagedVKSharesResponse, NyxdError> {
let request = DkgQueryMsg::GetVerificationKeys { let request = DkgQueryMsg::GetVerificationKeys {
limit: page_limit, limit: page_limit,
start_after, start_after,
@@ -1,9 +1,9 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net> // Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::types::ExecuteResult; use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::{Fee, NymdClient, SigningCosmWasmClient}; use crate::nyxd::{Fee, NyxdClient, SigningCosmWasmClient};
use async_trait::async_trait; use async_trait::async_trait;
use coconut_dkg_common::msg::ExecuteMsg as DkgExecuteMsg; use coconut_dkg_common::msg::ExecuteMsg as DkgExecuteMsg;
use coconut_dkg_common::types::EncodedBTEPublicKeyWithProof; use coconut_dkg_common::types::EncodedBTEPublicKeyWithProof;
@@ -12,33 +12,33 @@ use contracts_common::dealings::ContractSafeBytes;
#[async_trait] #[async_trait]
pub trait DkgSigningClient { pub trait DkgSigningClient {
async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError>; async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError>;
async fn register_dealer( async fn register_dealer(
&self, &self,
bte_key: EncodedBTEPublicKeyWithProof, bte_key: EncodedBTEPublicKeyWithProof,
announce_address: String, announce_address: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn submit_dealing_bytes( async fn submit_dealing_bytes(
&self, &self,
commitment: ContractSafeBytes, commitment: ContractSafeBytes,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn submit_verification_key_share( async fn submit_verification_key_share(
&self, &self,
share: VerificationKeyShare, share: VerificationKeyShare,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
} }
#[async_trait] #[async_trait]
impl<C> DkgSigningClient for NymdClient<C> impl<C> DkgSigningClient for NyxdClient<C>
where where
C: SigningCosmWasmClient + Send + Sync, C: SigningCosmWasmClient + Send + Sync,
{ {
async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> { async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::AdvanceEpochState {}; let req = DkgExecuteMsg::AdvanceEpochState {};
self.client self.client
@@ -58,7 +58,7 @@ where
bte_key: EncodedBTEPublicKeyWithProof, bte_key: EncodedBTEPublicKeyWithProof,
announce_address: String, announce_address: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::RegisterDealer { let req = DkgExecuteMsg::RegisterDealer {
bte_key_with_proof: bte_key, bte_key_with_proof: bte_key,
announce_address, announce_address,
@@ -80,7 +80,7 @@ where
&self, &self,
dealing_bytes: ContractSafeBytes, dealing_bytes: ContractSafeBytes,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::CommitDealing { dealing_bytes }; let req = DkgExecuteMsg::CommitDealing { dealing_bytes };
self.client self.client
@@ -99,7 +99,7 @@ where
&self, &self,
share: VerificationKeyShare, share: VerificationKeyShare,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::CommitVerificationKeyShare { share }; let req = DkgExecuteMsg::CommitVerificationKeyShare { share };
self.client self.client
@@ -1,9 +1,9 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net> // Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient; pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::NymdClient; use crate::nyxd::NyxdClient;
use async_trait::async_trait; use async_trait::async_trait;
use cosmrs::AccountId; use cosmrs::AccountId;
use mixnet_contract_common::delegation::{MixNodeDelegationResponse, OwnerProxySubKey}; use mixnet_contract_common::delegation::{MixNodeDelegationResponse, OwnerProxySubKey};
@@ -29,38 +29,38 @@ use serde::Deserialize;
#[async_trait] #[async_trait]
pub trait MixnetQueryClient { pub trait MixnetQueryClient {
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NymdError> async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
where where
for<'a> T: Deserialize<'a>; for<'a> T: Deserialize<'a>;
// state/sys-params-related // state/sys-params-related
async fn get_mixnet_contract_version(&self) -> Result<ContractBuildInformation, NymdError> { async fn get_mixnet_contract_version(&self) -> Result<ContractBuildInformation, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetContractVersion {}) self.query_mixnet_contract(MixnetQueryMsg::GetContractVersion {})
.await .await
} }
async fn get_rewarding_validator_address(&self) -> Result<AccountId, NymdError> { async fn get_rewarding_validator_address(&self) -> Result<AccountId, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetRewardingValidatorAddress {}) self.query_mixnet_contract(MixnetQueryMsg::GetRewardingValidatorAddress {})
.await .await
} }
async fn get_mixnet_contract_settings(&self) -> Result<ContractStateParams, NymdError> { async fn get_mixnet_contract_settings(&self) -> Result<ContractStateParams, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetStateParams {}) self.query_mixnet_contract(MixnetQueryMsg::GetStateParams {})
.await .await
} }
async fn get_mixnet_contract_state(&self) -> Result<ContractState, NymdError> { async fn get_mixnet_contract_state(&self) -> Result<ContractState, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetState {}) self.query_mixnet_contract(MixnetQueryMsg::GetState {})
.await .await
} }
async fn get_rewarding_parameters(&self) -> Result<RewardingParams, NymdError> { async fn get_rewarding_parameters(&self) -> Result<RewardingParams, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetRewardingParams {}) self.query_mixnet_contract(MixnetQueryMsg::GetRewardingParams {})
.await .await
} }
async fn get_current_interval_details(&self) -> Result<CurrentIntervalResponse, NymdError> { async fn get_current_interval_details(&self) -> Result<CurrentIntervalResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetCurrentIntervalDetails {}) self.query_mixnet_contract(MixnetQueryMsg::GetCurrentIntervalDetails {})
.await .await
} }
@@ -69,7 +69,7 @@ pub trait MixnetQueryClient {
&self, &self,
start_after: Option<MixId>, start_after: Option<MixId>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<PagedRewardedSetResponse, NymdError> { ) -> Result<PagedRewardedSetResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetRewardedSet { limit, start_after }) self.query_mixnet_contract(MixnetQueryMsg::GetRewardedSet { limit, start_after })
.await .await
} }
@@ -78,7 +78,7 @@ pub trait MixnetQueryClient {
&self, &self,
start_after: Option<String>, start_after: Option<String>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<PagedFamiliesResponse, NymdError> { ) -> Result<PagedFamiliesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllFamiliesPaged { limit, start_after }) self.query_mixnet_contract(MixnetQueryMsg::GetAllFamiliesPaged { limit, start_after })
.await .await
} }
@@ -87,7 +87,7 @@ pub trait MixnetQueryClient {
&self, &self,
start_after: Option<String>, start_after: Option<String>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<PagedMembersResponse, NymdError> { ) -> Result<PagedMembersResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllMembersPaged { limit, start_after }) self.query_mixnet_contract(MixnetQueryMsg::GetAllMembersPaged { limit, start_after })
.await .await
} }
@@ -98,7 +98,7 @@ pub trait MixnetQueryClient {
&self, &self,
limit: Option<u32>, limit: Option<u32>,
start_after: Option<MixId>, start_after: Option<MixId>,
) -> Result<PagedMixnodeBondsResponse, NymdError> { ) -> Result<PagedMixnodeBondsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixNodeBonds { limit, start_after }) self.query_mixnet_contract(MixnetQueryMsg::GetMixNodeBonds { limit, start_after })
.await .await
} }
@@ -107,7 +107,7 @@ pub trait MixnetQueryClient {
&self, &self,
limit: Option<u32>, limit: Option<u32>,
start_after: Option<MixId>, start_after: Option<MixId>,
) -> Result<PagedMixnodesDetailsResponse, NymdError> { ) -> Result<PagedMixnodesDetailsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixNodesDetailed { limit, start_after }) self.query_mixnet_contract(MixnetQueryMsg::GetMixNodesDetailed { limit, start_after })
.await .await
} }
@@ -116,7 +116,7 @@ pub trait MixnetQueryClient {
&self, &self,
limit: Option<u32>, limit: Option<u32>,
start_after: Option<MixId>, start_after: Option<MixId>,
) -> Result<PagedUnbondedMixnodesResponse, NymdError> { ) -> Result<PagedUnbondedMixnodesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodes { limit, start_after }) self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodes { limit, start_after })
.await .await
} }
@@ -126,7 +126,7 @@ pub trait MixnetQueryClient {
owner: &AccountId, owner: &AccountId,
limit: Option<u32>, limit: Option<u32>,
start_after: Option<MixId>, start_after: Option<MixId>,
) -> Result<PagedUnbondedMixnodesResponse, NymdError> { ) -> Result<PagedUnbondedMixnodesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodesByOwner { self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodesByOwner {
owner: owner.to_string(), owner: owner.to_string(),
limit, limit,
@@ -140,7 +140,7 @@ pub trait MixnetQueryClient {
identity_key: String, identity_key: String,
limit: Option<u32>, limit: Option<u32>,
start_after: Option<MixId>, start_after: Option<MixId>,
) -> Result<PagedUnbondedMixnodesResponse, NymdError> { ) -> Result<PagedUnbondedMixnodesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodesByIdentityKey { self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodesByIdentityKey {
identity_key, identity_key,
limit, limit,
@@ -152,7 +152,7 @@ pub trait MixnetQueryClient {
async fn get_owned_mixnode( async fn get_owned_mixnode(
&self, &self,
address: &AccountId, address: &AccountId,
) -> Result<MixOwnershipResponse, NymdError> { ) -> Result<MixOwnershipResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetOwnedMixnode { self.query_mixnet_contract(MixnetQueryMsg::GetOwnedMixnode {
address: address.to_string(), address: address.to_string(),
}) })
@@ -162,7 +162,7 @@ pub trait MixnetQueryClient {
async fn get_mixnode_details( async fn get_mixnode_details(
&self, &self,
mix_id: MixId, mix_id: MixId,
) -> Result<MixnodeDetailsResponse, NymdError> { ) -> Result<MixnodeDetailsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeDetails { mix_id }) self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeDetails { mix_id })
.await .await
} }
@@ -170,7 +170,7 @@ pub trait MixnetQueryClient {
async fn get_mixnode_rewarding_details( async fn get_mixnode_rewarding_details(
&self, &self,
mix_id: MixId, mix_id: MixId,
) -> Result<MixnodeRewardingDetailsResponse, NymdError> { ) -> Result<MixnodeRewardingDetailsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeRewardingDetails { mix_id }) self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeRewardingDetails { mix_id })
.await .await
} }
@@ -178,7 +178,7 @@ pub trait MixnetQueryClient {
async fn get_mixnode_stake_saturation( async fn get_mixnode_stake_saturation(
&self, &self,
mix_id: MixId, mix_id: MixId,
) -> Result<StakeSaturationResponse, NymdError> { ) -> Result<StakeSaturationResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetStakeSaturation { mix_id }) self.query_mixnet_contract(MixnetQueryMsg::GetStakeSaturation { mix_id })
.await .await
} }
@@ -186,12 +186,12 @@ pub trait MixnetQueryClient {
async fn get_unbonded_mixnode_information( async fn get_unbonded_mixnode_information(
&self, &self,
mix_id: MixId, mix_id: MixId,
) -> Result<UnbondedMixnodeResponse, NymdError> { ) -> Result<UnbondedMixnodeResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodeInformation { mix_id }) self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodeInformation { mix_id })
.await .await
} }
async fn get_layer_distribution(&self) -> Result<LayerDistribution, NymdError> { async fn get_layer_distribution(&self) -> Result<LayerDistribution, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetLayerDistribution {}) self.query_mixnet_contract(MixnetQueryMsg::GetLayerDistribution {})
.await .await
} }
@@ -202,7 +202,7 @@ pub trait MixnetQueryClient {
&self, &self,
start_after: Option<IdentityKey>, start_after: Option<IdentityKey>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<PagedGatewayResponse, NymdError> { ) -> Result<PagedGatewayResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetGateways { start_after, limit }) self.query_mixnet_contract(MixnetQueryMsg::GetGateways { start_after, limit })
.await .await
} }
@@ -211,7 +211,7 @@ pub trait MixnetQueryClient {
async fn get_gateway_bond( async fn get_gateway_bond(
&self, &self,
identity: IdentityKey, identity: IdentityKey,
) -> Result<GatewayBondResponse, NymdError> { ) -> Result<GatewayBondResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetGatewayBond { identity }) self.query_mixnet_contract(MixnetQueryMsg::GetGatewayBond { identity })
.await .await
} }
@@ -220,7 +220,7 @@ pub trait MixnetQueryClient {
async fn get_owned_gateway( async fn get_owned_gateway(
&self, &self,
address: &AccountId, address: &AccountId,
) -> Result<GatewayOwnershipResponse, NymdError> { ) -> Result<GatewayOwnershipResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetOwnedGateway { self.query_mixnet_contract(MixnetQueryMsg::GetOwnedGateway {
address: address.to_string(), address: address.to_string(),
}) })
@@ -235,7 +235,7 @@ pub trait MixnetQueryClient {
mix_id: MixId, mix_id: MixId,
start_after: Option<String>, start_after: Option<String>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<PagedMixNodeDelegationsResponse, NymdError> { ) -> Result<PagedMixNodeDelegationsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeDelegations { self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeDelegations {
mix_id, mix_id,
start_after, start_after,
@@ -250,7 +250,7 @@ pub trait MixnetQueryClient {
delegator: String, delegator: String,
start_after: Option<(MixId, OwnerProxySubKey)>, start_after: Option<(MixId, OwnerProxySubKey)>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<PagedDelegatorDelegationsResponse, NymdError> { ) -> Result<PagedDelegatorDelegationsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetDelegatorDelegations { self.query_mixnet_contract(MixnetQueryMsg::GetDelegatorDelegations {
delegator, delegator,
start_after, start_after,
@@ -265,7 +265,7 @@ pub trait MixnetQueryClient {
mix_id: MixId, mix_id: MixId,
delegator: &AccountId, delegator: &AccountId,
proxy: Option<String>, proxy: Option<String>,
) -> Result<MixNodeDelegationResponse, NymdError> { ) -> Result<MixNodeDelegationResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetDelegationDetails { self.query_mixnet_contract(MixnetQueryMsg::GetDelegationDetails {
mix_id, mix_id,
delegator: delegator.to_string(), delegator: delegator.to_string(),
@@ -279,7 +279,7 @@ pub trait MixnetQueryClient {
&self, &self,
start_after: Option<delegation::StorageKey>, start_after: Option<delegation::StorageKey>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<PagedAllDelegationsResponse, NymdError> { ) -> Result<PagedAllDelegationsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllDelegations { start_after, limit }) self.query_mixnet_contract(MixnetQueryMsg::GetAllDelegations { start_after, limit })
.await .await
} }
@@ -288,7 +288,7 @@ pub trait MixnetQueryClient {
async fn get_pending_operator_reward( async fn get_pending_operator_reward(
&self, &self,
operator: &AccountId, operator: &AccountId,
) -> Result<PendingRewardResponse, NymdError> { ) -> Result<PendingRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingOperatorReward { self.query_mixnet_contract(MixnetQueryMsg::GetPendingOperatorReward {
address: operator.to_string(), address: operator.to_string(),
}) })
@@ -298,7 +298,7 @@ pub trait MixnetQueryClient {
async fn get_pending_mixnode_operator_reward( async fn get_pending_mixnode_operator_reward(
&self, &self,
mix_id: MixId, mix_id: MixId,
) -> Result<PendingRewardResponse, NymdError> { ) -> Result<PendingRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingMixNodeOperatorReward { mix_id }) self.query_mixnet_contract(MixnetQueryMsg::GetPendingMixNodeOperatorReward { mix_id })
.await .await
} }
@@ -308,7 +308,7 @@ pub trait MixnetQueryClient {
delegator: &AccountId, delegator: &AccountId,
mix_id: MixId, mix_id: MixId,
proxy: Option<String>, proxy: Option<String>,
) -> Result<PendingRewardResponse, NymdError> { ) -> Result<PendingRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingDelegatorReward { self.query_mixnet_contract(MixnetQueryMsg::GetPendingDelegatorReward {
address: delegator.to_string(), address: delegator.to_string(),
mix_id, mix_id,
@@ -322,7 +322,7 @@ pub trait MixnetQueryClient {
&self, &self,
mix_id: MixId, mix_id: MixId,
estimated_performance: Performance, estimated_performance: Performance,
) -> Result<EstimatedCurrentEpochRewardResponse, NymdError> { ) -> Result<EstimatedCurrentEpochRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetEstimatedCurrentEpochOperatorReward { self.query_mixnet_contract(MixnetQueryMsg::GetEstimatedCurrentEpochOperatorReward {
mix_id, mix_id,
estimated_performance, estimated_performance,
@@ -337,7 +337,7 @@ pub trait MixnetQueryClient {
mix_id: MixId, mix_id: MixId,
proxy: Option<String>, proxy: Option<String>,
estimated_performance: Performance, estimated_performance: Performance,
) -> Result<EstimatedCurrentEpochRewardResponse, NymdError> { ) -> Result<EstimatedCurrentEpochRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetEstimatedCurrentEpochDelegatorReward { self.query_mixnet_contract(MixnetQueryMsg::GetEstimatedCurrentEpochDelegatorReward {
address: delegator.to_string(), address: delegator.to_string(),
mix_id, mix_id,
@@ -353,7 +353,7 @@ pub trait MixnetQueryClient {
&self, &self,
start_after: Option<EpochEventId>, start_after: Option<EpochEventId>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<PendingEpochEventsResponse, NymdError> { ) -> Result<PendingEpochEventsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingEpochEvents { start_after, limit }) self.query_mixnet_contract(MixnetQueryMsg::GetPendingEpochEvents { start_after, limit })
.await .await
} }
@@ -362,7 +362,7 @@ pub trait MixnetQueryClient {
&self, &self,
start_after: Option<IntervalEventId>, start_after: Option<IntervalEventId>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<PendingIntervalEventsResponse, NymdError> { ) -> Result<PendingIntervalEventsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingIntervalEvents { start_after, limit }) self.query_mixnet_contract(MixnetQueryMsg::GetPendingIntervalEvents { start_after, limit })
.await .await
} }
@@ -370,21 +370,21 @@ pub trait MixnetQueryClient {
async fn get_mixnode_details_by_identity( async fn get_mixnode_details_by_identity(
&self, &self,
mix_identity: IdentityKey, mix_identity: IdentityKey,
) -> Result<Option<MixNodeDetails>, NymdError> { ) -> Result<Option<MixNodeDetails>, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetBondedMixnodeDetailsByIdentity { self.query_mixnet_contract(MixnetQueryMsg::GetBondedMixnodeDetailsByIdentity {
mix_identity, mix_identity,
}) })
.await .await
} }
async fn get_node_family_by_label(&self, label: &str) -> Result<Option<Family>, NymdError> { async fn get_node_family_by_label(&self, label: &str) -> Result<Option<Family>, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByLabel { self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByLabel {
label: label.to_string(), label: label.to_string(),
}) })
.await .await
} }
async fn get_node_family_by_head(&self, head: &str) -> Result<Option<Family>, NymdError> { async fn get_node_family_by_head(&self, head: &str) -> Result<Option<Family>, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByHead { self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByHead {
head: head.to_string(), head: head.to_string(),
}) })
@@ -393,11 +393,11 @@ pub trait MixnetQueryClient {
} }
#[async_trait] #[async_trait]
impl<C> MixnetQueryClient for NymdClient<C> impl<C> MixnetQueryClient for NyxdClient<C>
where where
C: CosmWasmClient + Sync + Send, C: CosmWasmClient + Sync + Send,
{ {
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NymdError> async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
where where
for<'a> T: Deserialize<'a>, for<'a> T: Deserialize<'a>,
{ {
@@ -412,10 +412,10 @@ impl<C> MixnetQueryClient for crate::Client<C>
where where
C: CosmWasmClient + Sync + Send, C: CosmWasmClient + Sync + Send,
{ {
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NymdError> async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
where where
for<'a> T: Deserialize<'a>, for<'a> T: Deserialize<'a>,
{ {
self.nymd.query_mixnet_contract(query).await self.nyxd.query_mixnet_contract(query).await
} }
} }
@@ -1,11 +1,11 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net> // Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::coin::Coin; use crate::nyxd::coin::Coin;
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient; pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult; use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::{Fee, NymdClient, SigningCosmWasmClient}; use crate::nyxd::{Fee, NyxdClient, SigningCosmWasmClient};
use async_trait::async_trait; use async_trait::async_trait;
use cosmrs::AccountId; use cosmrs::AccountId;
use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams}; use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
@@ -21,7 +21,7 @@ pub trait MixnetSigningClient {
fee: Option<Fee>, fee: Option<Fee>,
msg: MixnetExecuteMsg, msg: MixnetExecuteMsg,
funds: Vec<Coin>, funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
// state/sys-params-related // state/sys-params-related
@@ -29,7 +29,7 @@ pub trait MixnetSigningClient {
&self, &self,
address: AccountId, address: AccountId,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UpdateRewardingValidatorAddress { MixnetExecuteMsg::UpdateRewardingValidatorAddress {
@@ -44,7 +44,7 @@ pub trait MixnetSigningClient {
&self, &self,
updated_parameters: ContractStateParams, updated_parameters: ContractStateParams,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UpdateContractStateParams { updated_parameters }, MixnetExecuteMsg::UpdateContractStateParams { updated_parameters },
@@ -58,7 +58,7 @@ pub trait MixnetSigningClient {
active_set_size: u32, active_set_size: u32,
force_immediately: bool, force_immediately: bool,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UpdateActiveSetSize { MixnetExecuteMsg::UpdateActiveSetSize {
@@ -75,7 +75,7 @@ pub trait MixnetSigningClient {
updated_params: IntervalRewardingParamsUpdate, updated_params: IntervalRewardingParamsUpdate,
force_immediately: bool, force_immediately: bool,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UpdateRewardingParams { MixnetExecuteMsg::UpdateRewardingParams {
@@ -93,7 +93,7 @@ pub trait MixnetSigningClient {
epoch_duration_secs: u64, epoch_duration_secs: u64,
force_immediately: bool, force_immediately: bool,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UpdateIntervalConfig { MixnetExecuteMsg::UpdateIntervalConfig {
@@ -111,7 +111,7 @@ pub trait MixnetSigningClient {
new_rewarded_set: Vec<LayerAssignment>, new_rewarded_set: Vec<LayerAssignment>,
expected_active_set_size: u32, expected_active_set_size: u32,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::AdvanceCurrentEpoch { MixnetExecuteMsg::AdvanceCurrentEpoch {
@@ -127,7 +127,7 @@ pub trait MixnetSigningClient {
&self, &self,
limit: Option<u32>, limit: Option<u32>,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::ReconcileEpochEvents { limit }, MixnetExecuteMsg::ReconcileEpochEvents { limit },
@@ -142,7 +142,7 @@ pub trait MixnetSigningClient {
owner_signature: String, owner_signature: String,
label: String, label: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::CreateFamily { MixnetExecuteMsg::CreateFamily {
@@ -160,7 +160,7 @@ pub trait MixnetSigningClient {
owner_signature: String, owner_signature: String,
label: String, label: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::CreateFamilyOnBehalf { MixnetExecuteMsg::CreateFamilyOnBehalf {
@@ -178,7 +178,7 @@ pub trait MixnetSigningClient {
signature: String, signature: String,
family_head: String, family_head: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::JoinFamily { MixnetExecuteMsg::JoinFamily {
@@ -196,7 +196,7 @@ pub trait MixnetSigningClient {
signature: String, signature: String,
family_head: String, family_head: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::JoinFamilyOnBehalf { MixnetExecuteMsg::JoinFamilyOnBehalf {
@@ -214,7 +214,7 @@ pub trait MixnetSigningClient {
signature: String, signature: String,
family_head: String, family_head: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::LeaveFamily { MixnetExecuteMsg::LeaveFamily {
@@ -232,7 +232,7 @@ pub trait MixnetSigningClient {
signature: String, signature: String,
family_head: String, family_head: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::LeaveFamilyOnBehalf { MixnetExecuteMsg::LeaveFamilyOnBehalf {
@@ -250,7 +250,7 @@ pub trait MixnetSigningClient {
signature: String, signature: String,
member: String, member: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::KickFamilyMember { signature, member }, MixnetExecuteMsg::KickFamilyMember { signature, member },
@@ -265,7 +265,7 @@ pub trait MixnetSigningClient {
signature: String, signature: String,
member: String, member: String,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::KickFamilyMemberOnBehalf { MixnetExecuteMsg::KickFamilyMemberOnBehalf {
@@ -286,7 +286,7 @@ pub trait MixnetSigningClient {
owner_signature: String, owner_signature: String,
pledge: Coin, pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::BondMixnode { MixnetExecuteMsg::BondMixnode {
@@ -307,7 +307,7 @@ pub trait MixnetSigningClient {
owner_signature: String, owner_signature: String,
pledge: Coin, pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::BondMixnodeOnBehalf { MixnetExecuteMsg::BondMixnodeOnBehalf {
@@ -325,7 +325,7 @@ pub trait MixnetSigningClient {
&self, &self,
additional_pledge: Coin, additional_pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::PledgeMore {}, MixnetExecuteMsg::PledgeMore {},
@@ -339,7 +339,7 @@ pub trait MixnetSigningClient {
owner: AccountId, owner: AccountId,
additional_pledge: Coin, additional_pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::PledgeMoreOnBehalf { MixnetExecuteMsg::PledgeMoreOnBehalf {
@@ -350,7 +350,7 @@ pub trait MixnetSigningClient {
.await .await
} }
async fn unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> { async fn unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(fee, MixnetExecuteMsg::UnbondMixnode {}, vec![]) self.execute_mixnet_contract(fee, MixnetExecuteMsg::UnbondMixnode {}, vec![])
.await .await
} }
@@ -359,7 +359,7 @@ pub trait MixnetSigningClient {
&self, &self,
owner: AccountId, owner: AccountId,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UnbondMixnodeOnBehalf { MixnetExecuteMsg::UnbondMixnodeOnBehalf {
@@ -374,7 +374,7 @@ pub trait MixnetSigningClient {
&self, &self,
new_costs: MixNodeCostParams, new_costs: MixNodeCostParams,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UpdateMixnodeCostParams { new_costs }, MixnetExecuteMsg::UpdateMixnodeCostParams { new_costs },
@@ -388,7 +388,7 @@ pub trait MixnetSigningClient {
owner: AccountId, owner: AccountId,
new_costs: MixNodeCostParams, new_costs: MixNodeCostParams,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UpdateMixnodeCostParamsOnBehalf { MixnetExecuteMsg::UpdateMixnodeCostParamsOnBehalf {
@@ -404,7 +404,7 @@ pub trait MixnetSigningClient {
&self, &self,
new_config: MixNodeConfigUpdate, new_config: MixNodeConfigUpdate,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UpdateMixnodeConfig { new_config }, MixnetExecuteMsg::UpdateMixnodeConfig { new_config },
@@ -418,7 +418,7 @@ pub trait MixnetSigningClient {
owner: AccountId, owner: AccountId,
new_config: MixNodeConfigUpdate, new_config: MixNodeConfigUpdate,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UpdateMixnodeConfigOnBehalf { MixnetExecuteMsg::UpdateMixnodeConfigOnBehalf {
@@ -438,7 +438,7 @@ pub trait MixnetSigningClient {
owner_signature: String, owner_signature: String,
pledge: Coin, pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::BondGateway { MixnetExecuteMsg::BondGateway {
@@ -457,7 +457,7 @@ pub trait MixnetSigningClient {
owner_signature: String, owner_signature: String,
pledge: Coin, pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::BondGatewayOnBehalf { MixnetExecuteMsg::BondGatewayOnBehalf {
@@ -470,7 +470,7 @@ pub trait MixnetSigningClient {
.await .await
} }
async fn unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> { async fn unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(fee, MixnetExecuteMsg::UnbondGateway {}, vec![]) self.execute_mixnet_contract(fee, MixnetExecuteMsg::UnbondGateway {}, vec![])
.await .await
} }
@@ -479,7 +479,7 @@ pub trait MixnetSigningClient {
&self, &self,
owner: AccountId, owner: AccountId,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UnbondGatewayOnBehalf { MixnetExecuteMsg::UnbondGatewayOnBehalf {
@@ -497,7 +497,7 @@ pub trait MixnetSigningClient {
mix_id: MixId, mix_id: MixId,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::DelegateToMixnode { mix_id }, MixnetExecuteMsg::DelegateToMixnode { mix_id },
@@ -512,7 +512,7 @@ pub trait MixnetSigningClient {
mix_id: MixId, mix_id: MixId,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::DelegateToMixnodeOnBehalf { MixnetExecuteMsg::DelegateToMixnodeOnBehalf {
@@ -528,7 +528,7 @@ pub trait MixnetSigningClient {
&self, &self,
mix_id: MixId, mix_id: MixId,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UndelegateFromMixnode { mix_id }, MixnetExecuteMsg::UndelegateFromMixnode { mix_id },
@@ -542,7 +542,7 @@ pub trait MixnetSigningClient {
delegate: AccountId, delegate: AccountId,
mix_id: MixId, mix_id: MixId,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::UndelegateFromMixnodeOnBehalf { MixnetExecuteMsg::UndelegateFromMixnodeOnBehalf {
@@ -561,7 +561,7 @@ pub trait MixnetSigningClient {
mix_id: MixId, mix_id: MixId,
performance: Performance, performance: Performance,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::RewardMixnode { MixnetExecuteMsg::RewardMixnode {
@@ -573,7 +573,7 @@ pub trait MixnetSigningClient {
.await .await
} }
async fn withdraw_operator_reward(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> { async fn withdraw_operator_reward(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(fee, MixnetExecuteMsg::WithdrawOperatorReward {}, vec![]) self.execute_mixnet_contract(fee, MixnetExecuteMsg::WithdrawOperatorReward {}, vec![])
.await .await
} }
@@ -582,7 +582,7 @@ pub trait MixnetSigningClient {
&self, &self,
owner: AccountId, owner: AccountId,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::WithdrawOperatorRewardOnBehalf { MixnetExecuteMsg::WithdrawOperatorRewardOnBehalf {
@@ -597,7 +597,7 @@ pub trait MixnetSigningClient {
&self, &self,
mix_id: MixId, mix_id: MixId,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::WithdrawDelegatorReward { mix_id }, MixnetExecuteMsg::WithdrawDelegatorReward { mix_id },
@@ -611,7 +611,7 @@ pub trait MixnetSigningClient {
owner: AccountId, owner: AccountId,
mix_id: MixId, mix_id: MixId,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract( self.execute_mixnet_contract(
fee, fee,
MixnetExecuteMsg::WithdrawDelegatorRewardOnBehalf { MixnetExecuteMsg::WithdrawDelegatorRewardOnBehalf {
@@ -625,7 +625,7 @@ pub trait MixnetSigningClient {
} }
#[async_trait] #[async_trait]
impl<C> MixnetSigningClient for NymdClient<C> impl<C> MixnetSigningClient for NyxdClient<C>
where where
C: SigningCosmWasmClient + Sync + Send, C: SigningCosmWasmClient + Sync + Send,
{ {
@@ -634,7 +634,7 @@ where
fee: Option<Fee>, fee: Option<Fee>,
msg: MixnetExecuteMsg, msg: MixnetExecuteMsg,
funds: Vec<Coin>, funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let memo = msg.default_memo(); let memo = msg.default_memo();
self.client self.client
@@ -660,7 +660,7 @@ where
fee: Option<Fee>, fee: Option<Fee>,
msg: MixnetExecuteMsg, msg: MixnetExecuteMsg,
funds: Vec<Coin>, funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.nymd.execute_mixnet_contract(fee, msg, funds).await self.nyxd.execute_mixnet_contract(fee, msg, funds).await
} }
} }
@@ -1,8 +1,8 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net> // Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::{CosmWasmClient, NymdClient}; use crate::nyxd::{CosmWasmClient, NyxdClient};
use cw3::{ProposalListResponse, ProposalResponse}; use cw3::{ProposalListResponse, ProposalResponse};
use multisig_contract_common::msg::QueryMsg; use multisig_contract_common::msg::QueryMsg;
@@ -11,17 +11,17 @@ use async_trait::async_trait;
#[async_trait] #[async_trait]
pub trait MultisigQueryClient { pub trait MultisigQueryClient {
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NymdError>; async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NyxdError>;
async fn list_proposals( async fn list_proposals(
&self, &self,
start_after: Option<u64>, start_after: Option<u64>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<ProposalListResponse, NymdError>; ) -> Result<ProposalListResponse, NyxdError>;
} }
#[async_trait] #[async_trait]
impl<C: CosmWasmClient + Sync + Send> MultisigQueryClient for NymdClient<C> { impl<C: CosmWasmClient + Sync + Send> MultisigQueryClient for NyxdClient<C> {
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NymdError> { async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NyxdError> {
let request = QueryMsg::Proposal { proposal_id }; let request = QueryMsg::Proposal { proposal_id };
self.client self.client
.query_contract_smart(self.multisig_contract_address(), &request) .query_contract_smart(self.multisig_contract_address(), &request)
@@ -32,7 +32,7 @@ impl<C: CosmWasmClient + Sync + Send> MultisigQueryClient for NymdClient<C> {
&self, &self,
start_after: Option<u64>, start_after: Option<u64>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<ProposalListResponse, NymdError> { ) -> Result<ProposalListResponse, NyxdError> {
let request = QueryMsg::ListProposals { start_after, limit }; let request = QueryMsg::ListProposals { start_after, limit };
self.client self.client
.query_contract_smart(self.multisig_contract_address(), &request) .query_contract_smart(self.multisig_contract_address(), &request)
@@ -1,10 +1,10 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net> // Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient; pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult; use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::{Fee, NymdClient}; use crate::nyxd::{Fee, NyxdClient};
use coconut_bandwidth_contract_common::msg::ExecuteMsg as CoconutBandwidthExecuteMsg; use coconut_bandwidth_contract_common::msg::ExecuteMsg as CoconutBandwidthExecuteMsg;
use cw3::Vote; use cw3::Vote;
@@ -21,31 +21,31 @@ pub trait MultisigSigningClient {
blinded_serial_number: String, blinded_serial_number: String,
voucher_value: u128, voucher_value: u128,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn vote_proposal( async fn vote_proposal(
&self, &self,
proposal_id: u64, proposal_id: u64,
yes: bool, yes: bool,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn execute_proposal( async fn execute_proposal(
&self, &self,
proposal_id: u64, proposal_id: u64,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
} }
#[async_trait] #[async_trait]
impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NymdClient<C> { impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NyxdClient<C> {
async fn propose_release_funds( async fn propose_release_funds(
&self, &self,
title: String, title: String,
blinded_serial_number: String, blinded_serial_number: String,
voucher_value: u128, voucher_value: u128,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let release_funds_req = CoconutBandwidthExecuteMsg::ReleaseFunds { let release_funds_req = CoconutBandwidthExecuteMsg::ReleaseFunds {
funds: Coin::new( funds: Coin::new(
@@ -81,7 +81,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NymdClien
proposal_id: u64, proposal_id: u64,
vote_yes: bool, vote_yes: bool,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let vote = if vote_yes { Vote::Yes } else { Vote::No }; let vote = if vote_yes { Vote::Yes } else { Vote::No };
let req = ExecuteMsg::Vote { proposal_id, vote }; let req = ExecuteMsg::Vote { proposal_id, vote };
@@ -101,7 +101,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NymdClien
&self, &self,
proposal_id: u64, proposal_id: u64,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = ExecuteMsg::Execute { proposal_id }; let req = ExecuteMsg::Execute { proposal_id };
self.client self.client
@@ -1,10 +1,10 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::coin::Coin; use crate::nyxd::coin::Coin;
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient; pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::NymdClient; use crate::nyxd::NyxdClient;
use async_trait::async_trait; use async_trait::async_trait;
use contracts_common::ContractBuildInformation; use contracts_common::ContractBuildInformation;
use cosmwasm_std::{Coin as CosmWasmCoin, Timestamp}; use cosmwasm_std::{Coin as CosmWasmCoin, Timestamp};
@@ -18,11 +18,11 @@ use vesting_contract_common::{
#[async_trait] #[async_trait]
pub trait VestingQueryClient { pub trait VestingQueryClient {
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NymdError> async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NyxdError>
where where
for<'a> T: Deserialize<'a>; for<'a> T: Deserialize<'a>;
async fn get_vesting_contract_version(&self) -> Result<ContractBuildInformation, NymdError> { async fn get_vesting_contract_version(&self) -> Result<ContractBuildInformation, NyxdError> {
self.query_vesting_contract(VestingQueryMsg::GetContractVersion {}) self.query_vesting_contract(VestingQueryMsg::GetContractVersion {})
.await .await
} }
@@ -31,72 +31,72 @@ pub trait VestingQueryClient {
&self, &self,
address: &str, address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>; ) -> Result<Coin, NyxdError>;
async fn spendable_coins( async fn spendable_coins(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>; ) -> Result<Coin, NyxdError>;
async fn vested_coins( async fn vested_coins(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>; ) -> Result<Coin, NyxdError>;
async fn vesting_coins( async fn vesting_coins(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>; ) -> Result<Coin, NyxdError>;
async fn vesting_start_time( async fn vesting_start_time(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
) -> Result<Timestamp, NymdError>; ) -> Result<Timestamp, NyxdError>;
async fn vesting_end_time(&self, vesting_account_address: &str) async fn vesting_end_time(&self, vesting_account_address: &str)
-> Result<Timestamp, NymdError>; -> Result<Timestamp, NyxdError>;
async fn original_vesting( async fn original_vesting(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
) -> Result<OriginalVestingResponse, NymdError>; ) -> Result<OriginalVestingResponse, NyxdError>;
async fn delegated_free( async fn delegated_free(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>; ) -> Result<Coin, NyxdError>;
async fn delegated_vesting( async fn delegated_vesting(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>; ) -> Result<Coin, NyxdError>;
async fn get_account(&self, address: &str) -> Result<Account, NymdError>; async fn get_account(&self, address: &str) -> Result<Account, NyxdError>;
async fn get_mixnode_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError>; async fn get_mixnode_pledge(&self, address: &str) -> Result<Option<PledgeData>, NyxdError>;
async fn get_gateway_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError>; async fn get_gateway_pledge(&self, address: &str) -> Result<Option<PledgeData>, NyxdError>;
async fn get_current_vesting_period( async fn get_current_vesting_period(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
) -> Result<Period, NymdError>; ) -> Result<Period, NyxdError>;
async fn get_delegation_timestamps( async fn get_delegation_timestamps(
&self, &self,
address: &str, address: &str,
mix_id: MixId, mix_id: MixId,
) -> Result<DelegationTimesResponse, NymdError>; ) -> Result<DelegationTimesResponse, NyxdError>;
async fn get_all_vesting_delegations_paged( async fn get_all_vesting_delegations_paged(
&self, &self,
start_after: Option<(u32, MixId, u64)>, start_after: Option<(u32, MixId, u64)>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<AllDelegationsResponse, NymdError>; ) -> Result<AllDelegationsResponse, NyxdError>;
async fn get_all_vesting_delegations(&self) -> Result<Vec<VestingDelegation>, NymdError> { async fn get_all_vesting_delegations(&self) -> Result<Vec<VestingDelegation>, NyxdError> {
let mut delegations = Vec::new(); let mut delegations = Vec::new();
let mut start_after = None; let mut start_after = None;
loop { loop {
@@ -117,8 +117,8 @@ pub trait VestingQueryClient {
} }
#[async_trait] #[async_trait]
impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> { impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NyxdClient<C> {
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NymdError> async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NyxdError>
where where
for<'a> T: Deserialize<'a>, for<'a> T: Deserialize<'a>,
{ {
@@ -131,7 +131,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> { ) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::LockedCoins { let request = VestingQueryMsg::LockedCoins {
vesting_account_address: vesting_account_address.to_string(), vesting_account_address: vesting_account_address.to_string(),
block_time, block_time,
@@ -146,7 +146,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> { ) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::SpendableCoins { let request = VestingQueryMsg::SpendableCoins {
vesting_account_address: vesting_account_address.to_string(), vesting_account_address: vesting_account_address.to_string(),
block_time, block_time,
@@ -160,7 +160,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> { ) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::GetVestedCoins { let request = VestingQueryMsg::GetVestedCoins {
vesting_account_address: vesting_account_address.to_string(), vesting_account_address: vesting_account_address.to_string(),
block_time, block_time,
@@ -174,7 +174,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> { ) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::GetVestingCoins { let request = VestingQueryMsg::GetVestingCoins {
vesting_account_address: vesting_account_address.to_string(), vesting_account_address: vesting_account_address.to_string(),
block_time, block_time,
@@ -188,7 +188,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
async fn vesting_start_time( async fn vesting_start_time(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
) -> Result<Timestamp, NymdError> { ) -> Result<Timestamp, NyxdError> {
let request = VestingQueryMsg::GetStartTime { let request = VestingQueryMsg::GetStartTime {
vesting_account_address: vesting_account_address.to_string(), vesting_account_address: vesting_account_address.to_string(),
}; };
@@ -200,7 +200,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
async fn vesting_end_time( async fn vesting_end_time(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
) -> Result<Timestamp, NymdError> { ) -> Result<Timestamp, NyxdError> {
let request = VestingQueryMsg::GetEndTime { let request = VestingQueryMsg::GetEndTime {
vesting_account_address: vesting_account_address.to_string(), vesting_account_address: vesting_account_address.to_string(),
}; };
@@ -212,7 +212,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
async fn original_vesting( async fn original_vesting(
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
) -> Result<OriginalVestingResponse, NymdError> { ) -> Result<OriginalVestingResponse, NyxdError> {
let request = VestingQueryMsg::GetOriginalVesting { let request = VestingQueryMsg::GetOriginalVesting {
vesting_account_address: vesting_account_address.to_string(), vesting_account_address: vesting_account_address.to_string(),
}; };
@@ -225,7 +225,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> { ) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::GetDelegatedFree { let request = VestingQueryMsg::GetDelegatedFree {
vesting_account_address: vesting_account_address.to_string(), vesting_account_address: vesting_account_address.to_string(),
block_time, block_time,
@@ -241,7 +241,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self, &self,
vesting_account_address: &str, vesting_account_address: &str,
block_time: Option<Timestamp>, block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> { ) -> Result<Coin, NyxdError> {
let request = VestingQueryMsg::GetDelegatedVesting { let request = VestingQueryMsg::GetDelegatedVesting {
vesting_account_address: vesting_account_address.to_string(), vesting_account_address: vesting_account_address.to_string(),
block_time, block_time,
@@ -252,7 +252,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
.map(Into::into) .map(Into::into)
} }
async fn get_account(&self, address: &str) -> Result<Account, NymdError> { async fn get_account(&self, address: &str) -> Result<Account, NyxdError> {
let request = VestingQueryMsg::GetAccount { let request = VestingQueryMsg::GetAccount {
address: address.to_string(), address: address.to_string(),
}; };
@@ -260,7 +260,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
.query_contract_smart(self.vesting_contract_address(), &request) .query_contract_smart(self.vesting_contract_address(), &request)
.await .await
} }
async fn get_mixnode_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError> { async fn get_mixnode_pledge(&self, address: &str) -> Result<Option<PledgeData>, NyxdError> {
let request = VestingQueryMsg::GetMixnode { let request = VestingQueryMsg::GetMixnode {
address: address.to_string(), address: address.to_string(),
}; };
@@ -268,7 +268,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
.query_contract_smart(self.vesting_contract_address(), &request) .query_contract_smart(self.vesting_contract_address(), &request)
.await .await
} }
async fn get_gateway_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError> { async fn get_gateway_pledge(&self, address: &str) -> Result<Option<PledgeData>, NyxdError> {
let request = VestingQueryMsg::GetGateway { let request = VestingQueryMsg::GetGateway {
address: address.to_string(), address: address.to_string(),
}; };
@@ -277,7 +277,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
.await .await
} }
async fn get_current_vesting_period(&self, address: &str) -> Result<Period, NymdError> { async fn get_current_vesting_period(&self, address: &str) -> Result<Period, NyxdError> {
let request = VestingQueryMsg::GetCurrentVestingPeriod { let request = VestingQueryMsg::GetCurrentVestingPeriod {
address: address.to_string(), address: address.to_string(),
}; };
@@ -290,7 +290,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self, &self,
address: &str, address: &str,
mix_id: MixId, mix_id: MixId,
) -> Result<DelegationTimesResponse, NymdError> { ) -> Result<DelegationTimesResponse, NyxdError> {
let request = VestingQueryMsg::GetDelegationTimes { let request = VestingQueryMsg::GetDelegationTimes {
address: address.to_string(), address: address.to_string(),
mix_id, mix_id,
@@ -304,7 +304,7 @@ impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
&self, &self,
start_after: Option<(u32, MixId, u64)>, start_after: Option<(u32, MixId, u64)>,
limit: Option<u32>, limit: Option<u32>,
) -> Result<AllDelegationsResponse, NymdError> { ) -> Result<AllDelegationsResponse, NyxdError> {
let request = VestingQueryMsg::GetAllDelegations { start_after, limit }; let request = VestingQueryMsg::GetAllDelegations { start_after, limit };
self.client self.client
.query_contract_smart(self.vesting_contract_address(), &request) .query_contract_smart(self.vesting_contract_address(), &request)
@@ -1,10 +1,10 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient; pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult; use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use crate::nymd::{Coin, Fee, NymdClient}; use crate::nyxd::{Coin, Fee, NyxdClient};
use async_trait::async_trait; use async_trait::async_trait;
use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams}; use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
use mixnet_contract_common::{Gateway, MixId, MixNode}; use mixnet_contract_common::{Gateway, MixId, MixNode};
@@ -18,25 +18,25 @@ pub trait VestingSigningClient {
fee: Option<Fee>, fee: Option<Fee>,
msg: VestingExecuteMsg, msg: VestingExecuteMsg,
funds: Vec<Coin>, funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn vesting_update_mixnode_cost_params( async fn vesting_update_mixnode_cost_params(
&self, &self,
new_costs: MixNodeCostParams, new_costs: MixNodeCostParams,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn vesting_update_mixnode_config( async fn vesting_update_mixnode_config(
&self, &self,
new_config: MixNodeConfigUpdate, new_config: MixNodeConfigUpdate,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn update_mixnet_address( async fn update_mixnet_address(
&self, &self,
address: &str, address: &str,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn vesting_bond_gateway( async fn vesting_bond_gateway(
&self, &self,
@@ -44,16 +44,16 @@ pub trait VestingSigningClient {
owner_signature: &str, owner_signature: &str,
pledge: Coin, pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn vesting_unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError>; async fn vesting_unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError>;
async fn vesting_track_unbond_gateway( async fn vesting_track_unbond_gateway(
&self, &self,
owner: &str, owner: &str,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn vesting_bond_mixnode( async fn vesting_bond_mixnode(
&self, &self,
@@ -62,13 +62,13 @@ pub trait VestingSigningClient {
owner_signature: &str, owner_signature: &str,
pledge: Coin, pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn vesting_pledge_more( async fn vesting_pledge_more(
&self, &self,
additional_pledge: Coin, additional_pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract( self.execute_vesting_contract(
fee, fee,
VestingExecuteMsg::PledgeMore { VestingExecuteMsg::PledgeMore {
@@ -79,20 +79,20 @@ pub trait VestingSigningClient {
.await .await
} }
async fn vesting_unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError>; async fn vesting_unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError>;
async fn vesting_track_unbond_mixnode( async fn vesting_track_unbond_mixnode(
&self, &self,
owner: &str, owner: &str,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn withdraw_vested_coins( async fn withdraw_vested_coins(
&self, &self,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn vesting_track_undelegation( async fn vesting_track_undelegation(
&self, &self,
@@ -100,20 +100,20 @@ pub trait VestingSigningClient {
mix_id: MixId, mix_id: MixId,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn vesting_delegate_to_mixnode( async fn vesting_delegate_to_mixnode(
&self, &self,
mix_id: MixId, mix_id: MixId,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn vesting_undelegate_from_mixnode( async fn vesting_undelegate_from_mixnode(
&self, &self,
mix_id: MixId, mix_id: MixId,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
async fn create_periodic_vesting_account( async fn create_periodic_vesting_account(
&self, &self,
@@ -123,17 +123,17 @@ pub trait VestingSigningClient {
amount: Coin, amount: Coin,
cap: Option<PledgeCap>, cap: Option<PledgeCap>,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>; ) -> Result<ExecuteResult, NyxdError>;
} }
#[async_trait] #[async_trait]
impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient<C> { impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NyxdClient<C> {
async fn execute_vesting_contract( async fn execute_vesting_contract(
&self, &self,
fee: Option<Fee>, fee: Option<Fee>,
msg: VestingExecuteMsg, msg: VestingExecuteMsg,
funds: Vec<Coin>, funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let memo = msg.name().to_string(); let memo = msg.name().to_string();
self.client self.client
@@ -152,7 +152,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
&self, &self,
new_costs: MixNodeCostParams, new_costs: MixNodeCostParams,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract( self.execute_vesting_contract(
fee, fee,
VestingExecuteMsg::UpdateMixnodeCostParams { new_costs }, VestingExecuteMsg::UpdateMixnodeCostParams { new_costs },
@@ -165,7 +165,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
&self, &self,
new_config: MixNodeConfigUpdate, new_config: MixNodeConfigUpdate,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::UpdateMixnodeConfig { new_config }; let req = VestingExecuteMsg::UpdateMixnodeConfig { new_config };
self.client self.client
@@ -184,7 +184,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
&self, &self,
address: &str, address: &str,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::UpdateMixnetAddress { let req = VestingExecuteMsg::UpdateMixnetAddress {
address: address.to_string(), address: address.to_string(),
@@ -207,7 +207,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
owner_signature: &str, owner_signature: &str,
pledge: Coin, pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::BondGateway { let req = VestingExecuteMsg::BondGateway {
gateway, gateway,
@@ -226,7 +226,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
.await .await
} }
async fn vesting_unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> { async fn vesting_unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::UnbondGateway {}; let req = VestingExecuteMsg::UnbondGateway {};
self.client self.client
@@ -246,7 +246,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
owner: &str, owner: &str,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::TrackUnbondGateway { let req = VestingExecuteMsg::TrackUnbondGateway {
owner: owner.to_string(), owner: owner.to_string(),
@@ -271,7 +271,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
owner_signature: &str, owner_signature: &str,
pledge: Coin, pledge: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract( self.execute_vesting_contract(
fee, fee,
VestingExecuteMsg::BondMixnode { VestingExecuteMsg::BondMixnode {
@@ -285,7 +285,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
.await .await
} }
async fn vesting_unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> { async fn vesting_unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::UnbondMixnode {}; let req = VestingExecuteMsg::UnbondMixnode {};
self.client self.client
@@ -305,7 +305,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
owner: &str, owner: &str,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::TrackUnbondMixnode { let req = VestingExecuteMsg::TrackUnbondMixnode {
owner: owner.to_string(), owner: owner.to_string(),
@@ -327,7 +327,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
&self, &self,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::WithdrawVestedCoins { let req = VestingExecuteMsg::WithdrawVestedCoins {
amount: amount.into(), amount: amount.into(),
@@ -350,7 +350,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
mix_id: MixId, mix_id: MixId,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract( self.execute_vesting_contract(
fee, fee,
VestingExecuteMsg::TrackUndelegation { VestingExecuteMsg::TrackUndelegation {
@@ -368,7 +368,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
mix_id: MixId, mix_id: MixId,
amount: Coin, amount: Coin,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract( self.execute_vesting_contract(
fee, fee,
VestingExecuteMsg::DelegateToMixnode { VestingExecuteMsg::DelegateToMixnode {
@@ -384,7 +384,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
&self, &self,
mix_id: MixId, mix_id: MixId,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
self.execute_vesting_contract( self.execute_vesting_contract(
fee, fee,
VestingExecuteMsg::UndelegateFromMixnode { mix_id }, VestingExecuteMsg::UndelegateFromMixnode { mix_id },
@@ -401,7 +401,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> VestingSigningClient for NymdClient
amount: Coin, amount: Coin,
cap: Option<PledgeCap>, cap: Option<PledgeCap>,
fee: Option<Fee>, fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> { ) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier))); let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = VestingExecuteMsg::CreateAccount { let req = VestingExecuteMsg::CreateAccount {
owner_address: owner_address.to_string(), owner_address: owner_address.to_string(),
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net> // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError; use crate::nyxd::error::NyxdError;
use config::defaults; use config::defaults;
use cosmrs::bip32::{DerivationPath, XPrv}; use cosmrs::bip32::{DerivationPath, XPrv};
use cosmrs::crypto::secp256k1::{Signature, SigningKey}; use cosmrs::crypto::secp256k1::{Signature, SigningKey};
@@ -62,16 +62,16 @@ impl DirectSecp256k1HdWallet {
} }
/// Restores a wallet from the given BIP39 mnemonic using default options. /// Restores a wallet from the given BIP39 mnemonic using default options.
pub fn from_mnemonic(prefix: &str, mnemonic: bip39::Mnemonic) -> Result<Self, NymdError> { pub fn from_mnemonic(prefix: &str, mnemonic: bip39::Mnemonic) -> Result<Self, NyxdError> {
DirectSecp256k1HdWalletBuilder::new(prefix).build(mnemonic) DirectSecp256k1HdWalletBuilder::new(prefix).build(mnemonic)
} }
pub fn generate(prefix: &str, word_count: usize) -> Result<Self, NymdError> { pub fn generate(prefix: &str, word_count: usize) -> Result<Self, NyxdError> {
let mneomonic = bip39::Mnemonic::generate(word_count)?; let mneomonic = bip39::Mnemonic::generate(word_count)?;
Self::from_mnemonic(prefix, mneomonic) Self::from_mnemonic(prefix, mneomonic)
} }
fn derive_keypair(&self, hd_path: &DerivationPath) -> Result<Secp256k1Keypair, NymdError> { fn derive_keypair(&self, hd_path: &DerivationPath) -> Result<Secp256k1Keypair, NyxdError> {
let extended_private_key = XPrv::derive_from_path(self.seed, hd_path)?; let extended_private_key = XPrv::derive_from_path(self.seed, hd_path)?;
let private_key: SigningKey = extended_private_key.into(); let private_key: SigningKey = extended_private_key.into();
@@ -80,7 +80,7 @@ impl DirectSecp256k1HdWallet {
Ok((private_key, public_key)) Ok((private_key, public_key))
} }
pub fn try_derive_accounts(&self) -> Result<Vec<AccountData>, NymdError> { pub fn try_derive_accounts(&self) -> Result<Vec<AccountData>, NyxdError> {
let mut accounts = Vec::with_capacity(self.accounts.len()); let mut accounts = Vec::with_capacity(self.accounts.len());
for derivation_info in &self.accounts { for derivation_info in &self.accounts {
let keypair = self.derive_keypair(&derivation_info.hd_path)?; let keypair = self.derive_keypair(&derivation_info.hd_path)?;
@@ -89,7 +89,7 @@ impl DirectSecp256k1HdWallet {
let address = keypair let address = keypair
.1 .1
.account_id(&derivation_info.prefix) .account_id(&derivation_info.prefix)
.map_err(|_| NymdError::AccountDerivationError)?; .map_err(|_| NyxdError::AccountDerivationError)?;
accounts.push(AccountData { accounts.push(AccountData {
address, address,
@@ -109,36 +109,36 @@ impl DirectSecp256k1HdWallet {
&self, &self,
signer: &AccountData, signer: &AccountData,
message: &[u8], message: &[u8],
) -> Result<Signature, NymdError> { ) -> Result<Signature, NyxdError> {
signer signer
.private_key .private_key
.sign(message) .sign(message)
.map_err(|_| NymdError::SigningFailure) .map_err(|_| NyxdError::SigningFailure)
} }
pub fn sign_direct_with_account( pub fn sign_direct_with_account(
&self, &self,
signer: &AccountData, signer: &AccountData,
sign_doc: SignDoc, sign_doc: SignDoc,
) -> Result<tx::Raw, NymdError> { ) -> Result<tx::Raw, NyxdError> {
// ideally I'd prefer to have the entire error put into the NymdError::SigningFailure // ideally I'd prefer to have the entire error put into the NyxdError::SigningFailure
// but I'm super hesitant to trying to downcast the eyre::Report to cosmrs::error::Error // but I'm super hesitant to trying to downcast the eyre::Report to cosmrs::error::Error
sign_doc sign_doc
.sign(&signer.private_key) .sign(&signer.private_key)
.map_err(|_| NymdError::SigningFailure) .map_err(|_| NyxdError::SigningFailure)
} }
pub fn sign_direct( pub fn sign_direct(
&self, &self,
signer_address: &AccountId, signer_address: &AccountId,
sign_doc: SignDoc, sign_doc: SignDoc,
) -> Result<tx::Raw, NymdError> { ) -> Result<tx::Raw, NyxdError> {
// I hate deriving accounts at every sign here so much : ( // I hate deriving accounts at every sign here so much : (
let accounts = self.try_derive_accounts()?; let accounts = self.try_derive_accounts()?;
let account = accounts let account = accounts
.iter() .iter()
.find(|account| &account.address == signer_address) .find(|account| &account.address == signer_address)
.ok_or_else(|| NymdError::SigningAccountNotFound(signer_address.clone()))?; .ok_or_else(|| NyxdError::SigningAccountNotFound(signer_address.clone()))?;
self.sign_direct_with_account(account, sign_doc) self.sign_direct_with_account(account, sign_doc)
} }
@@ -185,7 +185,7 @@ impl DirectSecp256k1HdWalletBuilder {
self self
} }
pub fn build(self, mnemonic: bip39::Mnemonic) -> Result<DirectSecp256k1HdWallet, NymdError> { pub fn build(self, mnemonic: bip39::Mnemonic) -> Result<DirectSecp256k1HdWallet, NyxdError> {
let seed = mnemonic.to_seed(&self.bip39_password); let seed = mnemonic.to_seed(&self.bip39_password);
let prefix = self.prefix; let prefix = self.prefix;
let accounts = self let accounts = self
+1 -1
View File
@@ -27,7 +27,7 @@ tap = "1"
cosmrs = { git = "https://github.com/neacsu/cosmos-rust", branch = "neacsu/feegrant_support" } cosmrs = { git = "https://github.com/neacsu/cosmos-rust", branch = "neacsu/feegrant_support" }
cosmwasm-std = { version = "1.0.0" } cosmwasm-std = { version = "1.0.0" }
validator-client = { path = "../client-libs/validator-client", features = ["nymd-client"] } validator-client = { path = "../client-libs/validator-client", features = ["nyxd-client"] }
network-defaults = { path = "../network-defaults" } network-defaults = { path = "../network-defaults" }
mixnet-contract-common = { path = "../cosmwasm-smart-contracts/mixnet-contract" } mixnet-contract-common = { path = "../cosmwasm-smart-contracts/mixnet-contract" }
vesting-contract-common = { path = "../cosmwasm-smart-contracts/vesting-contract" } vesting-contract-common = { path = "../cosmwasm-smart-contracts/vesting-contract" }
+3 -3
View File
@@ -11,13 +11,13 @@ pub enum ContextError {
#[error("failed to parse mnemonic - {0}")] #[error("failed to parse mnemonic - {0}")]
Bip39Error(#[from] bip39::Error), Bip39Error(#[from] bip39::Error),
// there are lots of error that can occur in the nymd client, so just pass through their display details // there are lots of error that can occur in the nyxd client, so just pass through their display details
// TODO: improve this to return known errors // TODO: improve this to return known errors
#[error("failed to create client - {0}")] #[error("failed to create client - {0}")]
NymdError(String), NyxdError(String),
#[error(transparent)] #[error(transparent)]
NymdErrorPassthrough(#[from] validator_client::nymd::error::NymdError), NyxdErrorPassthrough(#[from] validator_client::nyxd::error::NyxdError),
#[error(transparent)] #[error(transparent)]
ValidatorClientError(#[from] validator_client::ValidatorClientError), ValidatorClientError(#[from] validator_client::ValidatorClientError),
+24 -24
View File
@@ -3,26 +3,26 @@
use network_defaults::{ use network_defaults::{
setup_env, setup_env,
var_names::{API_VALIDATOR, MIXNET_CONTRACT_ADDRESS, NYMD_VALIDATOR, VESTING_CONTRACT_ADDRESS}, var_names::{MIXNET_CONTRACT_ADDRESS, NYM_API, NYXD, VESTING_CONTRACT_ADDRESS},
NymNetworkDetails, NymNetworkDetails,
}; };
use tap::prelude::*; use tap::prelude::*;
pub use validator_client::nym_api::Client as NymApiClient; pub use validator_client::nym_api::Client as NymApiClient;
use validator_client::nymd::{self, AccountId, NymdClient, QueryNymdClient, SigningNymdClient}; use validator_client::nyxd::{self, AccountId, NyxdClient, QueryNyxdClient, SigningNyxdClient};
use crate::context::errors::ContextError; use crate::context::errors::ContextError;
pub mod errors; pub mod errors;
pub type SigningClient = validator_client::nymd::NymdClient<SigningNymdClient>; pub type SigningClient = validator_client::nyxd::NyxdClient<SigningNyxdClient>;
pub type QueryClient = validator_client::nymd::NymdClient<QueryNymdClient>; pub type QueryClient = validator_client::nyxd::NyxdClient<QueryNyxdClient>;
pub type SigningClientWithNymd = validator_client::Client<SigningNymdClient>; pub type SigningClientWithNyxd = validator_client::Client<SigningNyxdClient>;
pub type QueryClientWithNymd = validator_client::Client<QueryNymdClient>; pub type QueryClientWithNyxd = validator_client::Client<QueryNyxdClient>;
#[derive(Debug)] #[derive(Debug)]
pub struct ClientArgs { pub struct ClientArgs {
pub config_env_file: Option<std::path::PathBuf>, pub config_env_file: Option<std::path::PathBuf>,
pub nymd_url: Option<String>, pub nyxd_url: Option<String>,
pub nym_api_url: Option<String>, pub nym_api_url: Option<String>,
pub mnemonic: Option<bip39::Mnemonic>, pub mnemonic: Option<bip39::Mnemonic>,
pub mixnet_contract_address: Option<AccountId>, pub mixnet_contract_address: Option<AccountId>,
@@ -35,11 +35,11 @@ pub fn get_network_details(args: &ClientArgs) -> Result<NymNetworkDetails, Conte
setup_env(args.config_env_file.as_ref()); setup_env(args.config_env_file.as_ref());
// override the env vars with user supplied arguments, if set // override the env vars with user supplied arguments, if set
if let Some(nymd_url) = args.nymd_url.as_ref() { if let Some(nyxd_url) = args.nyxd_url.as_ref() {
std::env::set_var(NYMD_VALIDATOR, nymd_url); std::env::set_var(NYXD, nyxd_url);
} }
if let Some(nym_api_url) = args.nym_api_url.as_ref() { if let Some(nym_api_url) = args.nym_api_url.as_ref() {
std::env::set_var(API_VALIDATOR, nym_api_url); std::env::set_var(NYM_API, nym_api_url);
} }
if let Some(mixnet_contract_address) = args.mixnet_contract_address.as_ref() { if let Some(mixnet_contract_address) = args.mixnet_contract_address.as_ref() {
std::env::set_var(MIXNET_CONTRACT_ADDRESS, mixnet_contract_address.to_string()); std::env::set_var(MIXNET_CONTRACT_ADDRESS, mixnet_contract_address.to_string());
@@ -58,7 +58,7 @@ pub fn create_signing_client(
args: ClientArgs, args: ClientArgs,
network_details: &NymNetworkDetails, network_details: &NymNetworkDetails,
) -> Result<SigningClient, ContextError> { ) -> Result<SigningClient, ContextError> {
let client_config = nymd::Config::try_from_nym_network_details(network_details) let client_config = nyxd::Config::try_from_nym_network_details(network_details)
.tap_err(|err| log::error!("Failed to get client config - {err}"))?; .tap_err(|err| log::error!("Failed to get client config - {err}"))?;
// get mnemonic // get mnemonic
@@ -71,42 +71,42 @@ pub fn create_signing_client(
}, },
}; };
let nymd_url = network_details let nyxd_url = network_details
.endpoints .endpoints
.first() .first()
.expect("network details are not defined") .expect("network details are not defined")
.nymd_url .nyxd_url
.as_str(); .as_str();
match NymdClient::connect_with_mnemonic(client_config, nymd_url, mnemonic, None) { match NyxdClient::connect_with_mnemonic(client_config, nyxd_url, mnemonic, None) {
Ok(client) => Ok(client), Ok(client) => Ok(client),
Err(e) => Err(ContextError::NymdError(format!("{:?}", e))), Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
} }
} }
pub fn create_query_client( pub fn create_query_client(
network_details: &NymNetworkDetails, network_details: &NymNetworkDetails,
) -> Result<QueryClient, ContextError> { ) -> Result<QueryClient, ContextError> {
let client_config = nymd::Config::try_from_nym_network_details(network_details) let client_config = nyxd::Config::try_from_nym_network_details(network_details)
.tap_err(|err| log::error!("Failed to get client config - {err}"))?; .tap_err(|err| log::error!("Failed to get client config - {err}"))?;
let nymd_url = network_details let nyxd_url = network_details
.endpoints .endpoints
.first() .first()
.expect("network details are not defined") .expect("network details are not defined")
.nymd_url .nyxd_url
.as_str(); .as_str();
match NymdClient::connect(client_config, nymd_url) { match NyxdClient::connect(client_config, nyxd_url) {
Ok(client) => Ok(client), Ok(client) => Ok(client),
Err(e) => Err(ContextError::NymdError(format!("{:?}", e))), Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
} }
} }
pub fn create_signing_client_with_nym_api( pub fn create_signing_client_with_nym_api(
args: ClientArgs, args: ClientArgs,
network_details: &NymNetworkDetails, network_details: &NymNetworkDetails,
) -> Result<SigningClientWithNymd, ContextError> { ) -> Result<SigningClientWithNyxd, ContextError> {
let client_config = validator_client::Config::try_from_nym_network_details(network_details) let client_config = validator_client::Config::try_from_nym_network_details(network_details)
.tap_err(|err| log::error!("Failed to get client config - {err}"))?; .tap_err(|err| log::error!("Failed to get client config - {err}"))?;
@@ -122,18 +122,18 @@ pub fn create_signing_client_with_nym_api(
match validator_client::client::Client::new_signing(client_config, mnemonic) { match validator_client::client::Client::new_signing(client_config, mnemonic) {
Ok(client) => Ok(client), Ok(client) => Ok(client),
Err(e) => Err(ContextError::NymdError(format!("{:?}", e))), Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
} }
} }
pub fn create_query_client_with_nym_api( pub fn create_query_client_with_nym_api(
network_details: &NymNetworkDetails, network_details: &NymNetworkDetails,
) -> Result<QueryClientWithNymd, ContextError> { ) -> Result<QueryClientWithNyxd, ContextError> {
let client_config = validator_client::Config::try_from_nym_network_details(network_details) let client_config = validator_client::Config::try_from_nym_network_details(network_details)
.tap_err(|err| log::error!("Failed to get client config - {err}"))?; .tap_err(|err| log::error!("Failed to get client config - {err}"))?;
match validator_client::client::Client::new_query(client_config) { match validator_client::client::Client::new_query(client_config) {
Ok(client) => Ok(client), Ok(client) => Ok(client),
Err(e) => Err(ContextError::NymdError(format!("{:?}", e))), Err(e) => Err(ContextError::NyxdError(format!("{:?}", e))),
} }
} }
+1 -1
View File
@@ -6,7 +6,7 @@ use std::fmt::Display;
use cosmwasm_std::{Coin as CosmWasmCoin, Decimal}; use cosmwasm_std::{Coin as CosmWasmCoin, Decimal};
use log::error; use log::error;
use validator_client::nymd::Coin; use validator_client::nyxd::Coin;
pub fn pretty_coin(coin: &Coin) -> String { pub fn pretty_coin(coin: &Coin) -> String {
let amount = Decimal::from_ratio(coin.amount, 1_000_000u128); let amount = Decimal::from_ratio(coin.amount, 1_000_000u128);
@@ -4,7 +4,7 @@
use clap::Parser; use clap::Parser;
use log::{error, info}; use log::{error, info};
use validator_client::nymd::AccountId; use validator_client::nyxd::AccountId;
use crate::context::QueryClient; use crate::context::QueryClient;
use crate::utils::{pretty_coin, show_error}; use crate::utils::{pretty_coin, show_error};
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use clap::Parser; use clap::Parser;
use validator_client::nymd::wallet::DirectSecp256k1HdWallet; use validator_client::nyxd::wallet::DirectSecp256k1HdWallet;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -4,8 +4,8 @@
use clap::Parser; use clap::Parser;
use log::{error, info}; use log::{error, info};
use validator_client::nymd::wallet::DirectSecp256k1HdWallet; use validator_client::nyxd::wallet::DirectSecp256k1HdWallet;
use validator_client::nymd::AccountId; use validator_client::nyxd::AccountId;
use crate::context::QueryClient; use crate::context::QueryClient;
use crate::utils::show_error; use crate::utils::show_error;
@@ -5,7 +5,7 @@ use clap::Parser;
use log::info; use log::info;
use serde_json::json; use serde_json::json;
use validator_client::nymd::{AccountId, Coin}; use validator_client::nyxd::{AccountId, Coin};
use crate::context::SigningClient; use crate::context::SigningClient;
@@ -6,7 +6,7 @@ use clap::Parser;
use cosmrs::AccountId; use cosmrs::AccountId;
use log::{error, info}; use log::{error, info};
use serde_json::{json, Value}; use serde_json::{json, Value};
use validator_client::nymd::Coin; use validator_client::nyxd::Coin;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -6,8 +6,8 @@ use clap::Parser;
use cosmrs::{AccountId, Coin as CosmosCoin}; use cosmrs::{AccountId, Coin as CosmosCoin};
use log::info; use log::info;
use network_defaults::NymNetworkDetails; use network_defaults::NymNetworkDetails;
use validator_client::nymd::cosmwasm_client::types::{ContractCodeId, InstantiateOptions}; use validator_client::nyxd::cosmwasm_client::types::{ContractCodeId, InstantiateOptions};
use validator_client::nymd::Coin; use validator_client::nyxd::Coin;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -6,7 +6,7 @@ use crate::utils::show_error_passthrough;
use clap::Parser; use clap::Parser;
use cosmrs::AccountId; use cosmrs::AccountId;
use log::info; use log::info;
use validator_client::nymd::cosmwasm_client::types::{ContractCodeId, EmptyMsg}; use validator_client::nyxd::cosmwasm_client::types::{ContractCodeId, EmptyMsg};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -5,7 +5,7 @@ use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use mixnet_contract_common::{Coin, MixId}; use mixnet_contract_common::{Coin, MixId};
use validator_client::nymd::traits::{MixnetQueryClient, MixnetSigningClient}; use validator_client::nyxd::traits::{MixnetQueryClient, MixnetSigningClient};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -4,7 +4,7 @@
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use crate::context::SigningClientWithNymd; use crate::context::SigningClientWithNyxd;
use crate::utils::{pretty_cosmwasm_coin, show_error_passthrough}; use crate::utils::{pretty_cosmwasm_coin, show_error_passthrough};
use comfy_table::Table; use comfy_table::Table;
@@ -14,19 +14,19 @@ use mixnet_contract_common::{Delegation, PendingEpochEvent, PendingEpochEventKin
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args {} pub struct Args {}
pub async fn execute(_args: Args, client: SigningClientWithNymd) { pub async fn execute(_args: Args, client: SigningClientWithNyxd) {
info!( info!(
"Getting delegations for account {}...", "Getting delegations for account {}...",
client.nymd.address() client.nyxd.address()
); );
let delegations = client let delegations = client
.get_all_delegator_delegations(client.nymd.address()) .get_all_delegator_delegations(client.nyxd.address())
.await .await
.map_err(show_error_passthrough); .map_err(show_error_passthrough);
let mixnet_contract_events = client let mixnet_contract_events = client
.get_all_nymd_pending_epoch_events() .get_all_nyxd_pending_epoch_events()
.await .await
.map_err(show_error_passthrough); .map_err(show_error_passthrough);
@@ -48,14 +48,14 @@ pub async fn execute(_args: Args, client: SigningClientWithNymd) {
} }
} }
async fn to_iso_timestamp(block_height: u32, client: &SigningClientWithNymd) -> String { async fn to_iso_timestamp(block_height: u32, client: &SigningClientWithNyxd) -> String {
match client.nymd.get_block_timestamp(Some(block_height)).await { match client.nyxd.get_block_timestamp(Some(block_height)).await {
Ok(res) => res.to_rfc3339(), Ok(res) => res.to_rfc3339(),
Err(_e) => "-".to_string(), Err(_e) => "-".to_string(),
} }
} }
async fn print_delegations(delegations: Vec<Delegation>, client: &SigningClientWithNymd) { async fn print_delegations(delegations: Vec<Delegation>, client: &SigningClientWithNyxd) {
let mut table = Table::new(); let mut table = Table::new();
table.set_header(vec!["Timestamp", "Mix Id", "Delegation", "Proxy"]); table.set_header(vec!["Timestamp", "Mix Id", "Delegation", "Proxy"]);
@@ -75,7 +75,7 @@ async fn print_delegations(delegations: Vec<Delegation>, client: &SigningClientW
println!("{table}"); println!("{table}");
} }
async fn print_delegation_events(events: Vec<PendingEpochEvent>, client: &SigningClientWithNymd) { async fn print_delegation_events(events: Vec<PendingEpochEvent>, client: &SigningClientWithNyxd) {
let mut table = Table::new(); let mut table = Table::new();
table.set_header(vec![ table.set_header(vec![
@@ -94,7 +94,7 @@ async fn print_delegation_events(events: Vec<PendingEpochEvent>, client: &Signin
amount, amount,
proxy, proxy,
} => { } => {
if owner.as_str() == client.nymd.address().as_ref() { if owner.as_str() == client.nyxd.address().as_ref() {
table.add_row(vec![ table.add_row(vec![
"not-sure-if-applicable".into(), "not-sure-if-applicable".into(),
mix_id.to_string(), mix_id.to_string(),
@@ -109,7 +109,7 @@ async fn print_delegation_events(events: Vec<PendingEpochEvent>, client: &Signin
mix_id, mix_id,
proxy, proxy,
} => { } => {
if owner.as_str() == client.nymd.address().as_ref() { if owner.as_str() == client.nyxd.address().as_ref() {
table.add_row(vec![ table.add_row(vec![
"not-sure-if-applicable".into(), "not-sure-if-applicable".into(),
mix_id.to_string(), mix_id.to_string(),
@@ -5,7 +5,7 @@ use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use mixnet_contract_common::MixId; use mixnet_contract_common::MixId;
use validator_client::nymd::traits::{MixnetQueryClient, MixnetSigningClient}; use validator_client::nyxd::traits::{MixnetQueryClient, MixnetSigningClient};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -5,7 +5,7 @@ use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use mixnet_contract_common::MixId; use mixnet_contract_common::MixId;
use validator_client::nymd::traits::{MixnetQueryClient, MixnetSigningClient}; use validator_client::nyxd::traits::{MixnetQueryClient, MixnetSigningClient};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -5,7 +5,7 @@ use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use mixnet_contract_common::MixId; use mixnet_contract_common::MixId;
use validator_client::nymd::traits::{MixnetQueryClient, MixnetSigningClient}; use validator_client::nyxd::traits::{MixnetQueryClient, MixnetSigningClient};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -5,8 +5,8 @@ use clap::Parser;
use log::info; use log::info;
use mixnet_contract_common::{Coin, MixId}; use mixnet_contract_common::{Coin, MixId};
use validator_client::nymd::traits::MixnetQueryClient; use validator_client::nyxd::traits::MixnetQueryClient;
use validator_client::nymd::VestingSigningClient; use validator_client::nyxd::VestingSigningClient;
use crate::context::SigningClient; use crate::context::SigningClient;
@@ -4,8 +4,8 @@
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use mixnet_contract_common::MixId; use mixnet_contract_common::MixId;
use validator_client::nymd::traits::MixnetQueryClient; use validator_client::nyxd::traits::MixnetQueryClient;
use validator_client::nymd::VestingSigningClient; use validator_client::nyxd::VestingSigningClient;
use crate::context::SigningClient; use crate::context::SigningClient;
@@ -6,7 +6,7 @@ use clap::Parser;
use log::{info, warn}; use log::{info, warn};
use mixnet_contract_common::Coin; use mixnet_contract_common::Coin;
use network_defaults::{DEFAULT_CLIENT_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT}; use network_defaults::{DEFAULT_CLIENT_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT};
use validator_client::nymd::traits::MixnetSigningClient; use validator_client::nyxd::traits::MixnetSigningClient;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -4,7 +4,7 @@
use crate::context::SigningClient; use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use validator_client::nymd::traits::MixnetSigningClient; use validator_client::nyxd::traits::MixnetSigningClient;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args {} pub struct Args {}
@@ -6,7 +6,7 @@ use clap::Parser;
use log::{info, warn}; use log::{info, warn};
use mixnet_contract_common::{Coin, Gateway}; use mixnet_contract_common::{Coin, Gateway};
use network_defaults::{DEFAULT_CLIENT_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT}; use network_defaults::{DEFAULT_CLIENT_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT};
use validator_client::nymd::VestingSigningClient; use validator_client::nyxd::VestingSigningClient;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -4,7 +4,7 @@
use crate::context::SigningClient; use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use validator_client::nymd::traits::MixnetSigningClient; use validator_client::nyxd::traits::MixnetSigningClient;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args {} pub struct Args {}
@@ -9,8 +9,8 @@ use mixnet_contract_common::{Coin, MixNodeCostParams, Percent};
use network_defaults::{ use network_defaults::{
DEFAULT_HTTP_API_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT, DEFAULT_VERLOC_LISTENING_PORT, DEFAULT_HTTP_API_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT, DEFAULT_VERLOC_LISTENING_PORT,
}; };
use validator_client::nymd::traits::MixnetSigningClient; use validator_client::nyxd::traits::MixnetSigningClient;
use validator_client::nymd::CosmWasmCoin; use validator_client::nyxd::CosmWasmCoin;
use crate::context::SigningClient; use crate::context::SigningClient;
@@ -4,7 +4,7 @@
use crate::context::SigningClient; use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use validator_client::nymd::traits::MixnetSigningClient; use validator_client::nyxd::traits::MixnetSigningClient;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args {} pub struct Args {}
@@ -4,7 +4,7 @@
use crate::context::SigningClient; use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use validator_client::nymd::traits::MixnetSigningClient; use validator_client::nyxd::traits::MixnetSigningClient;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -5,7 +5,7 @@ use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use mixnet_contract_common::MixNodeConfigUpdate; use mixnet_contract_common::MixNodeConfigUpdate;
use validator_client::nymd::traits::{MixnetQueryClient, MixnetSigningClient}; use validator_client::nyxd::traits::{MixnetQueryClient, MixnetSigningClient};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -5,8 +5,8 @@ use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use mixnet_contract_common::MixNodeConfigUpdate; use mixnet_contract_common::MixNodeConfigUpdate;
use validator_client::nymd::traits::MixnetQueryClient; use validator_client::nyxd::traits::MixnetQueryClient;
use validator_client::nymd::VestingSigningClient; use validator_client::nyxd::VestingSigningClient;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -3,7 +3,7 @@
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use validator_client::nymd::traits::MixnetSigningClient; use validator_client::nyxd::traits::MixnetSigningClient;
use crate::context::SigningClient; use crate::context::SigningClient;
@@ -10,7 +10,7 @@ use mixnet_contract_common::{MixNode, Percent};
use network_defaults::{ use network_defaults::{
DEFAULT_HTTP_API_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT, DEFAULT_VERLOC_LISTENING_PORT, DEFAULT_HTTP_API_LISTENING_PORT, DEFAULT_MIX_LISTENING_PORT, DEFAULT_VERLOC_LISTENING_PORT,
}; };
use validator_client::nymd::{CosmWasmCoin, VestingSigningClient}; use validator_client::nyxd::{CosmWasmCoin, VestingSigningClient};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -4,7 +4,7 @@
use crate::context::SigningClient; use crate::context::SigningClient;
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use validator_client::nymd::VestingSigningClient; use validator_client::nyxd::VestingSigningClient;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct Args { pub struct Args {
@@ -4,7 +4,7 @@
use clap::Parser; use clap::Parser;
use comfy_table::Table; use comfy_table::Table;
use crate::context::QueryClientWithNymd; use crate::context::QueryClientWithNyxd;
use crate::utils::{pretty_cosmwasm_coin, show_error}; use crate::utils::{pretty_cosmwasm_coin, show_error};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
@@ -14,7 +14,7 @@ pub struct Args {
pub identity_key: Option<String>, pub identity_key: Option<String>,
} }
pub async fn query(args: Args, client: &QueryClientWithNymd) { pub async fn query(args: Args, client: &QueryClientWithNyxd) {
match client.nym_api.get_gateways().await { match client.nym_api.get_gateways().await {
Ok(res) => match args.identity_key { Ok(res) => match args.identity_key {
Some(identity_key) => { Some(identity_key) => {
@@ -4,7 +4,7 @@
use clap::Parser; use clap::Parser;
use comfy_table::Table; use comfy_table::Table;
use crate::context::QueryClientWithNymd; use crate::context::QueryClientWithNyxd;
use crate::utils::{pretty_decimal_with_denom, show_error}; use crate::utils::{pretty_decimal_with_denom, show_error};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
@@ -14,7 +14,7 @@ pub struct Args {
pub identity_key: Option<String>, pub identity_key: Option<String>,
} }
pub async fn query(args: Args, client: &QueryClientWithNymd) { pub async fn query(args: Args, client: &QueryClientWithNyxd) {
match client.nym_api.get_mixnodes().await { match client.nym_api.get_mixnodes().await {
Ok(res) => match args.identity_key { Ok(res) => match args.identity_key {
Some(identity_key) => { Some(identity_key) => {
@@ -7,7 +7,7 @@ use cosmrs::crypto::PublicKey;
use log::error; use log::error;
use serde::Serialize; use serde::Serialize;
use serde_json::json; use serde_json::json;
use validator_client::nymd::wallet::DirectSecp256k1HdWallet; use validator_client::nyxd::wallet::DirectSecp256k1HdWallet;
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
pub struct SignatureOutputJson { pub struct SignatureOutputJson {
@@ -8,7 +8,7 @@ use cosmrs::crypto::PublicKey;
use log::{error, info}; use log::{error, info};
use serde_json::json; use serde_json::json;
use validator_client::nymd::AccountId; use validator_client::nyxd::AccountId;
use crate::context::QueryClient; use crate::context::QueryClient;
use crate::validator::signature::helpers::secp256k1_verify_with_public_key; use crate::validator::signature::helpers::secp256k1_verify_with_public_key;
@@ -5,7 +5,7 @@ use clap::Parser;
use cosmrs::AccountId; use cosmrs::AccountId;
use log::{error, info}; use log::{error, info};
use validator_client::nymd::{Coin, VestingQueryClient}; use validator_client::nyxd::{Coin, VestingQueryClient};
use crate::context::QueryClient; use crate::context::QueryClient;
use crate::utils::show_error; use crate::utils::show_error;
@@ -8,9 +8,9 @@ use log::info;
use mixnet_contract_common::Coin; use mixnet_contract_common::Coin;
use network_defaults::NymNetworkDetails; use network_defaults::NymNetworkDetails;
use validator_client::nymd::AccountId; use validator_client::nyxd::AccountId;
use validator_client::nymd::VestingSigningClient; use validator_client::nyxd::VestingSigningClient;
use validator_client::nymd::{CosmosCoin, Denom}; use validator_client::nyxd::{CosmosCoin, Denom};
use vesting_contract_common::messages::VestingSpecification; use vesting_contract_common::messages::VestingSpecification;
use vesting_contract_common::PledgeCap; use vesting_contract_common::PledgeCap;
@@ -6,7 +6,7 @@ use cosmrs::AccountId;
use cosmwasm_std::Coin as CosmWasmCoin; use cosmwasm_std::Coin as CosmWasmCoin;
use log::{error, info}; use log::{error, info};
use validator_client::nymd::{Coin, VestingQueryClient}; use validator_client::nyxd::{Coin, VestingQueryClient};
use crate::context::QueryClient; use crate::context::QueryClient;
use crate::utils::show_error; use crate::utils::show_error;
@@ -4,7 +4,7 @@
use clap::Parser; use clap::Parser;
use log::info; use log::info;
use validator_client::nymd::{Coin, VestingQueryClient, VestingSigningClient}; use validator_client::nyxd::{Coin, VestingQueryClient, VestingSigningClient};
use crate::context::SigningClient; use crate::context::SigningClient;
use crate::utils::show_error; use crate::utils::show_error;
+1 -1
View File
@@ -37,7 +37,7 @@ pub async fn obtain_aggregate_verification_key(
async fn obtain_partial_credential( async fn obtain_partial_credential(
params: &Parameters, params: &Parameters,
attributes: &BandwidthVoucher, attributes: &BandwidthVoucher,
client: &validator_client::client::ApiClient, client: &validator_client::client::NymApiClient,
validator_vk: &VerificationKey, validator_vk: &VerificationKey,
) -> Result<Signature, Error> { ) -> Result<Signature, Error> {
let public_attributes = attributes.get_public_attributes(); let public_attributes = attributes.get_public_attributes();
+2 -2
View File
@@ -53,13 +53,13 @@ pub fn execute(attr: TokenStream, item: TokenStream) -> TokenStream {
); );
let execute_output = quote! { let execute_output = quote! {
-> Result<ExecuteResult, NymdError> -> Result<ExecuteResult, NyxdError>
}; };
let o_ts = proc_macro::TokenStream::from(execute_output); let o_ts = proc_macro::TokenStream::from(execute_output);
execute_f.sig.output = parse_macro_input!(o_ts as ReturnType); execute_f.sig.output = parse_macro_input!(o_ts as ReturnType);
let simulate_output = quote! { let simulate_output = quote! {
-> Result<SimulateResponse, NymdError> -> Result<SimulateResponse, NyxdError>
}; };
let o_ts = proc_macro::TokenStream::from(simulate_output); let o_ts = proc_macro::TokenStream::from(simulate_output);
simulate_f.sig.output = parse_macro_input!(o_ts as ReturnType); simulate_f.sig.output = parse_macro_input!(o_ts as ReturnType);
+2 -2
View File
@@ -176,7 +176,7 @@ pub struct VerlocMeasurer {
// It only does bunch of REST queries. If we update it at some point to a more sophisticated (maybe signing) client, // It only does bunch of REST queries. If we update it at some point to a more sophisticated (maybe signing) client,
// then it definitely cannot be constructed here and probably will need to be passed from outside, // then it definitely cannot be constructed here and probably will need to be passed from outside,
// as mixnodes/gateways would already be using an instance of said client. // as mixnodes/gateways would already be using an instance of said client.
validator_client: validator_client::ApiClient, validator_client: validator_client::NymApiClient,
results: AtomicVerlocResult, results: AtomicVerlocResult,
} }
@@ -204,7 +204,7 @@ impl VerlocMeasurer {
)), )),
shutdown_listener, shutdown_listener,
currently_used_api: 0, currently_used_api: 0,
validator_client: validator_client::ApiClient::new(config.nym_api_urls[0].clone()), validator_client: validator_client::NymApiClient::new(config.nym_api_urls[0].clone()),
config, config,
results: AtomicVerlocResult::new(), results: AtomicVerlocResult::new(),
} }
+29 -11
View File
@@ -1,6 +1,7 @@
// Copyright 2020 - Nym Technologies SA <contact@nymtech.net> // Copyright 2020 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
use crate::var_names::{DEPRECATED_API_VALIDATOR, DEPRECATED_NYMD_VALIDATOR, NYM_API, NYXD};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{env::var, ops::Not, path::PathBuf}; use std::{env::var, ops::Not, path::PathBuf};
use url::Url; use url::Url;
@@ -77,8 +78,8 @@ impl NymNetworkDetails {
.expect("denomination exponent is not u32"), .expect("denomination exponent is not u32"),
}) })
.with_validator_endpoint(ValidatorDetails::new( .with_validator_endpoint(ValidatorDetails::new(
var(var_names::NYMD_VALIDATOR).expect("nymd validator not set"), var(var_names::NYXD).expect("nyxd validator not set"),
Some(var(var_names::API_VALIDATOR).expect("api validator not set")), Some(var(var_names::NYM_API).expect("nym api not set")),
)) ))
.with_mixnet_contract(Some( .with_mixnet_contract(Some(
var(var_names::MIXNET_CONTRACT_ADDRESS).expect("mixnet contract not set"), var(var_names::MIXNET_CONTRACT_ADDRESS).expect("mixnet contract not set"),
@@ -254,7 +255,7 @@ impl DenomDetailsOwned {
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] #[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ValidatorDetails { pub struct ValidatorDetails {
// it is assumed those values are always valid since they're being provided in our defaults file // it is assumed those values are always valid since they're being provided in our defaults file
pub nymd_url: String, pub nyxd_url: String,
// Right now api_url is optional as we are not running the api reliably on all validators // Right now api_url is optional as we are not running the api reliably on all validators
// however, later on it should be a mandatory field // however, later on it should be a mandatory field
pub api_url: Option<String>, pub api_url: Option<String>,
@@ -262,24 +263,24 @@ pub struct ValidatorDetails {
} }
impl ValidatorDetails { impl ValidatorDetails {
pub fn new<S: Into<String>>(nymd_url: S, api_url: Option<S>) -> Self { pub fn new<S: Into<String>>(nyxd_url: S, api_url: Option<S>) -> Self {
ValidatorDetails { ValidatorDetails {
nymd_url: nymd_url.into(), nyxd_url: nyxd_url.into(),
api_url: api_url.map(Into::into), api_url: api_url.map(Into::into),
} }
} }
pub fn new_nymd_only<S: Into<String>>(nymd_url: S) -> Self { pub fn new_nyxd_only<S: Into<String>>(nyxd_url: S) -> Self {
ValidatorDetails { ValidatorDetails {
nymd_url: nymd_url.into(), nyxd_url: nyxd_url.into(),
api_url: None, api_url: None,
} }
} }
pub fn nymd_url(&self) -> Url { pub fn nyxd_url(&self) -> Url {
self.nymd_url self.nyxd_url
.parse() .parse()
.expect("the provided nymd url is invalid!") .expect("the provided nyxd url is invalid!")
} }
pub fn api_url(&self) -> Option<Url> { pub fn api_url(&self) -> Option<Url> {
@@ -289,6 +290,20 @@ impl ValidatorDetails {
} }
} }
fn fix_deprecated_environmental_variables() {
// if we're using the outdated environmental variables, set the updated ones to preserve compatibility
if let Ok(nyxd) = std::env::var(DEPRECATED_NYMD_VALIDATOR) {
if std::env::var(NYXD).is_err() {
std::env::set_var(NYXD, nyxd)
}
}
if let Ok(nym_apis) = std::env::var(DEPRECATED_API_VALIDATOR) {
if std::env::var(NYM_API).is_err() {
std::env::set_var(NYM_API, nym_apis)
}
}
}
pub fn setup_env(config_env_file: Option<&PathBuf>) { pub fn setup_env(config_env_file: Option<&PathBuf>) {
match std::env::var(var_names::CONFIGURED) { match std::env::var(var_names::CONFIGURED) {
// if the configuration is not already set in the env vars // if the configuration is not already set in the env vars
@@ -296,6 +311,7 @@ pub fn setup_env(config_env_file: Option<&PathBuf>) {
if let Some(config_env_file) = config_env_file { if let Some(config_env_file) = config_env_file {
dotenv::from_path(config_env_file) dotenv::from_path(config_env_file)
.expect("Invalid path to environment configuration file"); .expect("Invalid path to environment configuration file");
fix_deprecated_environmental_variables();
} else { } else {
// if nothing is set, the use mainnet defaults // if nothing is set, the use mainnet defaults
// if the user has not set `CONFIGURED`, then even if they set any of the env variables, // if the user has not set `CONFIGURED`, then even if they set any of the env variables,
@@ -304,7 +320,9 @@ pub fn setup_env(config_env_file: Option<&PathBuf>) {
} }
} }
Err(_) => crate::mainnet::export_to_env(), Err(_) => crate::mainnet::export_to_env(),
_ => {} _ => {
fix_deprecated_environmental_variables();
}
} }
// if we haven't explicitly defined any of the constants, fallback to defaults // if we haven't explicitly defined any of the constants, fallback to defaults
+7 -7
View File
@@ -26,10 +26,10 @@ pub(crate) const _ETH_ERC20_CONTRACT_ADDRESS: [u8; 20] =
pub(crate) const REWARDING_VALIDATOR_ADDRESS: &str = "n10yyd98e2tuwu0f7ypz9dy3hhjw7v772q6287gy"; pub(crate) const REWARDING_VALIDATOR_ADDRESS: &str = "n10yyd98e2tuwu0f7ypz9dy3hhjw7v772q6287gy";
pub const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "https://mainnet-stats.nymte.ch:8090/"; pub const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "https://mainnet-stats.nymte.ch:8090/";
pub const NYMD_VALIDATOR: &str = "https://rpc.nymtech.net"; pub const NYXD_URL: &str = "https://rpc.nymtech.net";
pub const API_VALIDATOR: &str = "https://validator.nymtech.net/api/"; pub const NYM_API: &str = "https://validator.nymtech.net/api/";
pub(crate) fn validators() -> Vec<ValidatorDetails> { pub(crate) fn validators() -> Vec<ValidatorDetails> {
vec![ValidatorDetails::new(NYMD_VALIDATOR, Some(API_VALIDATOR))] vec![ValidatorDetails::new(NYXD_URL, Some(NYM_API))]
} }
const DEFAULT_SUFFIX: &str = "_MAINNET_DEFAULT"; const DEFAULT_SUFFIX: &str = "_MAINNET_DEFAULT";
@@ -97,8 +97,8 @@ pub fn export_to_env() {
var_names::STATISTICS_SERVICE_DOMAIN_ADDRESS, var_names::STATISTICS_SERVICE_DOMAIN_ADDRESS,
STATISTICS_SERVICE_DOMAIN_ADDRESS, STATISTICS_SERVICE_DOMAIN_ADDRESS,
); );
set_var_to_default(var_names::NYMD_VALIDATOR, NYMD_VALIDATOR); set_var_to_default(var_names::NYXD, NYXD_URL);
set_var_to_default(var_names::API_VALIDATOR, API_VALIDATOR); set_var_to_default(var_names::NYM_API, NYM_API);
} }
pub fn export_to_env_if_not_set() { pub fn export_to_env_if_not_set() {
@@ -141,6 +141,6 @@ pub fn export_to_env_if_not_set() {
var_names::STATISTICS_SERVICE_DOMAIN_ADDRESS, var_names::STATISTICS_SERVICE_DOMAIN_ADDRESS,
STATISTICS_SERVICE_DOMAIN_ADDRESS, STATISTICS_SERVICE_DOMAIN_ADDRESS,
); );
set_var_conditionally_to_default(var_names::NYMD_VALIDATOR, NYMD_VALIDATOR); set_var_conditionally_to_default(var_names::NYXD, NYXD_URL);
set_var_conditionally_to_default(var_names::API_VALIDATOR, API_VALIDATOR); set_var_conditionally_to_default(var_names::NYM_API, NYM_API);
} }
+6 -2
View File
@@ -18,5 +18,9 @@ pub const MULTISIG_CONTRACT_ADDRESS: &str = "MULTISIG_CONTRACT_ADDRESS";
pub const COCONUT_DKG_CONTRACT_ADDRESS: &str = "COCONUT_DKG_CONTRACT_ADDRESS"; pub const COCONUT_DKG_CONTRACT_ADDRESS: &str = "COCONUT_DKG_CONTRACT_ADDRESS";
pub const REWARDING_VALIDATOR_ADDRESS: &str = "REWARDING_VALIDATOR_ADDRESS"; pub const REWARDING_VALIDATOR_ADDRESS: &str = "REWARDING_VALIDATOR_ADDRESS";
pub const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "STATISTICS_SERVICE_DOMAIN_ADDRESS"; pub const STATISTICS_SERVICE_DOMAIN_ADDRESS: &str = "STATISTICS_SERVICE_DOMAIN_ADDRESS";
pub const NYMD_VALIDATOR: &str = "NYMD_VALIDATOR"; pub const NYXD: &str = "NYXD";
pub const API_VALIDATOR: &str = "API_VALIDATOR"; pub const NYM_API: &str = "NYM_API";
// we don't want to explicitly tag those with `#[deprecated]` because then our CI would be red and sad : (
pub const DEPRECATED_NYMD_VALIDATOR: &str = "NYMD_VALIDATOR";
pub const DEPRECATED_API_VALIDATOR: &str = "API_VALIDATOR";
+1 -1
View File
@@ -23,7 +23,7 @@ cosmwasm-std = "1.0.0"
cosmrs = { git = "https://github.com/neacsu/cosmos-rust", branch = "neacsu/feegrant_support" } cosmrs = { git = "https://github.com/neacsu/cosmos-rust", branch = "neacsu/feegrant_support" }
validator-client = { path = "../../common/client-libs/validator-client", features = [ validator-client = { path = "../../common/client-libs/validator-client", features = [
"nymd-client", "nyxd-client",
] } ] }
mixnet-contract-common = { path = "../../common/cosmwasm-smart-contracts/mixnet-contract" } mixnet-contract-common = { path = "../../common/cosmwasm-smart-contracts/mixnet-contract" }
vesting-contract-common = { path = "../../common/cosmwasm-smart-contracts/vesting-contract" } vesting-contract-common = { path = "../../common/cosmwasm-smart-contracts/vesting-contract" }

Some files were not shown because too many files have changed in this diff Show More