From d963527f2d71164502b121a1c53bb6d18ffc0cc0 Mon Sep 17 00:00:00 2001 From: nhpd Date: Wed, 9 Oct 2024 17:15:47 +0400 Subject: [PATCH] remove bindings; remove bindings for ibc-transfer contract --- contracts/ibc_transfer/Cargo.toml | 1 + contracts/ibc_transfer/src/contract.rs | 72 +- .../neutron_interchain_txs/src/contract.rs | 2 - packages/neutron-sdk/Cargo.toml | 1 + .../neutron-sdk/src/bin/neutron-sdk-schema.rs | 13 +- packages/neutron-sdk/src/bindings/dex/mod.rs | 3 - packages/neutron-sdk/src/bindings/dex/msg.rs | 102 - .../neutron-sdk/src/bindings/dex/query.rs | 231 -- .../neutron-sdk/src/bindings/dex/types.rs | 199 -- .../neutron-sdk/src/bindings/marketmap/mod.rs | 2 - .../src/bindings/marketmap/query.rs | 48 - .../src/bindings/marketmap/types.rs | 84 - packages/neutron-sdk/src/bindings/mod.rs | 4 - packages/neutron-sdk/src/bindings/msg.rs | 477 +-- .../neutron-sdk/src/bindings/oracle/mod.rs | 2 - .../neutron-sdk/src/bindings/oracle/query.rs | 40 - .../neutron-sdk/src/bindings/oracle/types.rs | 23 - packages/neutron-sdk/src/bindings/query.rs | 171 -- .../neutron-sdk/src/interchain_queries/mod.rs | 2 +- .../src/interchain_queries/queries.rs | 96 +- .../src/interchain_queries/v045/mod.rs | 10 - .../src/interchain_queries/v045/queries.rs | 534 ++-- .../v045/register_queries.rs | 354 --- .../src/interchain_queries/v047/mod.rs | 20 +- .../src/interchain_queries/v047/queries.rs | 152 +- .../v047/register_queries.rs | 116 +- .../src/interchain_queries/v047/testing.rs | 2648 ++++++++--------- .../src/interchain_queries/v047/types.rs | 272 +- packages/neutron-sdk/src/lib.rs | 1 - packages/neutron-sdk/src/query/min_ibc_fee.rs | 18 - packages/neutron-sdk/src/query/mod.rs | 3 - .../neutron-sdk/src/query/token_factory.rs | 54 - .../src/query/total_burned_neutrons.rs | 18 - 33 files changed, 1957 insertions(+), 3816 deletions(-) delete mode 100644 packages/neutron-sdk/src/bindings/dex/mod.rs delete mode 100644 packages/neutron-sdk/src/bindings/dex/msg.rs delete mode 100644 packages/neutron-sdk/src/bindings/dex/query.rs delete mode 100644 packages/neutron-sdk/src/bindings/dex/types.rs delete mode 100644 packages/neutron-sdk/src/bindings/marketmap/mod.rs delete mode 100644 packages/neutron-sdk/src/bindings/marketmap/query.rs delete mode 100644 packages/neutron-sdk/src/bindings/marketmap/types.rs delete mode 100644 packages/neutron-sdk/src/bindings/oracle/mod.rs delete mode 100644 packages/neutron-sdk/src/bindings/oracle/query.rs delete mode 100644 packages/neutron-sdk/src/bindings/oracle/types.rs delete mode 100644 packages/neutron-sdk/src/bindings/query.rs delete mode 100644 packages/neutron-sdk/src/interchain_queries/v045/register_queries.rs delete mode 100644 packages/neutron-sdk/src/query/min_ibc_fee.rs delete mode 100644 packages/neutron-sdk/src/query/mod.rs delete mode 100644 packages/neutron-sdk/src/query/token_factory.rs delete mode 100644 packages/neutron-sdk/src/query/total_burned_neutrons.rs diff --git a/contracts/ibc_transfer/Cargo.toml b/contracts/ibc_transfer/Cargo.toml index e53f6dae..c253a0d7 100644 --- a/contracts/ibc_transfer/Cargo.toml +++ b/contracts/ibc_transfer/Cargo.toml @@ -26,6 +26,7 @@ serde-json-wasm = { workspace = true } cw-storage-plus = { workspace = true, features = ["iterator"]} cosmwasm-schema = { workspace = true } neutron-sdk = { path = "../../packages/neutron-sdk", default-features = false } +neutron-std = "4.2.2-rc" [dev-dependencies] cosmwasm-schema = { workspace = true } diff --git a/contracts/ibc_transfer/src/contract.rs b/contracts/ibc_transfer/src/contract.rs index 46ddeb0c..187c06c6 100644 --- a/contracts/ibc_transfer/src/contract.rs +++ b/contracts/ibc_transfer/src/contract.rs @@ -3,20 +3,17 @@ use cosmwasm_std::{ StdError, StdResult, SubMsg, }; use cw2::set_contract_version; +use neutron_std::types::neutron::transfer::MsgTransfer; use neutron_sdk::interchain_txs::helpers::decode_message_response; -use neutron_sdk::proto_types::neutron::transfer::MsgTransferResponse; +use neutron_sdk::proto_types::neutron::transfer::{MsgTransferResponse}; use neutron_sdk::{ - bindings::{ - msg::{IbcFee, NeutronMsg}, - query::NeutronQuery, - }, - query::min_ibc_fee::query_min_ibc_fee, sudo::msg::{RequestPacket, RequestPacketTimeoutHeight, TransferSudoMsg}, NeutronResult, }; +use neutron_std::types::cosmos::base::v1beta1::Coin as SuperCoin; // TODO: rename use schemars::JsonSchema; use serde::{Deserialize, Serialize}; - +use neutron_sdk::proto_types::neutron::feerefunder::{Fee, FeerefunderQuerier}; use crate::{ msg::{ExecuteMsg, InstantiateMsg, MigrateMsg}, state::{ @@ -45,11 +42,11 @@ pub fn instantiate( #[entry_point] pub fn execute( - deps: DepsMut, + deps: DepsMut, env: Env, _: MessageInfo, msg: ExecuteMsg, -) -> NeutronResult> { +) -> StdResult { match msg { // NOTE: this is an example contract that shows how to make IBC transfers! // Please add necessary authorization or other protection mechanisms @@ -100,7 +97,7 @@ pub enum SudoPayload { // saves payload to process later to the storage and returns a SubmitTX Cosmos SubMsg with necessary reply id fn msg_with_sudo_callback>, T>( - deps: DepsMut, + deps: DepsMut, msg: C, payload: SudoPayload, ) -> StdResult> { @@ -143,46 +140,44 @@ pub fn reply(deps: DepsMut, env: Env, msg: Reply) -> StdResult { } fn execute_send( - mut deps: DepsMut, + mut deps: DepsMut, env: Env, channel: String, to: String, denom: String, amount: u128, timeout_height: Option, -) -> NeutronResult> { +) -> StdResult { // contract must pay for relaying of acknowledgements // See more info here: https://docs.neutron.org/neutron/feerefunder/overview - let fee = min_ntrn_ibc_fee(query_min_ibc_fee(deps.as_ref())?.min_fee); - let coin1 = coin(amount, denom.clone()); - let msg1 = NeutronMsg::IbcTransfer { + let fee = min_ntrn_ibc_fee(query_min_fee(deps.as_ref())?); + let msg1 = MsgTransfer { source_port: "transfer".to_string(), source_channel: channel.clone(), sender: env.contract.address.to_string(), receiver: to.clone(), - token: coin1, - timeout_height: RequestPacketTimeoutHeight { - revision_number: Some(2), - revision_height: timeout_height.or(Some(DEFAULT_TIMEOUT_HEIGHT)), - }, + token: Some(SuperCoin{ denom: denom.clone(), amount: amount.to_string() }), + timeout_height: Some(neutron_std::types::ibc::core::client::v1::Height { + revision_number: 2, + revision_height: timeout_height.unwrap_or_else(|| DEFAULT_TIMEOUT_HEIGHT), + }), timeout_timestamp: 0, memo: "".to_string(), - fee: fee.clone(), + fee: Some(fee.clone()), }; - let coin2 = coin(2 * amount, denom); - let msg2 = NeutronMsg::IbcTransfer { + let msg2 = MsgTransfer { source_port: "transfer".to_string(), source_channel: channel, sender: env.contract.address.to_string(), receiver: to, - token: coin2, - timeout_height: RequestPacketTimeoutHeight { - revision_number: Some(2), - revision_height: timeout_height.or(Some(DEFAULT_TIMEOUT_HEIGHT)), - }, + token: Some(SuperCoin{ denom, amount: (2 * amount).to_string() }), + timeout_height: Some(neutron_std::types::ibc::core::client::v1::Height { + revision_number: 2, + revision_height: timeout_height.unwrap_or_else(|| DEFAULT_TIMEOUT_HEIGHT), + }), timeout_timestamp: 0, memo: "".to_string(), - fee, + fee: Some(fee.clone()), }; // prepare first transfer message with payload of Type1 let submsg1 = msg_with_sudo_callback( @@ -279,17 +274,26 @@ pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult IbcFee { - IbcFee { - recv_fee: fee.recv_fee, +fn query_min_fee(deps: Deps) -> StdResult { + let querier = FeerefunderQuerier::new(&deps.querier); + let params = querier.params()?; + let params_inner = params.params.ok_or_else(|| StdError::generic_err("no params found for feerefunder"))?; + let min_fee = params_inner.min_fee.ok_or_else(|| StdError::generic_err("no minimum fee param for feerefunder"))?; + + Ok(min_fee) +} + +fn min_ntrn_ibc_fee(fee: Fee) -> neutron_std::types::neutron::feerefunder::Fee { + neutron_std::types::neutron::feerefunder::Fee { + recv_fee: fee.recv_fee.iter().map(|r| SuperCoin{ denom: r.denom.to_string(), amount: r.amount.clone() } ).collect(), ack_fee: fee .ack_fee - .into_iter() + .iter().map(|r| SuperCoin{ denom: r.denom.to_string(), amount: r.amount.clone() } ) .filter(|a| a.denom == FEE_DENOM) .collect(), timeout_fee: fee .timeout_fee - .into_iter() + .iter().map(|r| SuperCoin{ denom: r.denom.to_string(), amount: r.amount.clone() } ) .filter(|a| a.denom == FEE_DENOM) .collect(), } diff --git a/contracts/neutron_interchain_txs/src/contract.rs b/contracts/neutron_interchain_txs/src/contract.rs index a23cb4b5..cddab948 100644 --- a/contracts/neutron_interchain_txs/src/contract.rs +++ b/contracts/neutron_interchain_txs/src/contract.rs @@ -22,12 +22,10 @@ use neutron_sdk::proto_types::neutron::interchaintxs::v1::MsgSubmitTxResponse; use neutron_sdk::{ bindings::{ msg::NeutronMsg, - query::{NeutronQuery, QueryInterchainAccountAddressResponse}, types::ProtobufAny, }, interchain_txs::helpers::{decode_message_response, get_port_id}, interchain_txs::v047::helpers::decode_acknowledgement_response, - query::min_ibc_fee::query_min_ibc_fee, sudo::msg::{RequestPacket, SudoMsg}, NeutronError, NeutronResult, }; diff --git a/packages/neutron-sdk/Cargo.toml b/packages/neutron-sdk/Cargo.toml index ad1fcfc0..5d710d23 100644 --- a/packages/neutron-sdk/Cargo.toml +++ b/packages/neutron-sdk/Cargo.toml @@ -25,6 +25,7 @@ prost-types = { workspace = true } tendermint-proto = { workspace = true } speedate = { workspace = true } chrono = { version = "0.4.22", default-features = false } +neutron-std = { version = "4.2.2-rc" } neutron-std-derive = { version = "0.20.1", path = "../neutron-std-derive" } [dev-dependencies] diff --git a/packages/neutron-sdk/src/bin/neutron-sdk-schema.rs b/packages/neutron-sdk/src/bin/neutron-sdk-schema.rs index 6132c48b..31ce2532 100644 --- a/packages/neutron-sdk/src/bin/neutron-sdk-schema.rs +++ b/packages/neutron-sdk/src/bin/neutron-sdk-schema.rs @@ -1,14 +1,3 @@ -use std::env::current_dir; -use std::fs::create_dir_all; - -use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; -use neutron_sdk::bindings::{msg::NeutronMsg, query::NeutronQuery}; - fn main() { - let mut out_dir = current_dir().unwrap(); - out_dir.push("schema"); - create_dir_all(&out_dir).unwrap(); - remove_schemas(&out_dir).unwrap(); - export_schema(&schema_for!(NeutronMsg), &out_dir); - export_schema(&schema_for!(NeutronQuery), &out_dir); + // TODO: remove this file } diff --git a/packages/neutron-sdk/src/bindings/dex/mod.rs b/packages/neutron-sdk/src/bindings/dex/mod.rs deleted file mode 100644 index 299b4f33..00000000 --- a/packages/neutron-sdk/src/bindings/dex/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod msg; -pub mod query; -pub mod types; diff --git a/packages/neutron-sdk/src/bindings/dex/msg.rs b/packages/neutron-sdk/src/bindings/dex/msg.rs deleted file mode 100644 index d1e06baa..00000000 --- a/packages/neutron-sdk/src/bindings/dex/msg.rs +++ /dev/null @@ -1,102 +0,0 @@ -use crate::bindings::dex::types::LimitOrderType; -use cosmwasm_std::Uint128; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -use super::types::{DepositOptions, MultiHopRoute, PrecDec}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum DexMsg { - /// Deposit provides liquidity to a specific trading pair by depositing tokens - /// at a specific price into one or both sides of the pair in “a liquidity pool” - Deposit { - /// The account to which PoolShares will be issued - receiver: String, - /// Denom for one side of the deposit - token_a: String, - /// Denom for the opposing side of the deposit - token_b: String, - /// Amounts of tokenA to deposit - amounts_a: Vec, - /// Amounts of tokenB to deposit - amounts_b: Vec, - /// Tick indexes to deposit at defined in terms of TokenA to TokenB (ie. TokenA is on the left) - tick_indexes_a_to_b: Vec, - /// Fees to use for each deposit - fees: Vec, - /// Additional deposit options - options: Vec, - }, - /// Withdraw is used to redeem PoolShares for the user’s pro-rata - /// portion of tokens within a liquidity pool. Users can withdraw from a pool at any time - Withdrawal { - /// The account to which the tokens are credited - receiver: String, - /// Denom for one side of the deposit - token_a: String, - /// Denom for the opposing side of the deposit - token_b: String, - /// Amount of shares to remove from each pool - shares_to_remove: Vec, - /// Tick indexes of the target LiquidityPools defined in terms of TokenA to TokenB - /// (ie. TokenA is on the left) - tick_indexes_a_to_b: Vec, - /// Fee for the target LiquidityPools - fees: Vec, - }, - /// PlaceLimitOrder provides the primary mechanism for trading on the Duality Dex. Limit - /// orders can provide liquidity to the Dex (“Maker Limit Orders”) and/or can be used to - /// trade against preexisting liquidity (“Taker Limit Orders”) - PlaceLimitOrder { - /// Account to which TokenOut is credited or that will be allowed to - /// withdraw or cancel a maker order - receiver: String, - /// Token being “sold” - token_in: String, - /// Token being “bought” - token_out: String, - /// Limit tick for a limit order, specified in terms of TokenIn to TokenOut - tick_index_in_to_out: i64, - /// Amount of TokenIn to be traded - amount_in: Uint128, - /// Type of limit order to be used. Must be one of: - /// GOOD_TIL_CANCELLED, FILL_OR_KILL, IMMEDIATE_OR_CANCEL, JUST_IN_TIME, or GOOD_TIL_TIME - order_type: LimitOrderType, - // expirationTime is only valid if orderType == GOOD_TIL_TIME. - /// Expiration time for order. Only valid for GOOD_TIL_TIME limit orders - expiration_time: Option, - /// Maximum amount of TokenB can be bought. For everything except JUST_IN_TIME OrderType - max_amount_out: Option, - /// Accepts standard decimals and decimals with scientific notation (ie. 1234.23E-7) - limit_sell_price: String, - }, - /// WithdrawFilledLimitOrder. Once a limit order has been filled – either partially or in - /// its entirety, it can be withdrawn at any time. Withdrawing from a limit order credits - /// all available proceeds to the user. Withdraw can be called on a limit order multiple - /// times as new proceeds become available - WithdrawFilledLimitOrder { - /// TrancheKey for the target limit order - tranche_key: String, - }, - /// CancelLimitOrder. Standard Taker limit orders (Good-til-cancelled & Good-til-Time) - /// can be canceled at any time if they have not been completely filled - CancelLimitOrder { - /// TrancheKey for the target limit order - tranche_key: String, - }, - /// MultiHopSwap provides a swapping mechanism to achieve better prices by routing - /// through a series of pools - MultiHopSwap { - /// Account to which TokenOut is credited - receiver: String, - /// Array of possible routes - routes: Vec, - /// Amount of TokenIn to swap - amount_in: Uint128, - /// Minimum price that that must be satisfied for a route to succeed - exit_limit_price: PrecDec, - /// If true all routes are run and the route with the best price is used - pick_best_route: bool, - }, -} diff --git a/packages/neutron-sdk/src/bindings/dex/query.rs b/packages/neutron-sdk/src/bindings/dex/query.rs deleted file mode 100644 index 0f39f74b..00000000 --- a/packages/neutron-sdk/src/bindings/dex/query.rs +++ /dev/null @@ -1,231 +0,0 @@ -use crate::bindings::dex::types::{ - DepositRecord, LimitOrderTranche, LimitOrderTrancheUser, LimitOrderType, MultiHopRoute, Params, - Pool, PoolMetadata, PoolReserves, PrecDec, TickLiquidity, -}; -use crate::bindings::query::{PageRequest, PageResponse}; -use cosmwasm_std::{Coin, Int128}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum DexQuery { - /// Parameters queries the parameters of the module. - Params {}, - /// Queries a LimitOrderTrancheUser by index. - LimitOrderTrancheUser { - address: String, - tranche_key: String, - }, - /// Queries a list of LimitOrderTrancheMap items. - LimitOrderTrancheUserAll { pagination: Option }, - /// Queries a list of LimitOrderTrancheUser items for a given address. - LimitOrderTrancheUserAllByAddress { - address: String, - pagination: Option, - }, - /// Queries a LimitOrderTranche by index. - LimitOrderTranche { - pair_id: String, - tick_index: i64, - token_in: String, - tranche_key: String, - }, - /// Queries a list of LimitOrderTranche items for a given pairID / TokenIn combination. - LimitOrderTrancheAll { - pair_id: String, - token_in: String, - pagination: Option, - }, - /// Queries a list of UserDeposits items. - UserDepositAll { - address: String, - include_pool_data: bool, - pagination: Option, - }, - /// Queries a list of TickLiquidity items. - TickLiquidityAll { - pair_id: String, - token_in: String, - pagination: Option, - }, - /// Queries a InactiveLimitOrderTranche by index. - InactiveLimitOrderTranche { - pair_id: String, - tick_index: i64, - token_in: String, - tranche_key: String, - }, - /// Queries a list of InactiveLimitOrderTranche items. - InactiveLimitOrderTrancheAll { pagination: Option }, - /// Queries a list of PoolReserves items. - PoolReservesAll { - pair_id: String, - token_in: String, - pagination: Option, - }, - /// Queries a PoolReserve by index - PoolReserves { - pair_id: String, - token_in: String, - tick_index: i64, - fee: u64, - }, - /// Queries the simulated result of a multihop swap - EstimateMultiHopSwap { - creator: String, - receiver: String, - routes: Vec, - amount_in: Int128, - exit_limit_price: PrecDec, - pick_best_route: bool, - }, - /// Queries the simulated result of a PlaceLimit order - EstimatePlaceLimitOrder { - creator: String, - receiver: String, - token_in: String, - token_out: String, - tick_index_in_to_out: i64, - amount_in: Int128, - order_type: LimitOrderType, - // expirationTime is only valid iff orderType == GOOD_TIL_TIME. - expiration_time: Option, - max_amount_out: Option, - }, - /// Queries a pool by pair, tick and fee - Pool { - pair_id: String, - tick_index: i64, - fee: u64, - }, - /// Queries a pool by ID - #[serde(rename = "pool_by_id")] - PoolByID { pool_id: u64 }, - /// Queries a PoolMetadata by ID - PoolMetadata { id: u64 }, - /// Queries a list of PoolMetadata items. - PoolMetadataAll { pagination: Option }, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct ParamsResponse { - pub params: Params, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct LimitOrderTrancheUserResponse { - pub limit_order_tranche_user: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct AllLimitOrderTrancheUserResponse { - #[serde(default)] - pub limit_order_tranche_user: Vec, - pub pagination: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)] -#[serde(rename_all = "snake_case")] -pub struct AllUserLimitOrdersResponse { - #[serde(default)] - pub limit_orders: Vec, - pub pagination: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct LimitOrderTrancheResponse { - pub limit_order_tranche: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)] -#[serde(rename_all = "snake_case")] -pub struct AllLimitOrderTrancheResponse { - #[serde(default)] - pub limit_order_tranche: Vec, - pub pagination: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)] -#[serde(rename_all = "snake_case")] -pub struct AllUserDepositsResponse { - #[serde(default)] - pub deposits: Vec, - pub pagination: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct AllTickLiquidityResponse { - pub tick_liquidity: Vec, - pub pagination: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct InactiveLimitOrderTrancheResponse { - pub inactive_limit_order_tranche: LimitOrderTranche, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct AllInactiveLimitOrderTrancheResponse { - pub inactive_limit_order_tranche: Vec, - pub pagination: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct AllPoolReservesResponse { - pub pool_reserves: Vec, - pub pagination: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct PoolReservesResponse { - pub pool_reserves: PoolReserves, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct EstimateMultiHopSwapResponse { - pub coin_out: Coin, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct EstimatePlaceLimitOrderResponse { - /// Total amount of coin used for the limit order - /// You can derive makerLimitInCoin using the equation: totalInCoin = swapInCoin + makerLimitInCoin - pub total_in_coin: Coin, - /// Total amount of the token in that was immediately swapped for swapOutCoin - pub swap_in_coin: Coin, - /// Total amount of coin received from the taker portion of the limit order - /// This is the amount of coin immediately available in the users account after executing the - /// limit order. It does not include any future proceeds from the maker portion which will have withdrawn in the future - pub swap_out_coin: Coin, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct PoolResponse { - pub pool: Pool, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct PoolMetadataResponse { - pub pool_metadata: PoolMetadata, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct AllPoolMetadataResponse { - pub pool_metadata: Vec, - pub pagination: Option, -} diff --git a/packages/neutron-sdk/src/bindings/dex/types.rs b/packages/neutron-sdk/src/bindings/dex/types.rs deleted file mode 100644 index 58c4742b..00000000 --- a/packages/neutron-sdk/src/bindings/dex/types.rs +++ /dev/null @@ -1,199 +0,0 @@ -use cosmwasm_std::Int128; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum LimitOrderType { - #[default] - /// Good-til-Cancelled limit orders are hybrid maker and taker limit orders. - /// They will attempt to trade the supplied AmountIn at the TickIndex or better. - /// However, if they total AmountIn cannot be traded at the limit price they are remaining - /// amount will be placed as a maker limit order. The proceeds from the taker portion - /// are deposited into the user’s account immediately, however, the proceeds from the - /// maker portion must be explicitly withdrawn via WithdrawLimitOrder. - GoodTilCancelled, - /// Fill-or-Kill limit orders are taker limit orders that either successfully swap 100% - /// of the supplied AmountIn or return an error. If there is insufficient liquidity to - /// complete the trade at or above the supplied TickIndex a Fill-or-Kill order will - /// return an error `codespace: dex, code: 1134` - /// ( ErrGoodTilOrderWithoutExpiration). - FillOrKill, - /// Immediate-or-Cancel limit orders are taker orders that will swap as much as of the - /// AmountIn as possible given available liquidity above the supplied TickIndex. - /// Unlike Fill-or-Kill orders they will still successfully complete even if they - /// are only able to partially trade through the AmountIn at the TickIndex or better. - ImmediateOrCancel, - /// Just-in-Time limit orders are an advanced maker limit order that provides tradeable - /// liquidity for exactly one block. At the end of the same block in which the Just-in-Time - /// order was submitted the order is canceled and any untraded portion will no longer be - /// usable as active liquidity. - JustInTime, - /// Good-til-Time limit order function exactly the same as Good-til-Cancelled limit orders - /// first trying to trade as a taker limit order and then placing any remaining amount - /// as a maker limit order. However, the maker portion of the limit order has a specified ExpirationTime. - /// After the ExpirationTime the order will be cancelled and can no longer be traded against. - /// When withdrawing a Good-til-Time limit order the user will receive both the successfully - /// traded portion of the limit order (TokenOut) as well as any remaining untraded amount (TokenIn). - GoodTilTime, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)] -#[serde(rename_all = "snake_case", default)] -pub struct LimitOrderTrancheUser { - pub trade_pair_id: TradePairID, - pub tick_index_taker_to_maker: i64, - pub tranche_key: String, - pub address: String, - pub shares_owned: Int128, - pub shares_withdrawn: Int128, - pub shares_cancelled: Int128, - pub order_type: LimitOrderType, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct LimitOrderTrancheKey { - pub trade_pair_id: TradePairID, - pub tick_index_taker_to_maker: i64, - pub tranche_key: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct LimitOrderTranche { - pub key: LimitOrderTrancheKey, - pub reserves_maker_denom: Int128, - pub reserves_taker_denom: Int128, - pub total_maker_denom: Int128, - pub total_taker_denom: Int128, - pub expiration_time: Option, - pub price_taker_to_maker: PrecDec, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)] -#[serde(rename_all = "snake_case")] -pub struct TradePairID { - pub maker_denom: String, - pub taker_denom: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)] -#[serde(rename_all = "snake_case")] -pub struct FailedDeposit { - pub deposit_idx: Option, - pub error: Option, -} - -// TODO implement math for PrecDec -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -#[serde(from = "String")] -#[serde(into = "String")] -pub struct PrecDec { - pub i: String, -} - -#[allow(clippy::from_over_into)] -impl Into for PrecDec { - fn into(self) -> String { - self.i - } -} - -impl From for PrecDec { - fn from(value: String) -> Self { - PrecDec { i: value } - } -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct DepositOptions { - pub disable_autoswap: Option, - pub fail_tx_on_bel: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct MultiHopRoute { - pub hops: Vec, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct Params { - pub fee_tiers: Vec, - pub paused: bool, - pub max_jits_per_block: u64, - pub good_til_purge_allowance: u64, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)] -#[serde(rename_all = "snake_case")] -#[serde(default)] -pub struct PoolMetadata { - pub id: u64, - pub tick: i64, - pub fee: u64, - pub pair_id: PairID, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct Pool { - #[serde(default)] - pub id: u64, - pub lower_tick0: Option, - pub upper_tick1: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct DepositRecord { - pub pair_id: PairID, - pub shares_owned: Int128, - pub center_tick_index: i64, - pub lower_tick_index: i64, - pub upper_tick_index: i64, - pub fee: Option, - pub total_shares: Option, - pub pool: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, Default)] -#[serde(rename_all = "snake_case")] -pub struct PairID { - pub token0: String, - pub token1: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct TickLiquidity { - pub liquidity: Liquidity, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum Liquidity { - PoolReserves(PoolReserves), - LimitOrderTranche(LimitOrderTranche), -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct PoolReserves { - pub key: PoolReservesKey, - pub reserves_maker_denom: Int128, - pub price_taker_to_maker: PrecDec, - pub price_opposite_taker_to_maker: PrecDec, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct PoolReservesKey { - pub trade_pair_id: TradePairID, - pub tick_index_taker_to_maker: i64, - pub fee: Option, -} diff --git a/packages/neutron-sdk/src/bindings/marketmap/mod.rs b/packages/neutron-sdk/src/bindings/marketmap/mod.rs deleted file mode 100644 index e44ca515..00000000 --- a/packages/neutron-sdk/src/bindings/marketmap/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod query; -pub mod types; diff --git a/packages/neutron-sdk/src/bindings/marketmap/query.rs b/packages/neutron-sdk/src/bindings/marketmap/query.rs deleted file mode 100644 index b62b8f90..00000000 --- a/packages/neutron-sdk/src/bindings/marketmap/query.rs +++ /dev/null @@ -1,48 +0,0 @@ -use crate::bindings::marketmap::types::{Market, MarketMap, Params}; -use crate::bindings::oracle::types::CurrencyPair; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum MarketMapQuery { - /// Parameters queries the parameters of the module. - Params {}, - LastUpdated {}, - MarketMap {}, - Market { - currency_pair: CurrencyPair, - }, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct ParamsResponse { - pub params: Params, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct LastUpdatedResponse { - pub last_updated: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct MarketMapResponse { - /// **market_map** defines the global set of market configurations for all providers - /// and markets. - pub market_map: MarketMap, - /// **last_updated** is the last block height that the market map was updated. - /// This field can be used as an optimization for clients checking if there - /// is a new update to the map. - pub last_updated: Option, - /// **chain_id** is the chain identifier for the market map. - pub chain_id: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct MarketResponse { - pub market: Market, -} diff --git a/packages/neutron-sdk/src/bindings/marketmap/types.rs b/packages/neutron-sdk/src/bindings/marketmap/types.rs deleted file mode 100644 index d3ffe95f..00000000 --- a/packages/neutron-sdk/src/bindings/marketmap/types.rs +++ /dev/null @@ -1,84 +0,0 @@ -use schemars::{JsonSchema, Map}; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct Params { - pub admin: String, - pub market_authorities: Vec, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct MarketMap { - pub markets: Map, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct Market { - /// **ticker** is the full list of tickers and their associated configurations - /// to be stored on-chain. - pub ticker: Ticker, - pub provider_configs: Vec, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct ProviderConfig { - /// **name** corresponds to the name of the provider for which the configuration is - /// being set. - pub name: String, - /// **off_chain_ticker** is the off-chain representation of the ticker i.e. BTC/USD. - /// The off-chain ticker is unique to a given provider and is used to fetch the - /// price of the ticker from the provider. - pub off_chain_ticker: String, - /// **normalize_by_pair** is the currency pair for this ticker to be normalized by. - /// For example, if the desired Ticker is BTC/USD, this market could be reached - /// using: OffChainTicker = BTC/USDT NormalizeByPair = USDT/USD This field is - /// optional and nullable. - pub normalize_by_pair: Option, - /// **invert** is a boolean indicating if the BASE and QUOTE of the market should - /// be inverted. i.e. BASE -> QUOTE, QUOTE -> BASE - #[serde(default)] - pub invert: bool, - /// **metadata_json** is a string of JSON that encodes any extra configuration - /// for the given provider config. - #[serde( - default, - rename(serialize = "metadata_JSON", deserialize = "metadata_JSON") - )] - pub metadata_json: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -pub struct CurrencyPair { - #[serde(rename(serialize = "Base", deserialize = "Base"))] - pub base: String, - #[serde(rename(serialize = "Quote", deserialize = "Quote"))] - pub quote: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct Ticker { - /// **currency_pair** is the currency pair for this ticker. - pub currency_pair: CurrencyPair, - /// **decimals** is the number of decimal places for the ticker. The number of - /// decimal places is used to convert the price to a human-readable format. - pub decimals: u64, - /// **min_provider_count** is the minimum number of providers required to consider - /// the ticker valid. - pub min_provider_count: u64, - /// **enabled** is the flag that denotes if the Ticker is enabled for price - /// fetching by an oracle. - #[serde(default)] - pub enabled: bool, - /// **metadata_json** is a string of JSON that encodes any extra configuration - /// for the given ticker. , - #[serde( - default, - rename(serialize = "metadata_JSON", deserialize = "metadata_JSON") - )] - pub metadata_json: String, -} diff --git a/packages/neutron-sdk/src/bindings/mod.rs b/packages/neutron-sdk/src/bindings/mod.rs index e09ce752..08938b58 100644 --- a/packages/neutron-sdk/src/bindings/mod.rs +++ b/packages/neutron-sdk/src/bindings/mod.rs @@ -1,7 +1,3 @@ -pub mod dex; -pub mod marketmap; #[allow(deprecated)] pub mod msg; -pub mod oracle; -pub mod query; pub mod types; diff --git a/packages/neutron-sdk/src/bindings/msg.rs b/packages/neutron-sdk/src/bindings/msg.rs index cc2c3fed..22cec40b 100644 --- a/packages/neutron-sdk/src/bindings/msg.rs +++ b/packages/neutron-sdk/src/bindings/msg.rs @@ -5,8 +5,6 @@ use crate::{ sudo::msg::RequestPacketTimeoutHeight, NeutronResult, }; - -use crate::bindings::dex::msg::DexMsg; use cosmwasm_std::{Binary, Coin, CosmosMsg, CustomMsg, DenomUnit, StdError, Uint128}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -35,188 +33,15 @@ pub enum ChannelOrdering { OrderUnordered, } +#[deprecated(note = "Please use neutron-std autogenerated messages instead of wasmbindings", since = "0.12.0")] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] /// A number of Custom messages that can call into the Neutron bindings. pub enum NeutronMsg { - /// RegisterInterchainAccount registers an interchain account on remote chain. - RegisterInterchainAccount { - /// **connection_id** is an IBC connection identifier between Neutron and remote chain. - connection_id: String, - - /// **interchain_account_id** is an identifier of your new interchain account. Can be any string. - /// This identifier allows contracts to have multiple interchain accounts on remote chains. - interchain_account_id: String, - - /// **register_fee** is a fees required to be payed to register interchain account - register_fee: Option>, - - /// **ordering** is an order of channel. Can be ordered or unordered. - /// Set to ordered if not specified. - ordering: Option, - }, - - /// SubmitTx starts the process of executing any Cosmos-SDK *msgs* on remote chain. - SubmitTx { - /// **connection_id** is an IBC connection identifier between Neutron and remote chain. - connection_id: String, - - /// **interchain_account_id** is an identifier of your interchain account from which you want to execute msgs. - interchain_account_id: String, - - /// **msgs** is a list of protobuf encoded Cosmos-SDK messages you want to execute on remote chain. - msgs: Vec, - - /// **memo** is a memo you want to attach to your interchain transaction.It behaves like a memo in usual Cosmos transaction. - memo: String, - - /// **timeout** is a timeout in seconds after which the packet times out. - timeout: u64, - - /// ***fee** is an ibc fee for the transaction. - fee: IbcFee, - }, - - /// RegisterInterchainQuery registers an interchain query. - RegisterInterchainQuery { - /// **query_type** is a query type identifier ('tx' or 'kv' for now). - query_type: String, - - /// **keys** is the KV-storage keys for which we want to get values from remote chain. - keys: Vec, - - /// **transactions_filter** is the filter for transaction search ICQ. - transactions_filter: String, - - /// **connection_id** is an IBC connection identifier between Neutron and remote chain. - connection_id: String, - - /// **update_period** is used to say how often the query must be updated. - update_period: u64, - }, - - /// RegisterInterchainQuery updates an interchain query. - UpdateInterchainQuery { - /// **query_id** is the ID of the query we want to update. - query_id: u64, - - /// **new_keys** is the new query keys to retrieve. - new_keys: Option>, - - /// **new_update_period** is a new update period of the query. - new_update_period: Option, - - /// **new_transactions_filter** is a new transactions filter of the query. - new_transactions_filter: Option, - }, - - /// RemoveInterchainQuery removes as interchain query. - RemoveInterchainQuery { - /// **query_id** is ID of the query we want to remove. - query_id: u64, - }, - /// IbcTransfer sends a fungible token packet over IBC. - IbcTransfer { - // the port on which the packet will be sent - source_port: String, - // the channel by which the packet will be sent - source_channel: String, - // the tokens to be transferred - token: Coin, - // the sender address - sender: String, - // the recipient address on the destination chain - receiver: String, - // Timeout height relative to the current block height. - // The timeout is disabled when set to 0. - timeout_height: RequestPacketTimeoutHeight, - // Timeout timestamp in absolute nanoseconds since unix epoch. - // The timeout is disabled when set to 0. - timeout_timestamp: u64, - // Memo to be sent along with transaction. - memo: String, - // Fees to refund relayer for different kinds of `SudoMsg` transmission - // Unused fee types will be returned to msg sender. - fee: IbcFee, - }, /// SubmitAdminProposal sends a proposal to neutron's Admin module. /// This type of messages can be only executed by Neutron DAO. SubmitAdminProposal { admin_proposal: AdminProposal }, - /// TokenFactory message. - /// Contracts can create denoms, namespaced under the contract's address. - /// A contract may create any number of independent sub-denoms. - CreateDenom { subdenom: String }, - - /// TokenFactory message. - /// Contracts can change the admin of a denom that they are the admin of. - ChangeAdmin { - denom: String, - new_admin_address: String, - }, - - /// TokenFactory message. - /// Contracts can mint native tokens for an existing factory denom - /// that they are the admin of. - MintTokens { - denom: String, - amount: Uint128, - mint_to_address: String, - }, - - /// TokenFactory message. - /// Contracts can burn native tokens for an existing factory denom - /// that they are the admin of. - /// Currently, the burn from address must be the admin contract. - BurnTokens { - denom: String, - amount: Uint128, - /// Must be set to `""` for now - burn_from_address: String, - }, - - /// TokenFactory message. - /// Contracts can set before send hooks for denoms, namespaced under the contract's address. - SetBeforeSendHook { - denom: String, - contract_addr: String, - }, - - /// TokenFactoryMessage - /// Contracts can force specified `amount` of an existing factory denom - /// that they are admin of to a `transfer_to_address` from a `transfer_from_address`. - ForceTransfer { - denom: String, - amount: Uint128, - transfer_from_address: String, - transfer_to_address: String, - }, - - /// TokenFactoryMessage - /// Contracts can set a metadata for of an existing factory denom - /// that they are admin of. - SetDenomMetadata { - /// **description** description of a token - description: String, - /// **denom_units** represents the list of DenomUnit's for a given coin - denom_units: Vec, - /// **base** represents the base denom (should be the DenomUnit with exponent = 0). - base: String, - /// **display** indicates the suggested denom that should be - /// displayed in clients. - display: String, - /// **name** defines the name of the token (eg: Cosmos Atom) - name: String, - /// **symbol** is the token symbol usually shown on exchanges (eg: ATOM). This can - /// be the same as the display. - symbol: String, - /// **uri** to a document (on or off-chain) that contains additional information. Optional. - uri: String, - /// **uri_hash** is a sha256 hash of a document pointed by URI. It's used to verify that - /// the document didn't change. Optional. - uri_hash: String, - }, - /// AddSchedule adds new schedule with a given `name`. /// Until schedule is removed it will execute all `msgs` every `period` blocks. /// First execution is at least on `current_block + period` block. @@ -242,304 +67,6 @@ pub enum NeutronMsg { /// Acknowledgement failure is created when contract returns error or acknowledgement is out of gas. /// [Permissioned - only from contract that is initial caller of IBC transaction] ResubmitFailure { failure_id: u64 }, - - /// Dex messages - Dex(DexMsg), -} - -impl NeutronMsg { - /// Basic helper to define a register interchain account message: - /// * **connection_id** is an IBC connection identifier between Neutron and remote chain; - /// * **interchain_account_id** is an identifier of your new interchain account. Can be any string. - /// * **ordering** is an ordering of ICA channel. Set to ORDERED if not specified - pub fn register_interchain_account( - connection_id: String, - interchain_account_id: String, - register_fee: Option>, - ordering: Option, - ) -> Self { - NeutronMsg::RegisterInterchainAccount { - connection_id, - interchain_account_id, - register_fee, - ordering, - } - } - - /// Basic helper to define a submit tx message: - /// * **connection_id** is an IBC connection identifier between Neutron and remote chain; - /// * **interchain_account_id** is an identifier of your interchain account from which you want to execute msgs; - /// * **msgs** is a list of protobuf encoded Cosmos-SDK messages you want to execute on remote chain; - /// * **memo** is a memo you want to attach to your interchain transaction. It behaves like a memo in usual Cosmos transaction; - /// * **timeout** is a timeout in seconds after which the packet times out. - /// * **fee** is a fee that is used for different kinds of callbacks. Unused fee types will be returned to msg sender. - pub fn submit_tx( - connection_id: String, - interchain_account_id: String, - msgs: Vec, - memo: String, - timeout: u64, - fee: IbcFee, - ) -> Self { - NeutronMsg::SubmitTx { - connection_id, - interchain_account_id, - msgs, - memo, - timeout, - fee, - } - } - - /// Basic helper to define a register interchain query message: - /// * **query** is a query type identifier ('tx' or 'kv' for now) with a payload: - /// - when the query enum is 'kv' then payload is the KV-storage keys for which we want to get - /// values from remote chain; - /// - when the query enum is 'tx' then payload is the filters for transaction search ICQ, - /// maximum allowed number of filters is 32. - /// * **connection_id** is an IBC connection identifier between Neutron and remote chain; - /// * **update_period** is used to say how often (in neutron blocks) the query must be updated. - pub fn register_interchain_query( - query: QueryPayload, - connection_id: String, - update_period: u64, - ) -> NeutronResult { - Ok(match query { - QueryPayload::KV(keys) => NeutronMsg::RegisterInterchainQuery { - query_type: QueryType::KV.into(), - keys, - transactions_filter: String::new(), - connection_id, - update_period, - }, - QueryPayload::TX(transactions_filters) => NeutronMsg::RegisterInterchainQuery { - query_type: QueryType::TX.into(), - keys: vec![], - transactions_filter: to_string(&transactions_filters) - .map_err(|e| StdError::generic_err(e.to_string()))?, - connection_id, - update_period, - }, - }) - } - - /// Basic helper to define a update interchain query message: - /// * **query_id** is ID of the query we want to update; - /// * **new_keys** is encoded keys to query; - /// * **new_update_period** is used to say how often (in neutron blocks) the query must be updated. - pub fn update_interchain_query( - query_id: u64, - new_keys: Option>, - new_update_period: Option, - new_transactions_filter: Option>, - ) -> NeutronResult { - Ok(NeutronMsg::UpdateInterchainQuery { - query_id, - new_keys, - new_update_period, - new_transactions_filter: match new_transactions_filter { - Some(filters) => { - Some(to_string(&filters).map_err(|e| StdError::generic_err(e.to_string()))?) - } - None => None, - }, - }) - } - - /// Basic helper to define a remove interchain query message: - /// * **query_id** is ID of the query we want to remove. - pub fn remove_interchain_query(query_id: u64) -> Self { - NeutronMsg::RemoveInterchainQuery { query_id } - } - - /// Basic helper to define a parameter change proposal passed to AdminModule: - /// * **proposal** is struct which contains proposal that should change network parameter. - pub fn submit_param_change_proposal(proposal: ParamChangeProposal) -> Self { - NeutronMsg::SubmitAdminProposal { - admin_proposal: AdminProposal::ParamChangeProposal(proposal), - } - } - - #[deprecated( - since = "0.11.0", - note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use submit_proposal_execute_message instead" - )] - /// Basic helper to define an ibc upgrade proposal passed to AdminModule: - /// * **proposal** is struct which contains proposal that upgrades network. - pub fn submit_upgrade_proposal(proposal: UpgradeProposal) -> Self { - NeutronMsg::SubmitAdminProposal { - admin_proposal: AdminProposal::UpgradeProposal(proposal), - } - } - - #[deprecated( - since = "0.11.0", - note = "Used only for querying old proposals. Will fail if executed in a new proposal. Use submit_proposal_execute_message instead" - )] - /// Basic helper to define an ibc update client change proposal passed to AdminModule: - /// * **proposal** is struct which contains proposal updates cliient. - pub fn submit_client_update_proposal(proposal: ClientUpdateProposal) -> Self { - NeutronMsg::SubmitAdminProposal { - admin_proposal: AdminProposal::ClientUpdateProposal(proposal), - } - } - - /// Basic helper to define sdk47 compatible proposal passed to AdminModule: - /// * **proposal** is struct which contains JSON encoded sdk message. - pub fn submit_proposal_execute_message(proposal: ProposalExecuteMessage) -> Self { - NeutronMsg::SubmitAdminProposal { - admin_proposal: AdminProposal::ProposalExecuteMessage(proposal), - } - } - - /// Basic helper to build create denom message passed to TokenFactory module: - /// * **subdenom** is a subdenom name for denom to be created. - pub fn submit_create_denom(subdenom: impl Into) -> Self { - NeutronMsg::CreateDenom { - subdenom: subdenom.into(), - } - } - - /// Basic helper to define change of admin for a token passed to TokenFactory module: - /// * **denom** is a name of the denom to change an admin for; - /// * **new_admin_address** is a new admin address for a denom. - pub fn submit_change_admin( - denom: impl Into, - new_admin_address: impl Into, - ) -> Self { - NeutronMsg::ChangeAdmin { - denom: denom.into(), - new_admin_address: new_admin_address.into(), - } - } - - /// Basic helper to define mint tokens passed to TokenFactory module: - /// * **denom** is a name of the denom; - /// * **amount** is an amount of tokens to mint; - /// * **mint_to_address** is an address that will receive minted tokens. - pub fn submit_mint_tokens( - denom: impl Into, - amount: Uint128, - mint_to_address: impl Into, - ) -> Self { - NeutronMsg::MintTokens { - denom: denom.into(), - amount, - mint_to_address: mint_to_address.into(), - } - } - - /// Basic helper to define burn tokens passed to TokenFactory module: - /// * **denom** is a name of the denom; - /// * **amount** is an amount of tokens to burn. - /// * **burn_from_address** is an address tokens will be burned from - pub fn submit_burn_tokens( - denom: impl Into, - amount: Uint128, - burn_from_address: Option, - ) -> Self { - NeutronMsg::BurnTokens { - denom: denom.into(), - amount, - burn_from_address: burn_from_address.unwrap_or_default(), - } - } - - /// Basic helper to create set before send hook message passed to TokenFactory module: - /// * **denom** is a name for denom for hook to be created. - pub fn submit_set_before_send_hook( - denom: impl Into, - contract_addr: impl Into, - ) -> Self { - NeutronMsg::SetBeforeSendHook { - denom: denom.into(), - contract_addr: contract_addr.into(), - } - } - - /// Basic helper to create force transfer message passed to TokenFactory module: - /// * **denom** is a name for a denom to transfer; - /// * **amount** is an amount of **denom** tokens to transfer; - /// * **from_address** is from which address to transfer tokens; - /// * **to_address** is where to transfer tokens. - pub fn submit_force_transfer( - denom: impl Into, - amount: Uint128, - from_address: impl Into, - to_address: impl Into, - ) -> Self { - NeutronMsg::ForceTransfer { - denom: denom.into(), - amount, - transfer_from_address: from_address.into(), - transfer_to_address: to_address.into(), - } - } - /// Basic helper to create a set denom metadata message passed to TokenFactory module: - /// * **description** description of a token; - /// * **denom_units** represents the list of DenomUnit's for a given coin; - /// * **base** represents the base denom (should be the DenomUnit with exponent = 0); - /// * **display** indicates the suggested denom that should be - /// displayed in clients; - /// * **name** defines the name of the token (eg: Cosmos Atom); - /// * **symbol** is the token symbol usually shown on exchanges (eg: ATOM). This can - /// be the same as the display; - /// * **uri** to a document (on or off-chain) that contains additional information. Optional; - /// * **uri_hash** is a sha256 hash of a document pointed by URI. It's used to verify that - /// the document didn't change. Optional. - #[allow(clippy::too_many_arguments)] - pub fn submit_set_denom_metadata( - description: String, - denom_units: Vec, - base: String, - display: String, - name: String, - symbol: String, - uri: String, - uri_hash: String, - ) -> Self { - NeutronMsg::SetDenomMetadata { - description, - denom_units, - base, - display, - name, - symbol, - uri, - uri_hash, - } - } - - /// Basic helper to define add schedule passed to Cron module: - /// * **name** is a name of the schedule; - /// * **period** is a period of schedule execution in blocks; - /// * **msgs** is the messages that will be executed. - /// * **execution_stage** is the stage where schedule will be executed. - pub fn submit_add_schedule( - name: String, - period: u64, - msgs: Vec, - execution_stage: ExecutionStage, - ) -> Self { - NeutronMsg::AddSchedule { - name, - period, - msgs, - execution_stage: execution_stage.as_str_name().to_string(), - } - } - - /// Basic helper to define remove schedule passed to Cron module: - /// * **name** is a name of the schedule to be removed. - pub fn submit_remove_schedule(name: String) -> Self { - NeutronMsg::RemoveSchedule { name } - } - - /// Basic helper to define resubmit failure passed to Contractmanager module: - /// * **failure_id** is an id of the failure to be resubmitted. - pub fn submit_resubmit_failure(failure_id: u64) -> Self { - NeutronMsg::ResubmitFailure { failure_id } - } } impl From for CosmosMsg { @@ -574,7 +101,7 @@ pub struct MsgRegisterInterchainAccountResponse { pub struct MsgSubmitTxResponse { /// **sequence_id** is a channel's sequence_id for outgoing ibc packet. Unique per a channel. pub sequence_id: u64, - /// **channel** is a src channel on neutron side trasaction was submitted from. + /// **channel** is a src channel on neutron side transaction was submitted from. pub channel: String, } diff --git a/packages/neutron-sdk/src/bindings/oracle/mod.rs b/packages/neutron-sdk/src/bindings/oracle/mod.rs deleted file mode 100644 index e44ca515..00000000 --- a/packages/neutron-sdk/src/bindings/oracle/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod query; -pub mod types; diff --git a/packages/neutron-sdk/src/bindings/oracle/query.rs b/packages/neutron-sdk/src/bindings/oracle/query.rs deleted file mode 100644 index 73d01683..00000000 --- a/packages/neutron-sdk/src/bindings/oracle/query.rs +++ /dev/null @@ -1,40 +0,0 @@ -use crate::bindings::oracle::types::{CurrencyPair, QuotePrice}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum OracleQuery { - GetAllCurrencyPairs {}, - GetPrice { currency_pair: CurrencyPair }, - GetPrices { currency_pair_ids: Vec }, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct GetPriceResponse { - /// **price** represents the quote-price for the CurrencyPair given in - /// GetPriceRequest (possibly nil if no update has been made) - pub price: QuotePrice, - /// **nonce** represents the nonce for the CurrencyPair if it exists in state - pub nonce: u64, - /// **decimals* represents the number of decimals that the quote-price is - /// represented in. For Pairs where ETHEREUM is the quote this will be 18, - /// otherwise it will be 8. - pub decimals: u64, - /// *id** represents the identifier for the CurrencyPair. - #[serde(default)] - pub id: u64, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct GetPricesResponse { - pub prices: Vec, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct GetAllCurrencyPairsResponse { - pub currency_pairs: Vec, -} diff --git a/packages/neutron-sdk/src/bindings/oracle/types.rs b/packages/neutron-sdk/src/bindings/oracle/types.rs deleted file mode 100644 index 6afde01f..00000000 --- a/packages/neutron-sdk/src/bindings/oracle/types.rs +++ /dev/null @@ -1,23 +0,0 @@ -use cosmwasm_std::Int128; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -pub struct CurrencyPair { - #[serde(rename(serialize = "Base", deserialize = "Base"))] - pub base: String, - #[serde(rename(serialize = "Quote", deserialize = "Quote"))] - pub quote: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct QuotePrice { - pub price: Int128, - /// **block_timestamp** tracks the block height associated with this price update. - /// We include block timestamp alongside the price to ensure that smart - /// contracts and applications are not utilizing stale oracle prices - pub block_timestamp: String, - /// **block_height** is height of block mentioned above - pub block_height: Option, -} diff --git a/packages/neutron-sdk/src/bindings/query.rs b/packages/neutron-sdk/src/bindings/query.rs deleted file mode 100644 index 94c36199..00000000 --- a/packages/neutron-sdk/src/bindings/query.rs +++ /dev/null @@ -1,171 +0,0 @@ -use crate::bindings::marketmap::query::MarketMapQuery; -use crate::bindings::oracle::query::OracleQuery; -use crate::bindings::types::{Failure, InterchainQueryResult, RegisteredQuery}; -use cosmwasm_std::{Binary, CustomQuery, QueryRequest}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -use super::dex::query::DexQuery; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -/// The queries to interact with neutron specific blockchain modules. -pub enum NeutronQuery { - /// Query a result of registered interchain query on remote chain - InterchainQueryResult { - /// **query_id** is an ID registered interchain query - query_id: u64, - }, - - /// Query a registered interchain account address for a specific connection_id - /// Every contract may have as many interchain accounts as necessary. - InterchainAccountAddress { - /// **owner_address** is an address of contract which registered interchain account - owner_address: String, - - /// **interchain_account_id** is an identifier of your interchain account. Can be any string - /// This identifier allows contracts to have multiple interchain accounts on remote chains - interchain_account_id: String, - - /// **connection_id** is an IBC connection identifier between Neutron and remote chain - connection_id: String, - }, - - /// Query all registered interchain queries on all remote chains - RegisteredInterchainQueries { - owners: Vec, - connection_id: String, - pagination: PageRequest, - }, - - /// Query registered interchain query with a specific query_id - RegisteredInterchainQuery { - /// **query_id** is an ID registered interchain query - query_id: u64, - }, - - /// Query total amount of burned neutron fees - TotalBurnedNeutronsAmount {}, - - /// Query minimum IBC fee - MinIbcFee {}, - - /// TokenFactory query. Given a subdenom minted by a contract via - /// [`NeutronMsg::MintTokens`](crate::bindings::msg::NeutronMsg::MintTokens), - /// returns the full denom as used by [`BankMsg::Send`](cosmwasm_std::BankMsg::Send). - FullDenom { - creator_addr: String, - subdenom: String, - }, - - /// TokenFactory query. Returns the admin of a denom, if the denom is a TokenFactory denom. - DenomAdmin { - subdenom: String, - }, - - /// TokenFactory query. Returns the before send hook address of a denom, if the denom is a TokenFactory denom. - BeforeSendHook { - denom: String, - }, - - /// Contractmanager query. Returns the failures for a particular contract address. - Failures { - address: String, - pagination: PageRequest, - }, - - Dex(DexQuery), - - MarketMap(MarketMapQuery), - - Oracle(OracleQuery), -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct PageRequest { - /// **key** is a value returned in PageResponse.next_key to begin - /// querying the next page most efficiently. Only one of offset or key - /// should be set. - pub key: Binary, - /// **offset** is a numeric offset that can be used when key is unavailable. - /// It is less efficient than using key. Only one of offset or key should - /// be set. - pub offset: u64, - /// **limit** is the total number of results to be returned in the result page. - /// If left empty it will default to a value to be set by each app. - pub limit: u64, - /// **count_total** is set to true to indicate that the result set should include - /// a count of the total number of items available for pagination in UIs. - /// count_total is only respected when offset is used. It is ignored when key - /// is set. - pub count_total: bool, - /// reverse is set to true if results are to be returned in the descending order. - pub reverse: bool, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct PageResponse { - /// **next_key** is the key to be passed to PageRequest.key to - /// query the next page most efficiently. It will be empty if - /// there are no more results. - pub next_key: Option, - /// **total** is total number of results available if PageRequest.count_total - /// was set, its value is undefined otherwise - pub total: Option, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct QueryRegisteredQueriesResponse { - /// **registered_queries** is a list of registered queries - pub registered_queries: Vec, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct QueryRegisteredQueryResponse { - /// **registered_query** is a registered query - pub registered_query: RegisteredQuery, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct QueryRegisteredQueryResultResponse { - pub result: InterchainQueryResult, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct QueryInterchainAccountAddressResponse { - /// **interchain_account_address** is a interchain account address on the remote chain - pub interchain_account_address: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct QueryFailuresResponse { - /// **failures** is a list of failures of sudo handler calls - pub failures: Vec, -} - -impl CustomQuery for NeutronQuery {} - -impl From for QueryRequest { - fn from(msg: DexQuery) -> Self { - QueryRequest::Custom(NeutronQuery::Dex(msg)) - } -} - -impl From for QueryRequest { - fn from(msg: MarketMapQuery) -> Self { - QueryRequest::Custom(NeutronQuery::MarketMap(msg)) - } -} - -impl From for QueryRequest { - fn from(msg: OracleQuery) -> Self { - QueryRequest::Custom(NeutronQuery::Oracle(msg)) - } -} diff --git a/packages/neutron-sdk/src/interchain_queries/mod.rs b/packages/neutron-sdk/src/interchain_queries/mod.rs index 507603ea..8495aa96 100644 --- a/packages/neutron-sdk/src/interchain_queries/mod.rs +++ b/packages/neutron-sdk/src/interchain_queries/mod.rs @@ -4,4 +4,4 @@ pub mod types; pub mod v045; pub mod v047; -pub use queries::{check_query_type, get_registered_query, query_kv_result}; +// pub use queries::{check_query_type, get_registered_query, query_kv_result}; diff --git a/packages/neutron-sdk/src/interchain_queries/queries.rs b/packages/neutron-sdk/src/interchain_queries/queries.rs index 399cea7a..d88d3594 100644 --- a/packages/neutron-sdk/src/interchain_queries/queries.rs +++ b/packages/neutron-sdk/src/interchain_queries/queries.rs @@ -1,55 +1,43 @@ -use crate::bindings::query::{ - NeutronQuery, QueryRegisteredQueryResponse, QueryRegisteredQueryResultResponse, -}; -use crate::errors::error::NeutronResult; -use crate::interchain_queries::types::{KVReconstruct, QueryType}; -use crate::NeutronError; -use cosmwasm_std::Deps; +// use crate::bindings::query::{ +// NeutronQuery, QueryRegisteredQueryResponse, QueryRegisteredQueryResultResponse, +// }; +// use crate::errors::error::NeutronResult; +// use crate::interchain_queries::types::{KVReconstruct, QueryType}; +// use crate::NeutronError; +// use cosmwasm_std::Deps; -/// Checks **actual** query type is **expected** query type -pub fn check_query_type(actual: QueryType, expected: QueryType) -> NeutronResult<()> { - if actual != expected { - return Err(NeutronError::InvalidQueryType { - query_type: actual.into(), - }); - } - Ok(()) -} - -/// Queries registered query info -pub fn get_registered_query( - deps: Deps, - interchain_query_id: u64, -) -> NeutronResult { - let query = NeutronQuery::RegisteredInterchainQuery { - query_id: interchain_query_id, - }; - - let res: QueryRegisteredQueryResponse = deps.querier.query(&query.into())?; - Ok(res) -} - -/// Reads submitted raw KV values for Interchain Query with **query_id** from the storage and reconstructs the result -pub fn query_kv_result( - deps: Deps, - query_id: u64, -) -> NeutronResult { - let registered_query_result = get_raw_interchain_query_result(deps, query_id)?; - - KVReconstruct::reconstruct(®istered_query_result.result.kv_results) -} - -/// Queries raw interchain query result (raw KV storage values or transactions) from Interchain Queries Module. -/// Usually it is better to implement [KVReconstruct] for your own type and then use [query_kv_result], -/// but in cases when Rust forbids to implement foreign trait [KVReconstruct] for some foreign type, -/// it is possible to use [get_raw_interchain_query_result] and reconstruct query result manually. -pub fn get_raw_interchain_query_result( - deps: Deps, - interchain_query_id: u64, -) -> NeutronResult { - let interchain_query = NeutronQuery::InterchainQueryResult { - query_id: interchain_query_id, - }; - let res = deps.querier.query(&interchain_query.into())?; - Ok(res) -} +// TODO: rewrite using neutron-std or just leave helper methods for KVReconstruct +// /// Checks **actual** query type is **expected** query type +// pub fn check_query_type(actual: QueryType, expected: QueryType) -> NeutronResult<()> { +// if actual != expected { +// return Err(NeutronError::InvalidQueryType { +// query_type: actual.into(), +// }); +// } +// Ok(()) +// } +// +// /// Reads submitted raw KV values for Interchain Query with **query_id** from the storage and reconstructs the result +// pub fn query_kv_result( +// deps: Deps, +// query_id: u64, +// ) -> NeutronResult { +// let registered_query_result = get_raw_interchain_query_result(deps, query_id)?; +// +// KVReconstruct::reconstruct(®istered_query_result.result.kv_results) +// } +// +// /// Queries raw interchain query result (raw KV storage values or transactions) from Interchain Queries Module. +// /// Usually it is better to implement [KVReconstruct] for your own type and then use [query_kv_result], +// /// but in cases when Rust forbids to implement foreign trait [KVReconstruct] for some foreign type, +// /// it is possible to use [get_raw_interchain_query_result] and reconstruct query result manually. +// pub fn get_raw_interchain_query_result( +// deps: Deps, +// interchain_query_id: u64, +// ) -> NeutronResult { +// let interchain_query = NeutronQuery::InterchainQueryResult { +// query_id: interchain_query_id, +// }; +// let res = deps.querier.query(&interchain_query.into())?; +// Ok(res) +// } diff --git a/packages/neutron-sdk/src/interchain_queries/v045/mod.rs b/packages/neutron-sdk/src/interchain_queries/v045/mod.rs index 4dfdbe4c..3eb4bb34 100644 --- a/packages/neutron-sdk/src/interchain_queries/v045/mod.rs +++ b/packages/neutron-sdk/src/interchain_queries/v045/mod.rs @@ -1,16 +1,6 @@ pub mod helpers; pub mod queries; -pub mod register_queries; pub mod types; -#[allow(deprecated)] -pub use register_queries::{ - new_register_balance_query_msg, new_register_balances_query_msg, - new_register_bank_total_supply_query_msg, new_register_delegator_delegations_query_msg, - new_register_delegator_unbonding_delegations_query_msg, - new_register_distribution_fee_pool_query_msg, new_register_gov_proposals_query_msg, - new_register_staking_validators_query_msg, new_register_transfers_query_msg, -}; - #[cfg(test)] mod testing; diff --git a/packages/neutron-sdk/src/interchain_queries/v045/queries.rs b/packages/neutron-sdk/src/interchain_queries/v045/queries.rs index ce17573c..2496fcb5 100644 --- a/packages/neutron-sdk/src/interchain_queries/v045/queries.rs +++ b/packages/neutron-sdk/src/interchain_queries/v045/queries.rs @@ -1,267 +1,267 @@ -use crate::{ - bindings::query::NeutronQuery, - interchain_queries::{ - queries::{check_query_type, get_registered_query, query_kv_result}, - types::QueryType, - v045::types::{ - Balances, Delegations, FeePool, GovernmentProposal, GovernmentProposalVotes, - SigningInfo, StakingValidator, StdDelegation, TotalSupply, UnbondingDelegations, - }, - }, - NeutronResult, -}; -use cosmwasm_std::{Deps, Env}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct BalanceResponse { - pub balances: Balances, - pub last_submitted_local_height: u64, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct TotalSupplyResponse { - pub supply: TotalSupply, - pub last_submitted_local_height: u64, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct FeePoolResponse { - pub pool: FeePool, - pub last_submitted_local_height: u64, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct ValidatorResponse { - pub validator: StakingValidator, - pub last_submitted_local_height: u64, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct ValidatorSigningInfoResponse { - pub signing_infos: SigningInfo, - pub last_submitted_local_height: u64, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct ProposalResponse { - pub proposals: GovernmentProposal, - pub last_submitted_local_height: u64, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct ProposalVotesResponse { - pub votes: GovernmentProposalVotes, - pub last_submitted_local_height: u64, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct DelegatorDelegationsResponse { - pub delegations: Vec, - pub last_submitted_local_height: u64, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct DelegatorUnbondingDelegationsResponse { - pub unbonding_delegations: UnbondingDelegations, - pub last_submitted_local_height: u64, -} - -/// Returns balance of account on remote chain for particular denom -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_balance( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let balances: Balances = query_kv_result(deps, registered_query_id)?; - - Ok(BalanceResponse { - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - balances, - }) -} - -/// Returns bank total supply on remote chain for particular denom -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_bank_total( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let total_supply: TotalSupply = query_kv_result(deps, registered_query_id)?; - - Ok(TotalSupplyResponse { - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - supply: total_supply, - }) -} - -/// Returns distribution fee pool on remote chain -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_distribution_fee_pool( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let fee_pool: FeePool = query_kv_result(deps, registered_query_id)?; - - Ok(FeePoolResponse { - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - pool: fee_pool, - }) -} - -/// Returns staking validator from remote chain -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_staking_validators( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let validator: StakingValidator = query_kv_result(deps, registered_query_id)?; - - Ok(ValidatorResponse { - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - validator, - }) -} - -/// Returns validators signing infos from remote chain -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_validators_signing_infos( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let signing_infos: SigningInfo = query_kv_result(deps, registered_query_id)?; - - Ok(ValidatorSigningInfoResponse { - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - signing_infos, - }) -} - -/// Returns list of government proposals on the remote chain -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_government_proposals( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let proposals: GovernmentProposal = query_kv_result(deps, registered_query_id)?; - - Ok(ProposalResponse { - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - proposals, - }) -} - -/// Returns list of government proposal votes on the remote chain -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_government_proposal_votes( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let votes: GovernmentProposalVotes = query_kv_result(deps, registered_query_id)?; - - Ok(ProposalVotesResponse { - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - votes, - }) -} - -/// Returns delegations of particular delegator on remote chain -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_delegations( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let delegations: Delegations = query_kv_result(deps, registered_query_id)?; - - Ok(DelegatorDelegationsResponse { - delegations: delegations.delegations, - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - }) -} - -/// Returns list of unbonding delegations of particular delegator on remote chain -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_unbonding_delegations( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let unbonding_delegations: UnbondingDelegations = query_kv_result(deps, registered_query_id)?; - - Ok(DelegatorUnbondingDelegationsResponse { - unbonding_delegations, - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - }) -} +// use crate::{ +// bindings::query::NeutronQuery, +// interchain_queries::{ +// queries::{check_query_type, get_registered_query, query_kv_result}, +// types::QueryType, +// v045::types::{ +// Balances, Delegations, FeePool, GovernmentProposal, GovernmentProposalVotes, +// SigningInfo, StakingValidator, StdDelegation, TotalSupply, UnbondingDelegations, +// }, +// }, +// NeutronResult, +// }; +// use cosmwasm_std::{Deps, Env}; +// use schemars::JsonSchema; +// use serde::{Deserialize, Serialize}; +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct BalanceResponse { +// pub balances: Balances, +// pub last_submitted_local_height: u64, +// } +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct TotalSupplyResponse { +// pub supply: TotalSupply, +// pub last_submitted_local_height: u64, +// } +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct FeePoolResponse { +// pub pool: FeePool, +// pub last_submitted_local_height: u64, +// } +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct ValidatorResponse { +// pub validator: StakingValidator, +// pub last_submitted_local_height: u64, +// } +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct ValidatorSigningInfoResponse { +// pub signing_infos: SigningInfo, +// pub last_submitted_local_height: u64, +// } +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct ProposalResponse { +// pub proposals: GovernmentProposal, +// pub last_submitted_local_height: u64, +// } +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct ProposalVotesResponse { +// pub votes: GovernmentProposalVotes, +// pub last_submitted_local_height: u64, +// } +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct DelegatorDelegationsResponse { +// pub delegations: Vec, +// pub last_submitted_local_height: u64, +// } +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct DelegatorUnbondingDelegationsResponse { +// pub unbonding_delegations: UnbondingDelegations, +// pub last_submitted_local_height: u64, +// } +// +// /// Returns balance of account on remote chain for particular denom +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_balance( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let balances: Balances = query_kv_result(deps, registered_query_id)?; +// +// Ok(BalanceResponse { +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// balances, +// }) +// } +// +// /// Returns bank total supply on remote chain for particular denom +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_bank_total( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let total_supply: TotalSupply = query_kv_result(deps, registered_query_id)?; +// +// Ok(TotalSupplyResponse { +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// supply: total_supply, +// }) +// } +// +// /// Returns distribution fee pool on remote chain +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_distribution_fee_pool( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let fee_pool: FeePool = query_kv_result(deps, registered_query_id)?; +// +// Ok(FeePoolResponse { +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// pool: fee_pool, +// }) +// } +// +// /// Returns staking validator from remote chain +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_staking_validators( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let validator: StakingValidator = query_kv_result(deps, registered_query_id)?; +// +// Ok(ValidatorResponse { +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// validator, +// }) +// } +// +// /// Returns validators signing infos from remote chain +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_validators_signing_infos( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let signing_infos: SigningInfo = query_kv_result(deps, registered_query_id)?; +// +// Ok(ValidatorSigningInfoResponse { +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// signing_infos, +// }) +// } +// +// /// Returns list of government proposals on the remote chain +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_government_proposals( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let proposals: GovernmentProposal = query_kv_result(deps, registered_query_id)?; +// +// Ok(ProposalResponse { +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// proposals, +// }) +// } +// +// /// Returns list of government proposal votes on the remote chain +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_government_proposal_votes( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let votes: GovernmentProposalVotes = query_kv_result(deps, registered_query_id)?; +// +// Ok(ProposalVotesResponse { +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// votes, +// }) +// } +// +// /// Returns delegations of particular delegator on remote chain +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_delegations( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let delegations: Delegations = query_kv_result(deps, registered_query_id)?; +// +// Ok(DelegatorDelegationsResponse { +// delegations: delegations.delegations, +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// }) +// } +// +// /// Returns list of unbonding delegations of particular delegator on remote chain +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_unbonding_delegations( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let unbonding_delegations: UnbondingDelegations = query_kv_result(deps, registered_query_id)?; +// +// Ok(DelegatorUnbondingDelegationsResponse { +// unbonding_delegations, +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// }) +// } diff --git a/packages/neutron-sdk/src/interchain_queries/v045/register_queries.rs b/packages/neutron-sdk/src/interchain_queries/v045/register_queries.rs deleted file mode 100644 index d379e5a8..00000000 --- a/packages/neutron-sdk/src/interchain_queries/v045/register_queries.rs +++ /dev/null @@ -1,354 +0,0 @@ -use crate::interchain_queries::types::{ - QueryPayload, TransactionFilterItem, TransactionFilterOp, TransactionFilterValue, -}; -use crate::interchain_queries::v045::types::{ - BANK_STORE_KEY, DISTRIBUTION_STORE_KEY, HEIGHT_FIELD, KEY_BOND_DENOM, PARAMS_STORE_KEY, - RECIPIENT_FIELD, SLASHING_STORE_KEY, STAKING_STORE_KEY, WASM_STORE_KEY, -}; -use crate::{ - bindings::{msg::NeutronMsg, types::KVKey}, - errors::error::NeutronResult, - interchain_queries::helpers::decode_and_convert, - interchain_queries::v045::helpers::{ - create_balances_query_keys, create_delegation_key, create_fee_pool_key, - create_gov_proposal_keys, create_gov_proposals_voters_votes_keys, create_params_store_key, - create_total_denom_key, create_unbonding_delegation_key, create_validator_key, - create_validator_signing_info_key, create_wasm_contract_store_key, - }, -}; -use cosmwasm_std::Binary; - -/// Creates a message to register an Interchain Query to get balance of account on remote chain for list of denoms -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **addr** address of an account on remote chain for which you want to get balances; -/// * **denoms** denominations of the coins for which you want to get balance; -/// * **update_period** is used to say how often the query must be updated. -pub fn new_register_balances_query_msg( - connection_id: String, - addr: String, - denoms: Vec, - update_period: u64, -) -> NeutronResult { - let kv_keys = create_balances_query_keys(addr, denoms)?; - NeutronMsg::register_interchain_query(QueryPayload::KV(kv_keys), connection_id, update_period) -} - -/// Creates a message to register an Interchain Query to get balance of account on remote chain for a particular denom -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **addr** address of an account on remote chain for which you want to get balances; -/// * **denom** denomination of the coin for which you want to get balance; -/// * **update_period** is used to say how often the query must be updated. -#[deprecated(note = "Please use new_register_balances_query_msg instead")] -pub fn new_register_balance_query_msg( - connection_id: String, - addr: String, - denom: String, - update_period: u64, -) -> NeutronResult { - new_register_balances_query_msg(connection_id, addr, vec![denom], update_period) -} - -/// Creates a message to register an Interchain Query to get total supply on remote chain for particular denom -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **denom** denomination of the coin for which you want to get total supply; -/// * **update_period** is used to say how often the query must be updated. -pub fn new_register_bank_total_supply_query_msg( - connection_id: String, - denoms: Vec, - update_period: u64, -) -> NeutronResult { - let mut kv_keys: Vec = Vec::with_capacity(denoms.len()); - - for denom in denoms { - let supply_key = create_total_denom_key(denom)?; - - let kv_key = KVKey { - path: BANK_STORE_KEY.to_string(), - key: Binary::new(supply_key), - }; - - kv_keys.push(kv_key) - } - - NeutronMsg::register_interchain_query(QueryPayload::KV(kv_keys), connection_id, update_period) -} - -/// Creates a message to register an Interchain Query to get fee pool on remote chain from distribution module -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **update_period** is used to say how often the query must be updated. -pub fn new_register_distribution_fee_pool_query_msg( - connection_id: String, - update_period: u64, -) -> NeutronResult { - let kv_key = KVKey { - path: DISTRIBUTION_STORE_KEY.to_string(), - key: Binary::new(create_fee_pool_key()?), - }; - - NeutronMsg::register_interchain_query( - QueryPayload::KV(vec![kv_key]), - connection_id, - update_period, - ) -} - -/// Creates a message to register an Interchain Query to get governance proposals on remote chain -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **proposals_ids** is a list of proposals ids from remote chain. -/// * **update_period** is used to say how often the query must be updated. -pub fn new_register_gov_proposals_query_msg( - connection_id: String, - proposals_ids: Vec, - update_period: u64, -) -> NeutronResult { - let kv_keys = create_gov_proposal_keys(proposals_ids)?; - - NeutronMsg::register_interchain_query(QueryPayload::KV(kv_keys), connection_id, update_period) -} - -/// Creates a message to update an Interchain Query to get governance proposals on remote chain -/// -/// * **query_id** is an IBC connection identifier between Neutron and remote chain; -/// * **proposals_ids** is a list of proposals ids from remote chain. -/// * **new_update_period** is used to update period of how often the query must be updated. -pub fn update_gov_proposals_query_msg( - query_id: u64, - proposals_ids: Vec, - new_update_period: Option, -) -> NeutronResult { - let kv_keys = create_gov_proposal_keys(proposals_ids)?; - - NeutronMsg::update_interchain_query(query_id, Some(kv_keys), new_update_period, None) -} - -/// Creates a message to register an Interchain Query to get governance proposals votes on the remote chain -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **proposals_ids** is a list of proposals ids from remote chain. -/// * **voters** is a list of voter to get voting info from remote chain. -/// * **update_period** is used to say how often the query must be updated. -pub fn new_register_gov_proposals_voters_votes_query_msg( - connection_id: String, - proposals_ids: Vec, - voters: Vec, - update_period: u64, -) -> NeutronResult { - let kv_keys = create_gov_proposals_voters_votes_keys(proposals_ids, voters)?; - - NeutronMsg::register_interchain_query(QueryPayload::KV(kv_keys), connection_id, update_period) -} - -/// Creates a message to update an Interchain Query to get governance proposals votes on the remote chain -/// -/// * **query_id** is an IBC connection identifier between Neutron and remote chain; -/// * **proposals_ids** is a list of proposals ids from remote chain. -/// * **voters** is a list of voter to get voting info from remote chain. -/// * **new_update_period** is used to update period of how often the query must be updated. -pub fn update_gov_proposals_votes_query_msg( - query_id: u64, - proposals_ids: Vec, - voters: Vec, - new_update_period: Option, -) -> NeutronResult { - let kv_keys = create_gov_proposals_voters_votes_keys(proposals_ids, voters)?; - - NeutronMsg::update_interchain_query(query_id, Some(kv_keys), new_update_period, None) -} - -/// Creates a message to register an Interchain Query to get validator info on remote chain -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **validator** is an validator operator address of an account on remote chain for which you want to get rewards ; -/// * **update_period** is used to say how often the query must be updated. -pub fn new_register_staking_validators_query_msg( - connection_id: String, - validators: Vec, - update_period: u64, -) -> NeutronResult { - let mut kv_keys: Vec = Vec::with_capacity(validators.len()); - - for validator in validators { - let val_addr = decode_and_convert(&validator)?; - - let kv_key = KVKey { - path: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_validator_key(&val_addr)?), - }; - - kv_keys.push(kv_key) - } - - NeutronMsg::register_interchain_query(QueryPayload::KV(kv_keys), connection_id, update_period) -} - -/// Creates a message to register an Interchain Query to get validators signing infos on remote chain -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **validators** is an list of validators valcons addresses of an account on remote chain for which you want to get rewards ; -/// * **update_period** is used to say how often the query must be updated. -pub fn new_register_validators_signing_infos_query_msg( - connection_id: String, - validators: Vec, - update_period: u64, -) -> NeutronResult { - let mut kv_keys: Vec = Vec::with_capacity(validators.len()); - - for validator in validators { - let valcons_addr = decode_and_convert(&validator)?; - - let kv_key = KVKey { - path: SLASHING_STORE_KEY.to_string(), - key: Binary::new(create_validator_signing_info_key(&valcons_addr)?), - }; - - kv_keys.push(kv_key) - } - - NeutronMsg::register_interchain_query(QueryPayload::KV(kv_keys), connection_id, update_period) -} - -/// Creates a message to register an Interchain Query to get delegations of particular delegator on remote chain. -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **delegator** is an address of an account on remote chain for which you want to get list of delegations; -/// * **validators** is a list of validators addresses for which you want to get delegations from particular **delegator**; -/// * **update_period** is used to say how often the query must be updated. -pub fn new_register_delegator_delegations_query_msg( - connection_id: String, - delegator: String, - validators: Vec, - update_period: u64, -) -> NeutronResult { - let delegator_addr = decode_and_convert(&delegator)?; - - // Allocate memory for such KV keys as: - // * staking module params to get staking denomination - // * validators structures to calculate amount of delegated tokens - // * delegations structures to get info about delegations itself - let mut keys: Vec = Vec::with_capacity(validators.len() * 2 + 1); - - // create KV key to get BondDenom from staking module params - keys.push(KVKey { - path: PARAMS_STORE_KEY.to_string(), - key: Binary::new(create_params_store_key(STAKING_STORE_KEY, KEY_BOND_DENOM)), - }); - - for v in validators { - let val_addr = decode_and_convert(&v)?; - - // create delegation key to get delegation structure - keys.push(KVKey { - path: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_delegation_key(&delegator_addr, &val_addr)?), - }); - - // create validator key to get validator structure - keys.push(KVKey { - path: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_validator_key(&val_addr)?), - }) - } - - NeutronMsg::register_interchain_query(QueryPayload::KV(keys), connection_id, update_period) -} - -/// Creates a message to register an Interchain Query to get unbonding delegations of particular delegator on remote chain. -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **delegator** is an address of an account on remote chain for which you want to get list of unbonding delegations; -/// * **validators** is a list of validators addresses for which you want to get unbonding delegations from particular **delegator**; -/// * **update_period** is used to say how often the query must be updated. -pub fn new_register_delegator_unbonding_delegations_query_msg( - connection_id: String, - delegator: String, - validators: Vec, - update_period: u64, -) -> NeutronResult { - let delegator_addr = decode_and_convert(&delegator)?; - - // Allocate memory, one KV key per validator - let mut keys: Vec = Vec::with_capacity(validators.len()); - - for v in validators { - let val_addr = decode_and_convert(&v)?; - - // create unbonding delegation key to get unbonding delegation structure - keys.push(KVKey { - path: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_unbonding_delegation_key(&delegator_addr, &val_addr)?), - }) - } - - NeutronMsg::register_interchain_query(QueryPayload::KV(keys), connection_id, update_period) -} - -/// Creates a message to register an Interchain Query to get wasm contract store on remote chain -/// from **wasm** module -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **contract_address** is an address of a contract on a remote chain; -/// * **key** is a wasm contract store key; -/// * **update_period** is used to say how often the query must be updated. -/// -/// Obtaining a **key** might not be a trivial task. One could list all contract's storage keys -/// using `$CHAIN_BIN query wasm contract-state all $CONTRACT_ADDRESS --output json | jq`. -/// The listed keys will be in format of plain hexadecimal string which is hard to understand -/// just by looking it. One could pipe this string into `| xxd -r -p | hexdump -C` and examine -/// its contents. -pub fn new_register_wasm_contract_store_query_msg( - connection_id: String, - contract_address: String, - key: impl AsRef<[u8]>, - update_period: u64, -) -> NeutronResult { - let converted_addr_bytes = decode_and_convert(contract_address.as_str())?; - let wasm_key = create_wasm_contract_store_key(converted_addr_bytes, key.as_ref())?; - - let kv_key = KVKey { - path: WASM_STORE_KEY.to_string(), - key: Binary::new(wasm_key), - }; - - NeutronMsg::register_interchain_query( - QueryPayload::KV(vec![kv_key]), - connection_id, - update_period, - ) -} - -/// Creates a message to register an Interchain Query to get transfer events to a recipient on a remote chain. -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **recipient** is an address of an account on remote chain for which you want to get list of transfer transactions; -/// * **update_period** is used to say how often the query must be updated. -/// * **min_height** is used to set min height for query (by default = 0). -pub fn new_register_transfers_query_msg( - connection_id: String, - recipient: String, - update_period: u64, - min_height: Option, -) -> NeutronResult { - let mut query_data = vec![TransactionFilterItem { - field: RECIPIENT_FIELD.to_string(), - op: TransactionFilterOp::Eq, - value: TransactionFilterValue::String(recipient), - }]; - if let Some(min_height) = min_height { - query_data.push(TransactionFilterItem { - field: HEIGHT_FIELD.to_string(), - op: TransactionFilterOp::Gte, - value: TransactionFilterValue::Int(min_height), - }) - } - - NeutronMsg::register_interchain_query( - QueryPayload::TX(query_data), - connection_id, - update_period, - ) -} diff --git a/packages/neutron-sdk/src/interchain_queries/v047/mod.rs b/packages/neutron-sdk/src/interchain_queries/v047/mod.rs index c897bd7f..d764fefd 100644 --- a/packages/neutron-sdk/src/interchain_queries/v047/mod.rs +++ b/packages/neutron-sdk/src/interchain_queries/v047/mod.rs @@ -1,10 +1,10 @@ -// import all unchanged helpers and methods from v045 package -// to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual -pub use crate::interchain_queries::v045::helpers; - -pub mod queries; -pub mod types; - -pub mod register_queries; -#[cfg(test)] -mod testing; +// // import all unchanged helpers and methods from v045 package +// // to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual +// pub use crate::interchain_queries::v045::helpers; +// +// pub mod queries; +// pub mod types; +// +// pub mod register_queries; +// #[cfg(test)] +// mod testing; diff --git a/packages/neutron-sdk/src/interchain_queries/v047/queries.rs b/packages/neutron-sdk/src/interchain_queries/v047/queries.rs index 8bc2000b..280c0ea8 100644 --- a/packages/neutron-sdk/src/interchain_queries/v047/queries.rs +++ b/packages/neutron-sdk/src/interchain_queries/v047/queries.rs @@ -1,76 +1,76 @@ -// import all queries from v045 package -// to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual -pub use crate::interchain_queries::v045::queries::*; - -// But at the same time we redefine some methods from v045 with methods below to create methods -// compatible with Cosmos SDK 0.47 - -use crate::interchain_queries::v047::types::Delegations; -use crate::{ - bindings::query::NeutronQuery, - interchain_queries::{ - queries::{check_query_type, get_registered_query, query_kv_result}, - types::QueryType, - v047::types::{Balances, StdDelegation}, - }, - NeutronResult, -}; -use cosmwasm_std::{Deps, Env}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct BalanceResponse { - pub balances: Balances, - pub last_submitted_local_height: u64, -} - -/// Returns balance of account on remote chain for particular denom -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_balance( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let balances: Balances = query_kv_result(deps, registered_query_id)?; - - Ok(BalanceResponse { - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - balances, - }) -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct DelegatorDelegationsResponse { - pub delegations: Vec, - pub last_submitted_local_height: u64, -} - -/// Returns delegations of particular delegator on remote chain -/// * ***registered_query_id*** is an identifier of the corresponding registered interchain query -pub fn query_delegations( - deps: Deps, - _env: Env, - registered_query_id: u64, -) -> NeutronResult { - let registered_query = get_registered_query(deps, registered_query_id)?; - - check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; - - let delegations: Delegations = query_kv_result(deps, registered_query_id)?; - - Ok(DelegatorDelegationsResponse { - delegations: delegations.delegations, - last_submitted_local_height: registered_query - .registered_query - .last_submitted_result_local_height, - }) -} +// // import all queries from v045 package +// // to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual +// pub use crate::interchain_queries::v045::queries::*; +// +// // But at the same time we redefine some methods from v045 with methods below to create methods +// // compatible with Cosmos SDK 0.47 +// +// use crate::interchain_queries::v047::types::Delegations; +// use crate::{ +// bindings::query::NeutronQuery, +// interchain_queries::{ +// queries::{check_query_type, get_registered_query, query_kv_result}, +// types::QueryType, +// v047::types::{Balances, StdDelegation}, +// }, +// NeutronResult, +// }; +// use cosmwasm_std::{Deps, Env}; +// use schemars::JsonSchema; +// use serde::{Deserialize, Serialize}; +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct BalanceResponse { +// pub balances: Balances, +// pub last_submitted_local_height: u64, +// } +// +// /// Returns balance of account on remote chain for particular denom +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_balance( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let balances: Balances = query_kv_result(deps, registered_query_id)?; +// +// Ok(BalanceResponse { +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// balances, +// }) +// } +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// #[serde(rename_all = "snake_case")] +// pub struct DelegatorDelegationsResponse { +// pub delegations: Vec, +// pub last_submitted_local_height: u64, +// } +// +// /// Returns delegations of particular delegator on remote chain +// /// * ***registered_query_id*** is an identifier of the corresponding registered interchain query +// pub fn query_delegations( +// deps: Deps, +// _env: Env, +// registered_query_id: u64, +// ) -> NeutronResult { +// let registered_query = get_registered_query(deps, registered_query_id)?; +// +// check_query_type(registered_query.registered_query.query_type, QueryType::KV)?; +// +// let delegations: Delegations = query_kv_result(deps, registered_query_id)?; +// +// Ok(DelegatorDelegationsResponse { +// delegations: delegations.delegations, +// last_submitted_local_height: registered_query +// .registered_query +// .last_submitted_result_local_height, +// }) +// } diff --git a/packages/neutron-sdk/src/interchain_queries/v047/register_queries.rs b/packages/neutron-sdk/src/interchain_queries/v047/register_queries.rs index 547ba091..322ce09b 100644 --- a/packages/neutron-sdk/src/interchain_queries/v047/register_queries.rs +++ b/packages/neutron-sdk/src/interchain_queries/v047/register_queries.rs @@ -1,58 +1,58 @@ -// import all helpers from v045 package -// to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual -pub use crate::interchain_queries::v045::register_queries::*; - -use crate::bindings::msg::NeutronMsg; -use crate::bindings::types::KVKey; -use crate::interchain_queries::helpers::decode_and_convert; -use crate::interchain_queries::types::QueryPayload; -use crate::interchain_queries::v045::helpers::{create_delegation_key, create_validator_key}; -use crate::interchain_queries::v045::types::STAKING_STORE_KEY; -use crate::interchain_queries::v047::types::STAKING_PARAMS_KEY; -use crate::NeutronResult; -use cosmwasm_std::Binary; - -/// Creates a message to register an Interchain Query to get delegations of particular delegator on remote chain. -/// -/// * **connection_id** is an IBC connection identifier between Neutron and remote chain; -/// * **delegator** is an address of an account on remote chain for which you want to get list of delegations; -/// * **validators** is a list of validators addresses for which you want to get delegations from particular **delegator**; -/// * **update_period** is used to say how often the query must be updated. -pub fn new_register_delegator_delegations_query_msg( - connection_id: String, - delegator: String, - validators: Vec, - update_period: u64, -) -> NeutronResult { - let delegator_addr = decode_and_convert(&delegator)?; - - // Allocate memory for such KV keys as: - // * staking module params to get staking denomination - // * validators structures to calculate amount of delegated tokens - // * delegations structures to get info about delegations itself - let mut keys: Vec = Vec::with_capacity(validators.len() * 2 + 1); - - // create KV key to get Staking Params from staking module - keys.push(KVKey { - path: STAKING_STORE_KEY.to_string(), - key: Binary::new(vec![STAKING_PARAMS_KEY]), - }); - - for v in validators { - let val_addr = decode_and_convert(&v)?; - - // create delegation key to get delegation structure - keys.push(KVKey { - path: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_delegation_key(&delegator_addr, &val_addr)?), - }); - - // create validator key to get validator structure - keys.push(KVKey { - path: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_validator_key(&val_addr)?), - }) - } - - NeutronMsg::register_interchain_query(QueryPayload::KV(keys), connection_id, update_period) -} +// // import all helpers from v045 package +// // to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual +// pub use crate::interchain_queries::v045::register_queries::*; +// +// use crate::bindings::msg::NeutronMsg; +// use crate::bindings::types::KVKey; +// use crate::interchain_queries::helpers::decode_and_convert; +// use crate::interchain_queries::types::QueryPayload; +// use crate::interchain_queries::v045::helpers::{create_delegation_key, create_validator_key}; +// use crate::interchain_queries::v045::types::STAKING_STORE_KEY; +// use crate::interchain_queries::v047::types::STAKING_PARAMS_KEY; +// use crate::NeutronResult; +// use cosmwasm_std::Binary; +// +// /// Creates a message to register an Interchain Query to get delegations of particular delegator on remote chain. +// /// +// /// * **connection_id** is an IBC connection identifier between Neutron and remote chain; +// /// * **delegator** is an address of an account on remote chain for which you want to get list of delegations; +// /// * **validators** is a list of validators addresses for which you want to get delegations from particular **delegator**; +// /// * **update_period** is used to say how often the query must be updated. +// pub fn new_register_delegator_delegations_query_msg( +// connection_id: String, +// delegator: String, +// validators: Vec, +// update_period: u64, +// ) -> NeutronResult { +// let delegator_addr = decode_and_convert(&delegator)?; +// +// // Allocate memory for such KV keys as: +// // * staking module params to get staking denomination +// // * validators structures to calculate amount of delegated tokens +// // * delegations structures to get info about delegations itself +// let mut keys: Vec = Vec::with_capacity(validators.len() * 2 + 1); +// +// // create KV key to get Staking Params from staking module +// keys.push(KVKey { +// path: STAKING_STORE_KEY.to_string(), +// key: Binary::new(vec![STAKING_PARAMS_KEY]), +// }); +// +// for v in validators { +// let val_addr = decode_and_convert(&v)?; +// +// // create delegation key to get delegation structure +// keys.push(KVKey { +// path: STAKING_STORE_KEY.to_string(), +// key: Binary::new(create_delegation_key(&delegator_addr, &val_addr)?), +// }); +// +// // create validator key to get validator structure +// keys.push(KVKey { +// path: STAKING_STORE_KEY.to_string(), +// key: Binary::new(create_validator_key(&val_addr)?), +// }) +// } +// +// NeutronMsg::register_interchain_query(QueryPayload::KV(keys), connection_id, update_period) +// } diff --git a/packages/neutron-sdk/src/interchain_queries/v047/testing.rs b/packages/neutron-sdk/src/interchain_queries/v047/testing.rs index 5dec56c1..ba97a2d2 100644 --- a/packages/neutron-sdk/src/interchain_queries/v047/testing.rs +++ b/packages/neutron-sdk/src/interchain_queries/v047/testing.rs @@ -1,1324 +1,1324 @@ -use crate::bindings::types::StorageValue; -use crate::interchain_queries::helpers::decode_and_convert; -use crate::interchain_queries::types::KVReconstruct; -use crate::interchain_queries::v045::helpers::create_params_store_key; -use crate::interchain_queries::v045::types::KEY_BOND_DENOM; -use crate::interchain_queries::v047::helpers::{ - create_account_denom_balance_key, create_delegation_key, create_fee_pool_key, - create_gov_proposal_key, create_total_denom_key, create_validator_key, - create_validator_signing_info_key, -}; -use crate::interchain_queries::v047::types::{ - Balances, Delegations, FeePool, GovernmentProposal, Proposal, SigningInfo, StakingValidator, - StdDelegation, TallyResult, TotalSupply, UnbondingDelegations, UnbondingEntry, - UnbondingResponse, Validator as ContractValidator, ValidatorSigningInfo, DECIMAL_PLACES, - STAKING_PARAMS_KEY, STAKING_STORE_KEY, -}; -use crate::{NeutronError, NeutronResult}; -use base64::prelude::*; -use base64::Engine; -use cosmos_sdk_proto::cosmos::base::v1beta1::{Coin, DecCoin}; -use cosmos_sdk_proto::cosmos::distribution::v1beta1::FeePool as CosmosFeePool; -use cosmos_sdk_proto::cosmos::gov::v1beta1::{ - Proposal as CosmosProposal, TallyResult as CosmosTallyResult, -}; -use cosmos_sdk_proto::cosmos::slashing::v1beta1::ValidatorSigningInfo as CosmosValidatorSigningInfo; -use cosmos_sdk_proto::cosmos::staking::v1beta1::{ - Commission, CommissionRates, Delegation, Description, Params, Validator, -}; -use cosmos_sdk_proto::traits::Message; -use cosmwasm_std::{Addr, Binary, Coin as StdCoin, Decimal, Timestamp, Uint128}; -use hex; -use std::ops::Mul; -use std::str::FromStr; - -// raw hex data from KV storage created using https://github.com/neutron-org/icq-compliance-officer. -pub const BALANCES_HEX_RESPONSE: &str = "343934323133353631"; -pub const TOTAL_SUPPLY_HEX_RESPONSE: &str = "31363434313731393838393035373639"; -pub const FEE_POOL_HEX_RESPONSE: &str = - "0a630a446962632f31324441343233303445453143453936303731463731324141344435383138364144313143333136354330444344413731453031374135344633393335453636121b3434343235323231373030303030303030303030303030303030300a630a446962632f31344639424333453434423841394331424531464230383938304641423837303334433939303545463137434632463530303846433038353231383831314343121b3138393735333433323030303030303030303030303030303030300a620a446962632f31464244443538443433384234443034443236434246423245373232433138393834413046314135323436384334463432463337443130324633443346333939121a32353435353334383030303030303030303030303030303030300a620a446962632f32313831414142303231384541433234424339463836424431333634464242464133453645334643433235453838453345363843313544433645373532443836121a38393736343437323030303030303030303030303030303030300a5e0a446962632f323731373130394139353535394633413137454643304338393742373639314532324132323742333046433343354345374137434538383438313632393730341216393030303030303030303030303030303030303030300a640a446962632f34324534374135424137303845424536453043323237303036323534463237383445323039463444424433433642423737454443344232394546383735453845121c323332353636383932303030303030303030303030303030303030300a620a446962632f38314430384243333946423532304542443934384346303137393130444436393730324433344246354143313630463736443342354346433434344542434530121a33333633393935353030303030303030303030303030303030300a1c0a0574686574611213313531373130393430373239393334333933380a290a057561746f6d12203133353338343330393338303535303237343635383338343139363137323031"; -pub const GOV_PROPOSAL_HEX_RESPONSE: &str = "08011291030a232f636f736d6f732e676f762e76312e4d7367457865634c6567616379436f6e74656e7412e9020ab7020a202f636f736d6f732e676f762e763162657461312e5465787450726f706f73616c1292020a4441646a7573746d656e74206f6620626c6f636b735f7065725f7965617220746f20636f6d6520616c69676e656420776974682061637475616c20626c6f636b2074696d6512c9015468697320676f7665726e616e63652070726f706f73616c20697320666f722061646a7573746d656e74206f6620626c6f636b735f7065725f7965617220706172616d6574657220746f206e6f726d616c697a652074686520696e666c6174696f6e207261746520616e642072657761726420726174652e5c6e2069706673206c696e6b3a2068747470733a2f2f697066732e696f2f697066732f516d587145427235367865557a4670676a736d444b4d5369743369716e4b6144454c347461627850586f7a397863122d636f736d6f73313064303779323635676d6d757674347a30773961773838306a6e73723730306a367a6e396b6e1803222f0a0e3937313138393033353236373939120c3430323338303537373233341a0c3332303534353430303030302201302a0b0897c1c7e40510e4838e13320b0897ab91e50510e4838e133a120a057561746f6d1209353132313030303030420c088fcccae405109399d2ac024a0c088fb694e505109399d2ac025a4441646a7573746d656e74206f6620626c6f636b735f7065725f7965617220746f20636f6d6520616c69676e656420776974682061637475616c20626c6f636b2074696d6562c9015468697320676f7665726e616e63652070726f706f73616c20697320666f722061646a7573746d656e74206f6620626c6f636b735f7065725f7965617220706172616d6574657220746f206e6f726d616c697a652074686520696e666c6174696f6e207261746520616e642072657761726420726174652e5c6e2069706673206c696e6b3a2068747470733a2f2f697066732e696f2f697066732f516d587145427235367865557a4670676a736d444b4d5369743369716e4b6144454c347461627850586f7a397863"; -pub const STAKING_PARAMS_HEX_RESPONSE: &str = "0a040880c60a109601180720904e2a057561746f6d321135303030303030303030303030303030303a1532353030303030303030303030303030303030303042123235303030303030303030303030303030304a12353030303030303030303030303030303030"; -pub const STAKING_VALIDATOR_HEX_RESPONSE: &str = "0a34636f736d6f7376616c6f70657231307636777664656e65653872396c36776c73706863677572326c746c387a746b6672766a396112430a1d2f636f736d6f732e63727970746f2e656432353531392e5075624b657912220a20da3f8d90a407031bb7eaf76ecb5b031c96487998e2ee7c67995222cefd3b329120032a0f32353030323832373430353233363432213235303032383237343035323336343030303030303030303030303030303030303a3f0a0a656172746820f09f8c8e1210436f696e6261736520437573746f64791a0a68797068612e636f6f702a134120746573746e65742076616c696461746f7240f4b5704a0c0893efd1f605109bfa83af02524d0a3e0a123230303030303030303030303030303030301213313030303030303030303030303030303030301a1331303030303030303030303030303030303030120b08ff98e8f10510b7c886275a0731303030303030721b3130323030303030333030303030303030303030303030303030307a1c38363935303034363237303030303030303030303030303030303030"; -pub const DELEGATOR_DELEGATIONS_HEX_RESPONSE: &str = "0a2d636f736d6f7331706d6a776d306138707673326d3870617579673272756c6479386e657934716e387a676439361234636f736d6f7376616c6f70657231307636777664656e65653872396c36776c73706863677572326c746c387a746b6672766a39611a1635303030303030303030303030303030303030303030"; -pub const DELEGATOR_UNBONDING_DELEGATIONS_HEX_RESPONSE: &str = "0a2d636f736d6f73316d396c33353878756e6868776473303536387a6134396d7a68767578783975787265357475641234636f736d6f7376616c6f7065723138686c356339786e35647a6532673530756177306c326d723032657735377a6b3061756b746e1a2108ed02120c08ba97f9ac0610f6abf18f021a0531303030302205313030303028011a2008f902120b08c797f9ac0610e59a89011a053230303030220532303030302802"; -pub const VALIDATOR_SIGNING_INFO_HEX_RESPONSE: &str = "0a34636f736d6f7376616c636f6e73313966353366717132387636706d7a383737646e653735643464376c307236356432373530707718102200"; - -#[test] -fn test_balance_reconstruct() { - struct TestCase { - addr: String, - coins: Vec<(String, String)>, - } - let test_cases: Vec = vec![ - TestCase { - addr: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), - coins: vec![("uosmo".to_string(), "100".to_string())], - }, - TestCase { - addr: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), - coins: vec![ - ("uosmo".to_string(), "100".to_string()), - ("uatom".to_string(), "500".to_string()), - ("uluna".to_string(), "80".to_string()), - ], - }, - TestCase { - addr: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), - coins: vec![("uluna".to_string(), "".to_string())], - }, - ]; - - for ts in test_cases { - let mut st_values: Vec = vec![]; - - let converted_addr_bytes = decode_and_convert(ts.addr.as_str()).unwrap(); - for coin in &ts.coins { - let balance_key = - create_account_denom_balance_key(converted_addr_bytes.clone(), &coin.0).unwrap(); - - let s = StorageValue { - storage_prefix: "".to_string(), - key: Binary::new(balance_key), - value: Binary::new(coin.1.clone().into_bytes()), - }; - st_values.push(s); - } - - let balances = Balances::reconstruct(&st_values).unwrap(); - assert_eq!(balances.coins.len(), ts.coins.len()); - for (i, coin) in balances.coins.iter().enumerate() { - assert_eq!(coin.denom, ts.coins[i].0); - // special testcase where value is an empty string - if ts.coins[i].1.is_empty() { - assert_eq!(coin.amount, Uint128::zero()); - continue; - } - assert_eq!(coin.amount, Uint128::from_str(&ts.coins[i].1).unwrap()) - } - } -} - -#[test] -fn test_bank_total_supply_reconstruct() { - struct TestValue { - denom: String, - amount: String, - } - struct TestCase { - values: Vec, - } - - let test_cases: Vec = vec![ - TestCase { - values: vec![TestValue { - denom: "uatom".to_string(), - amount: "100".to_string(), - }], - }, - TestCase { - values: vec![ - TestValue { - denom: "uatom".to_string(), - amount: "100".to_string(), - }, - TestValue { - denom: "uosmo".to_string(), - amount: "200".to_string(), - }, - ], - }, - TestCase { values: vec![] }, - ]; - - for ts in test_cases { - let mut st_values: Vec = vec![]; - - for case in &ts.values { - let denom_key = create_total_denom_key(case.denom.as_str()).unwrap(); - let s = StorageValue { - storage_prefix: "".to_string(), - key: Binary::new(denom_key), - value: Binary::new(case.amount.as_bytes().to_vec()), - }; - st_values.push(s); - } - - let total_supply = TotalSupply::reconstruct(&st_values).unwrap(); - assert_eq!(total_supply.coins.len(), ts.values.len()); - for (i, coin) in total_supply.coins.iter().enumerate() { - assert_eq!(coin.denom, ts.values[i].denom); - assert_eq!( - coin.amount, - Uint128::from_str(ts.values[i].amount.as_str()).unwrap() - ) - } - } -} - -#[test] -fn test_staking_validators_reconstruct() { - struct TestCase { - validators: Vec, - expected_result: NeutronResult, - } - - let test_cases: Vec = vec![ - TestCase { - validators: vec![Validator { - operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), - consensus_pubkey: None, - jailed: false, - status: 0, - tokens: "1000000000000000000".to_string(), - delegator_shares: "1000000000000000000".to_string(), - description: None, - unbonding_height: 0, - unbonding_time: None, - commission: None, - min_self_delegation: "".to_string(), - }], - expected_result: Ok(StakingValidator { - validators: vec![ContractValidator { - operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3" - .to_string(), - status: 0, - consensus_pubkey: None, - tokens: "1000000000000000000".to_string(), - delegator_shares: "1000000000000000000".to_string(), - moniker: None, - identity: None, - website: None, - security_contact: None, - details: None, - unbonding_height: 0, - unbonding_time: None, - rate: None, - max_rate: None, - max_change_rate: None, - update_time: None, - min_self_delegation: Decimal::from_str("0").unwrap(), - jailed: false, - }], - }), - }, - TestCase { - validators: vec![Validator { - operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), - consensus_pubkey: Some(prost_types::Any { - type_url: "consensus_pubkey".to_string(), - value: vec![], - }), - jailed: false, - status: 0, - tokens: "1000000000000000000".to_string(), - delegator_shares: "1000000000000000000".to_string(), - description: Some(Description { - moniker: "Test validator".to_string(), - identity: "JHFDHHFHF".to_string(), - website: "https://neutron.org".to_string(), - security_contact: "".to_string(), - details: "Validator details".to_string(), - }), - unbonding_height: 0, - unbonding_time: Some(prost_types::Timestamp { - seconds: 1203981203, - nanos: 123123, - }), - commission: Some(Commission { - commission_rates: Some(CommissionRates { - rate: "5000000000000000000".to_string(), // Dec(5) is 5+18 zeros - max_rate: "20000000000000000000".to_string(), // Dec(20) is 20+18 zeros - max_change_rate: "1000000000000000000".to_string(), // Dec(1) is 1+18 zeros - }), - update_time: Some(prost_types::Timestamp { - seconds: 56324234, - nanos: 1343, - }), - }), - min_self_delegation: "".to_string(), - }], - expected_result: Ok(StakingValidator { - validators: vec![ContractValidator { - operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3" - .to_string(), - status: 0, - consensus_pubkey: Some(vec![]), - tokens: "1000000000000000000".to_string(), - delegator_shares: "1000000000000000000".to_string(), - moniker: Some("Test validator".to_string()), - identity: Some("JHFDHHFHF".to_string()), - website: Some("https://neutron.org".to_string()), - security_contact: Some("".to_string()), - details: Some("Validator details".to_string()), - unbonding_height: 0, - unbonding_time: Some(1203981203), - rate: Some(Decimal::from_str("5").unwrap()), - max_rate: Some(Decimal::from_str("20").unwrap()), - max_change_rate: Some(Decimal::from_str("1").unwrap()), - update_time: Some(56324234), - min_self_delegation: Decimal::from_str("0").unwrap(), - jailed: false, - }], - }), - }, - TestCase { - validators: vec![ - Validator { - operator_address: "cosmosvaloper132juzk0gdmwuxvx4phug7m3ymyatxlh9734g4w" - .to_string(), - consensus_pubkey: Some(prost_types::Any { - type_url: "consensus_pubkey".to_string(), - value: vec![1u8, 2u8, 3u8, 4u8], - }), - jailed: false, - status: 0, - tokens: "1000000000000000000".to_string(), - delegator_shares: "1000000000000000000".to_string(), - description: None, - unbonding_height: 0, - unbonding_time: None, - commission: None, - min_self_delegation: "".to_string(), - }, - Validator { - operator_address: "cosmosvaloper1sjllsnramtg3ewxqwwrwjxfgc4n4ef9u2lcnj0" - .to_string(), - consensus_pubkey: None, - jailed: false, - status: 0, - tokens: "2000000000000000000".to_string(), - delegator_shares: "3000000000000000000".to_string(), - description: None, - unbonding_height: 0, - unbonding_time: None, - commission: None, - min_self_delegation: "".to_string(), - }, - ], - expected_result: Ok(StakingValidator { - validators: vec![ - ContractValidator { - operator_address: "cosmosvaloper132juzk0gdmwuxvx4phug7m3ymyatxlh9734g4w" - .to_string(), - status: 0, - consensus_pubkey: Some(vec![1u8, 2u8, 3u8, 4u8]), - tokens: "1000000000000000000".to_string(), - delegator_shares: "1000000000000000000".to_string(), - moniker: None, - identity: None, - website: None, - security_contact: None, - details: None, - unbonding_height: 0, - unbonding_time: None, - rate: None, - max_rate: None, - max_change_rate: None, - update_time: None, - min_self_delegation: Decimal::from_str("0").unwrap(), - jailed: false, - }, - ContractValidator { - operator_address: "cosmosvaloper1sjllsnramtg3ewxqwwrwjxfgc4n4ef9u2lcnj0" - .to_string(), - status: 0, - consensus_pubkey: None, - tokens: "2000000000000000000".to_string(), - delegator_shares: "3000000000000000000".to_string(), - moniker: None, - identity: None, - website: None, - security_contact: None, - details: None, - unbonding_height: 0, - unbonding_time: None, - rate: None, - max_rate: None, - max_change_rate: None, - update_time: None, - min_self_delegation: Decimal::from_str("0").unwrap(), - jailed: false, - }, - ], - }), - }, - TestCase { - validators: vec![], - expected_result: Ok(StakingValidator { validators: vec![] }), - }, - ]; - - for ts in test_cases { - let mut st_values: Vec = vec![]; - - for validator in &ts.validators { - let val_addr = decode_and_convert(validator.operator_address.as_str()).unwrap(); - - let validator_key = create_validator_key(&val_addr).unwrap(); - let s = StorageValue { - storage_prefix: "".to_string(), - key: Binary::new(validator_key), - value: Binary::new(validator.encode_to_vec()), - }; - st_values.push(s); - } - - let stakin_validator = StakingValidator::reconstruct(&st_values); - - assert_eq!(stakin_validator, ts.expected_result) - } -} - -#[test] -fn test_validators_signing_infos_reconstruct() { - struct TestCase { - signing_infos: Vec, - expected_result: NeutronResult, - } - - let test_cases: Vec = vec![ - TestCase { - signing_infos: vec![CosmosValidatorSigningInfo { - address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), - start_height: 1, - index_offset: 1, - jailed_until: None, - tombstoned: false, - missed_blocks_counter: 987675, - }], - expected_result: Ok(SigningInfo { - signing_infos: vec![ValidatorSigningInfo { - address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), - start_height: 1, - index_offset: 1, - jailed_until: None, - tombstoned: false, - missed_blocks_counter: 987675, - }], - }), - }, - TestCase { - signing_infos: vec![CosmosValidatorSigningInfo { - address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), - start_height: 1, - index_offset: 1, - jailed_until: Some(prost_types::Timestamp { - seconds: 321654, - nanos: 123123, - }), - tombstoned: false, - missed_blocks_counter: 987675, - }], - expected_result: Ok(SigningInfo { - signing_infos: vec![ValidatorSigningInfo { - address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), - start_height: 1, - index_offset: 1, - jailed_until: Some(321654), - tombstoned: false, - missed_blocks_counter: 987675, - }], - }), - }, - TestCase { - signing_infos: vec![ - CosmosValidatorSigningInfo { - address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), - start_height: 1, - index_offset: 1, - jailed_until: None, - tombstoned: true, - missed_blocks_counter: 987675, - }, - CosmosValidatorSigningInfo { - address: "cosmosvalcons16tnak7apushwznnd3wtku8gm0rt3xytz6ut006".to_string(), - start_height: 1, - index_offset: 1, - jailed_until: Some(prost_types::Timestamp { - seconds: 321654, - nanos: 123123, - }), - tombstoned: false, - missed_blocks_counter: 345012, - }, - ], - expected_result: Ok(SigningInfo { - signing_infos: vec![ - ValidatorSigningInfo { - address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), - start_height: 1, - index_offset: 1, - jailed_until: None, - tombstoned: true, - missed_blocks_counter: 987675, - }, - ValidatorSigningInfo { - address: "cosmosvalcons16tnak7apushwznnd3wtku8gm0rt3xytz6ut006".to_string(), - start_height: 1, - index_offset: 1, - jailed_until: Some(321654), - tombstoned: false, - missed_blocks_counter: 345012, - }, - ], - }), - }, - TestCase { - signing_infos: vec![], - expected_result: Ok(SigningInfo { - signing_infos: vec![], - }), - }, - ]; - - for ts in test_cases { - let mut st_values: Vec = vec![]; - - for info in &ts.signing_infos { - let val_addr = decode_and_convert(info.address.as_str()).unwrap(); - - let signing_info_key = create_validator_signing_info_key(&val_addr).unwrap(); - let s = StorageValue { - storage_prefix: "".to_string(), - key: Binary::new(signing_info_key), - value: Binary::new(info.encode_to_vec()), - }; - st_values.push(s); - } - - let signing_infos = SigningInfo::reconstruct(&st_values); - - assert_eq!(signing_infos, ts.expected_result) - } -} - -#[test] -fn test_government_proposals_reconstruct() { - struct TestCase { - proposals: Vec, - expected_result: NeutronResult, - } - - let test_cases: Vec = vec![ - TestCase { - proposals: vec![CosmosProposal { - proposal_id: 1, - content: Some(prost_types::Any { - type_url: "proposal_type".to_string(), - value: vec![], - }), - status: 1, - final_tally_result: None, - submit_time: None, - deposit_end_time: None, - total_deposit: vec![Coin { - amount: "100000".to_string(), - denom: "stake".to_string(), - }], - voting_start_time: None, - voting_end_time: None, - }], - expected_result: Ok(GovernmentProposal { - proposals: vec![Proposal { - proposal_id: 1, - proposal_type: Some("proposal_type".to_string()), - total_deposit: vec![StdCoin::new(100000u128, "stake")], - status: 1, - submit_time: None, - deposit_end_time: None, - voting_start_time: None, - voting_end_time: None, - final_tally_result: None, - }], - }), - }, - TestCase { - proposals: vec![CosmosProposal { - proposal_id: 1, - content: Some(prost_types::Any { - type_url: "proposal_type".to_string(), - value: vec![], - }), - status: 1, - final_tally_result: Some(CosmosTallyResult { - abstain: "1".to_string(), - no: "2".to_string(), - no_with_veto: "3".to_string(), - yes: "4".to_string(), - }), - submit_time: Some(prost_types::Timestamp { - seconds: 2222222, - nanos: 123123, - }), - deposit_end_time: Some(prost_types::Timestamp { - seconds: 3333333, - nanos: 123123, - }), - total_deposit: vec![Coin { - amount: "100000".to_string(), - denom: "stake".to_string(), - }], - voting_start_time: Some(prost_types::Timestamp { - seconds: 4444444, - nanos: 123123, - }), - voting_end_time: Some(prost_types::Timestamp { - seconds: 555555555, - nanos: 123123, - }), - }], - expected_result: Ok(GovernmentProposal { - proposals: vec![Proposal { - proposal_id: 1, - proposal_type: Some("proposal_type".to_string()), - total_deposit: vec![StdCoin::new(100000u128, "stake")], - status: 1, - submit_time: Some(2222222), - deposit_end_time: Some(3333333), - voting_start_time: Some(4444444), - voting_end_time: Some(555555555), - final_tally_result: Some(TallyResult { - abstain: Uint128::from(1u128), - no: Uint128::from(2u128), - no_with_veto: Uint128::from(3u128), - yes: Uint128::from(4u128), - }), - }], - }), - }, - TestCase { - proposals: vec![ - CosmosProposal { - proposal_id: 1, - content: Some(prost_types::Any { - type_url: "proposal_type1".to_string(), - value: vec![], - }), - status: 1, - final_tally_result: None, - submit_time: None, - deposit_end_time: None, - total_deposit: vec![Coin { - amount: "100000".to_string(), - denom: "stake".to_string(), - }], - voting_start_time: None, - voting_end_time: None, - }, - CosmosProposal { - proposal_id: 2, - content: Some(prost_types::Any { - type_url: "proposal_type2".to_string(), - value: vec![], - }), - status: 1, - final_tally_result: None, - submit_time: None, - deposit_end_time: None, - total_deposit: vec![Coin { - amount: "200000".to_string(), - denom: "osmo".to_string(), - }], - voting_start_time: None, - voting_end_time: None, - }, - ], - expected_result: Ok(GovernmentProposal { - proposals: vec![ - Proposal { - proposal_id: 1, - proposal_type: Some("proposal_type1".to_string()), - total_deposit: vec![StdCoin::new(100000u128, "stake")], - status: 1, - submit_time: None, - deposit_end_time: None, - voting_start_time: None, - voting_end_time: None, - final_tally_result: None, - }, - Proposal { - proposal_id: 2, - proposal_type: Some("proposal_type2".to_string()), - total_deposit: vec![StdCoin::new(200000u128, "osmo")], - status: 1, - submit_time: None, - deposit_end_time: None, - voting_start_time: None, - voting_end_time: None, - final_tally_result: None, - }, - ], - }), - }, - TestCase { - proposals: vec![], - expected_result: Ok(GovernmentProposal { proposals: vec![] }), - }, - ]; - - for ts in test_cases { - let mut st_values: Vec = vec![]; - - for proposal in &ts.proposals { - let proposal_key = create_gov_proposal_key(proposal.proposal_id).unwrap(); - let s = StorageValue { - storage_prefix: "".to_string(), - key: Binary::new(proposal_key), - value: Binary::new(proposal.encode_to_vec()), - }; - st_values.push(s); - } - - let gov_proposal = GovernmentProposal::reconstruct(&st_values); - - assert_eq!(gov_proposal, ts.expected_result) - } -} - -#[test] -fn test_fee_pool_reconstruct() { - struct TestCase { - coins: Vec<(String, Uint128)>, - } - let test_cases: Vec = vec![ - TestCase { - coins: vec![("uosmo".to_string(), Uint128::from(100u128))], - }, - TestCase { - coins: vec![ - ("uosmo".to_string(), Uint128::from(100u128)), - ("uatom".to_string(), Uint128::from(500u128)), - ("uluna".to_string(), Uint128::from(80u128)), - ], - }, - TestCase { coins: vec![] }, - ]; - - for ts in test_cases { - let mut coins: Vec = vec![]; - - for coin in &ts.coins { - let balance_amount = DecCoin { - denom: coin.0.clone(), - amount: coin - .1 - .mul(Uint128::one().mul(Uint128::from(10u64).pow(DECIMAL_PLACES))) // adjust to Dec gogo proto format - .to_string(), - }; - - coins.push(balance_amount); - } - - let fee_pool = CosmosFeePool { - community_pool: coins, - }; - - let fee_pool_key = create_fee_pool_key().unwrap(); - - let st_value = StorageValue { - storage_prefix: "".to_string(), - key: Binary::new(fee_pool_key), - value: Binary::new(fee_pool.encode_to_vec()), - }; - - let fee_pool_coins = FeePool::reconstruct(&[st_value]).unwrap(); - assert_eq!(fee_pool_coins.coins.len(), ts.coins.len()); - for (i, coin) in fee_pool_coins.coins.iter().enumerate() { - assert_eq!(coin.denom, ts.coins[i].0); - assert_eq!(coin.amount, ts.coins[i].1) - } - } -} - -#[test] -fn test_delegations_reconstruct() { - struct TestCase { - staking_params: Params, - delegations: Vec, - validators: Vec, - expected_result: NeutronResult, - } - let test_cases: Vec = vec![ - TestCase { - staking_params: Params { - unbonding_time: None, - max_validators: 0, - max_entries: 0, - historical_entries: 0, - bond_denom: "stake".to_string(), - min_commission_rate: "".to_string(), - }, - delegations: vec![Delegation { - delegator_address: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), - validator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), - shares: "1000000000000000000".to_string(), - }], - validators: vec![Validator { - operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), - consensus_pubkey: None, - jailed: false, - status: 0, - tokens: "1000000000000000000".to_string(), - delegator_shares: "1000000000000000000".to_string(), - description: None, - unbonding_height: 0, - unbonding_time: None, - commission: None, - min_self_delegation: "".to_string(), - }], - expected_result: Ok(Delegations { - delegations: vec![StdDelegation { - delegator: Addr::unchecked("osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs"), - validator: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), - amount: StdCoin::new(1000000000000000000u128, "stake"), - }], - }), - }, - TestCase { - staking_params: Params { - unbonding_time: None, - max_validators: 0, - max_entries: 0, - historical_entries: 0, - bond_denom: "stake".to_string(), - min_commission_rate: "".to_string(), - }, - delegations: vec![ - Delegation { - delegator_address: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), - validator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3" - .to_string(), - shares: "1000000000000000000".to_string(), - }, - Delegation { - delegator_address: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), - validator_address: "osmovaloper1lzhlnpahvznwfv4jmay2tgaha5kmz5qxwmj9we" - .to_string(), - shares: "1000000000000000000".to_string(), - }, - ], - validators: vec![ - Validator { - operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3" - .to_string(), - consensus_pubkey: None, - jailed: false, - status: 0, - tokens: "1000000000000000000".to_string(), - delegator_shares: "1000000000000000000".to_string(), - description: None, - unbonding_height: 0, - unbonding_time: None, - commission: None, - min_self_delegation: "".to_string(), - }, - Validator { - operator_address: "osmovaloper1lzhlnpahvznwfv4jmay2tgaha5kmz5qxwmj9we" - .to_string(), - consensus_pubkey: None, - jailed: false, - status: 0, - tokens: "1000000000000000000".to_string(), - delegator_shares: "1000000000000000000".to_string(), - description: None, - unbonding_height: 0, - unbonding_time: None, - commission: None, - min_self_delegation: "".to_string(), - }, - ], - expected_result: Ok(Delegations { - delegations: vec![ - StdDelegation { - delegator: Addr::unchecked("osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs"), - validator: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), - amount: StdCoin::new(1000000000000000000u128, "stake"), - }, - StdDelegation { - delegator: Addr::unchecked("osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs"), - validator: "osmovaloper1lzhlnpahvznwfv4jmay2tgaha5kmz5qxwmj9we".to_string(), - amount: StdCoin::new(1000000000000000000u128, "stake"), - }, - ], - }), - }, - TestCase { - staking_params: Params { - unbonding_time: None, - max_validators: 0, - max_entries: 0, - historical_entries: 0, - bond_denom: "stake".to_string(), - min_commission_rate: "".to_string(), - }, - delegations: vec![], - validators: vec![], - expected_result: Ok(Delegations { - delegations: vec![], - }), - }, - TestCase { - staking_params: Default::default(), - delegations: vec![], - validators: vec![], - expected_result: Err(NeutronError::InvalidQueryResultFormat( - "params is empty".into(), - )), - }, - TestCase { - staking_params: Params { - unbonding_time: None, - max_validators: 0, - max_entries: 0, - historical_entries: 0, - bond_denom: "stake".to_string(), - min_commission_rate: "".to_string(), - }, - delegations: vec![Delegation { - delegator_address: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), - validator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), - shares: "1000000000000000000".to_string(), - }], - validators: vec![], - expected_result: Err(NeutronError::InvalidQueryResultFormat( - "validator is empty".into(), - )), - }, - ]; - - for ts in &test_cases { - // prepare storage values - let mut st_values: Vec = vec![StorageValue { - storage_prefix: STAKING_STORE_KEY.to_string(), - key: Binary::new(vec![STAKING_PARAMS_KEY]), - value: { - if ts.staking_params.bond_denom.is_empty() { - return Default::default(); - } - Binary::from(ts.staking_params.encode_to_vec()) - }, - }]; - - for (i, d) in ts.delegations.iter().enumerate() { - let delegator_addr = decode_and_convert(&d.delegator_address).unwrap(); - let val_addr = decode_and_convert(&d.validator_address).unwrap(); - - st_values.push(StorageValue { - storage_prefix: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_delegation_key(&delegator_addr, &val_addr).unwrap()), - value: Binary::from(d.encode_to_vec()), - }); - - if let Some(v) = ts.validators.get(i) { - st_values.push(StorageValue { - storage_prefix: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_validator_key(&val_addr).unwrap()), - value: Binary::from(v.encode_to_vec()), - }); - } - } - - // test reconstruction - let delegations = Delegations::reconstruct(&st_values); - - assert_eq!(delegations, ts.expected_result) - } -} - -#[test] -fn test_balance_reconstruct_from_hex() { - let bytes = hex::decode(BALANCES_HEX_RESPONSE).unwrap(); // decode hex string to bytes - let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string - - let s = StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::new(create_account_denom_balance_key("addr", "uatom").unwrap()), - value: Binary::from_base64(base64_input.as_str()).unwrap(), - }; - let bank_balances = Balances::reconstruct(&[s]).unwrap(); - assert_eq!( - bank_balances, - Balances { - coins: vec![StdCoin::new(494213561u128, "uatom")] - } - ); -} - -#[test] -fn test_balance_reconstruct_from_empty_value() { - let s = StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::new(create_account_denom_balance_key("addr", "uatom").unwrap()), - value: Binary::from(vec![]), - }; - let bank_balances = Balances::reconstruct(&[s]).unwrap(); - assert_eq!( - bank_balances, - Balances { - coins: vec![StdCoin::new(0u128, "uatom")] - } - ); -} - -#[test] -fn test_bank_total_supply_reconstruct_from_hex() { - let bytes = hex::decode(TOTAL_SUPPLY_HEX_RESPONSE).unwrap(); // decode hex string to bytes - let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string - - let s = StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::new(create_total_denom_key("stake").unwrap()), - value: Binary::from_base64(base64_input.as_str()).unwrap(), - }; - let total_supply = TotalSupply::reconstruct(&[s]).unwrap(); - assert_eq!( - total_supply, - TotalSupply { - coins: vec![StdCoin { - denom: String::from("stake"), - amount: Uint128::from(1644171988905769u64), // mutating - }] - } - ); -} - -#[test] -fn test_delegations_reconstruct_overflow() { - struct TestCase { - staking_params: Params, - delegations: Vec, - validators: Vec, - expected_result: NeutronResult, - } - let test_cases: Vec = vec![TestCase { - staking_params: Params { - unbonding_time: None, - max_validators: 0, - max_entries: 0, - historical_entries: 0, - bond_denom: "stake".to_string(), - min_commission_rate: "".to_string(), - }, - delegations: vec![Delegation { - delegator_address: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), - validator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), - shares: "340282366920938463463".to_string(), - }], - validators: vec![Validator { - operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), - consensus_pubkey: None, - jailed: false, - status: 0, - tokens: "340282366920938463463".to_string(), - delegator_shares: "340282366920938463463".to_string(), - description: None, - unbonding_height: 0, - unbonding_time: None, - commission: None, - min_self_delegation: "".to_string(), - }], - expected_result: Ok(Delegations { - delegations: vec![StdDelegation { - delegator: Addr::unchecked("osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs"), - validator: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), - amount: StdCoin::new(340282366920938463463u128, "stake"), - }], - }), - }]; - - for ts in &test_cases { - // prepare storage values - let mut st_values: Vec = vec![StorageValue { - storage_prefix: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_params_store_key(STAKING_STORE_KEY, KEY_BOND_DENOM)), - value: { - if ts.staking_params.bond_denom.is_empty() { - return Default::default(); - } - Binary::from(ts.staking_params.encode_to_vec()) - }, - }]; - - for (i, d) in ts.delegations.iter().enumerate() { - let delegator_addr = decode_and_convert(&d.delegator_address).unwrap(); - let val_addr = decode_and_convert(&d.validator_address).unwrap(); - - st_values.push(StorageValue { - storage_prefix: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_delegation_key(&delegator_addr, &val_addr).unwrap()), - value: Binary::from(d.encode_to_vec()), - }); - - if let Some(v) = ts.validators.get(i) { - st_values.push(StorageValue { - storage_prefix: STAKING_STORE_KEY.to_string(), - key: Binary::new(create_validator_key(&val_addr).unwrap()), - value: Binary::from(v.encode_to_vec()), - }); - } - } - - // test reconstruction - let delegations = Delegations::reconstruct(&st_values); - - assert_eq!(delegations, ts.expected_result) - } -} - -#[test] -fn test_staking_validators_reconstruct_from_hex() { - let bytes = hex::decode(STAKING_VALIDATOR_HEX_RESPONSE).unwrap(); // decode hex string to bytes - let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string - - let s = StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::default(), // not used in reconstruct - value: Binary::from_base64(base64_input.as_str()).unwrap(), - }; - let staking_validator = StakingValidator::reconstruct(&[s]).unwrap(); - assert_eq!( - staking_validator, - StakingValidator { - validators: vec![ContractValidator { - operator_address: String::from( - "cosmosvaloper10v6wvdenee8r9l6wlsphcgur2ltl8ztkfrvj9a" // mutating - ), - consensus_pubkey: Some(vec![ - 10, 32, 218, 63, 141, 144, 164, 7, 3, 27, 183, 234, 247, 110, 203, 91, 3, 28, - 150, 72, 121, 152, 226, 238, 124, 103, 153, 82, 34, 206, 253, 59, 50, 145, - ]), - jailed: false, - status: 3, - tokens: String::from("250028274052364"), - delegator_shares: String::from("250028274052364000000000000000000"), - moniker: Some(String::from("earth 🌎")), - identity: Some(String::from("Coinbase Custody")), - website: Some(String::from("hypha.coop")), - security_contact: Some(String::from("")), - details: Some(String::from("A testnet validator")), - unbonding_height: 1841908u64, - unbonding_time: Some(1590982547u64), - rate: Some(Decimal::from_str("0.200000000000000000").unwrap()), - max_rate: Some(Decimal::from_str("1.00000000000000000").unwrap()), - max_change_rate: Some(Decimal::from_str("1.000000000000000000").unwrap()), - update_time: Some(1580862591u64), // mutating - min_self_delegation: Decimal::from_str("1000000").unwrap(), - }] - } - ); -} - -#[test] -fn test_validators_signing_infos_reconstruct_from_hex() { - let bytes = hex::decode(VALIDATOR_SIGNING_INFO_HEX_RESPONSE).unwrap(); // decode hex string to bytes - let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string - - let s = StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::default(), // not used in reconstruct - value: Binary::from_base64(base64_input.as_str()).unwrap(), - }; - let signing_info = SigningInfo::reconstruct(&[s]).unwrap(); - assert_eq!( - signing_info, - SigningInfo { - signing_infos: vec![ValidatorSigningInfo { - address: "cosmosvalcons19f53fqq28v6pmz877dne75d4d7l0r65d2750pw".to_string(), - start_height: 0, - index_offset: 16, - jailed_until: Some(0), - tombstoned: false, - missed_blocks_counter: 0, - }] - } - ); -} - -#[test] -fn test_government_proposals_reconstruct_from_hex() { - let bytes = hex::decode(GOV_PROPOSAL_HEX_RESPONSE).unwrap(); // decode hex string to bytes - let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string - - let s = StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::default(), // not used in reconstruct - value: Binary::from_base64(base64_input.as_str()).unwrap(), - }; - let proposals = GovernmentProposal::reconstruct(&[s]).unwrap(); - assert_eq!( - proposals, - GovernmentProposal { - proposals: vec![Proposal { - proposal_id: 1u64, - proposal_type: Some(String::from("/cosmos.gov.v1.MsgExecLegacyContent")), - total_deposit: vec![StdCoin { - denom: String::from("uatom"), - amount: Uint128::from(512100000u64), - }], - status: 3i32, - submit_time: Some(1553064087u64), // mutating - deposit_end_time: Some(1554273687u64), // mutating - voting_start_time: Some(1553114639u64), // 0001-01-01T00:00:00Z - voting_end_time: Some(1554324239u64), // 0001-01-01T00:00:00Z - final_tally_result: Some(TallyResult { - yes: Uint128::from(97118903526799u128), - no: Uint128::from(320545400000u128), - abstain: Uint128::from(402380577234u128), - no_with_veto: Uint128::zero(), - }), - }] - } - ); -} - -#[test] -fn test_fee_pool_reconstruct_from_hex() { - let bytes = hex::decode(FEE_POOL_HEX_RESPONSE).unwrap(); // decode hex string to bytes - let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string - - let s = StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::default(), // not used in reconstruct - value: Binary::from_base64(base64_input.as_str()).unwrap(), - }; - let fee_pool = FeePool::reconstruct(&[s]).unwrap(); - assert_eq!( - fee_pool, - FeePool { - coins: vec![ - StdCoin { - denom: String::from( - "ibc/12DA42304EE1CE96071F712AA4D58186AD11C3165C0DCDA71E017A54F3935E66" - ), - amount: Uint128::from(444252217u64), // mutating - }, - StdCoin { - denom: String::from( - "ibc/14F9BC3E44B8A9C1BE1FB08980FAB87034C9905EF17CF2F5008FC085218811CC" - ), - amount: Uint128::from(189753432u64), // mutating - }, - StdCoin { - denom: String::from( - "ibc/1FBDD58D438B4D04D26CBFB2E722C18984A0F1A52468C4F42F37D102F3D3F399" - ), - amount: Uint128::from(25455348u64), // mutating - }, - StdCoin { - denom: String::from( - "ibc/2181AAB0218EAC24BC9F86BD1364FBBFA3E6E3FCC25E88E3E68C15DC6E752D86" - ), - amount: Uint128::from(89764472u64), // mutating - }, - StdCoin { - denom: String::from( - "ibc/2717109A95559F3A17EFC0C897B7691E22A227B30FC3C5CE7A7CE88481629704" - ), - amount: Uint128::from(9000u64), // mutating - }, - StdCoin { - denom: String::from( - "ibc/42E47A5BA708EBE6E0C227006254F2784E209F4DBD3C6BB77EDC4B29EF875E8E" - ), - amount: Uint128::from(2325668920u64), // mutating - }, - StdCoin { - denom: String::from( - "ibc/81D08BC39FB520EBD948CF017910DD69702D34BF5AC160F76D3B5CFC444EBCE0" - ), - amount: Uint128::from(33639955u64), // mutating - }, - StdCoin { - denom: String::from("theta"), - amount: Uint128::from(1u64), // mutating - }, - StdCoin { - denom: String::from("uatom"), - amount: Uint128::from(13538430938055u64), // mutating - }, - ] - } - ); -} - -#[test] -fn test_delegations_reconstruct_from_hex() { - let staking_params_bytes = hex::decode(STAKING_PARAMS_HEX_RESPONSE).unwrap(); // decode hex string to bytes - let staking_params_base64_input = BASE64_STANDARD.encode(staking_params_bytes); // encode bytes to base64 string - let staking_validator_bytes = hex::decode(STAKING_VALIDATOR_HEX_RESPONSE).unwrap(); // decode hex string to bytes - let staking_validator_base64_input = BASE64_STANDARD.encode(staking_validator_bytes); // encode bytes to base64 string - let delegation_bytes = hex::decode(DELEGATOR_DELEGATIONS_HEX_RESPONSE).unwrap(); // decode hex string to bytes - let delegation_base64_input = BASE64_STANDARD.encode(delegation_bytes); // encode bytes to base64 string - - let mut st_values: Vec = vec![StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::default(), // not used in reconstruct - value: Binary::from_base64(staking_params_base64_input.as_str()).unwrap(), - }]; - st_values.push(StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::default(), // not used in reconstruct - value: Binary::from_base64(delegation_base64_input.as_str()).unwrap(), - }); - st_values.push(StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::default(), // not used in reconstruct - value: Binary::from_base64(staking_validator_base64_input.as_str()).unwrap(), - }); - - let delegations = Delegations::reconstruct(&st_values).unwrap(); - assert_eq!( - delegations, - Delegations { - delegations: vec![StdDelegation { - delegator: Addr::unchecked("cosmos1pmjwm0a8pvs2m8pauyg2ruldy8ney4qn8zgd96"), // mutating - validator: String::from("cosmosvaloper10v6wvdenee8r9l6wlsphcgur2ltl8ztkfrvj9a"), // mutating - amount: StdCoin { - denom: String::from("uatom"), - amount: Uint128::from(5000u64), - }, - }], - } - ); -} - -#[test] -fn test_unbonding_delegations_reconstruct_from_hex() { - let unbonding_delegations_bytes = - hex::decode(DELEGATOR_UNBONDING_DELEGATIONS_HEX_RESPONSE).unwrap(); // decode hex string to bytes - let unbonding_delegations_base64_input = BASE64_STANDARD.encode(unbonding_delegations_bytes); // encode bytes to base64 string - - let st_values: Vec = vec![StorageValue { - storage_prefix: String::default(), // not used in reconstruct - key: Binary::default(), // not used in reconstruct - value: Binary::from_base64(unbonding_delegations_base64_input.as_str()).unwrap(), - }]; - - let unbonding_delegations = UnbondingDelegations::reconstruct(&st_values).unwrap(); - assert_eq!( - unbonding_delegations, - UnbondingDelegations { - unbonding_responses: vec![UnbondingResponse { - delegator_address: Addr::unchecked("cosmos1m9l358xunhhwds0568za49mzhvuxx9uxre5tud"), - validator_address: String::from( - "cosmosvaloper18hl5c9xn5dze2g50uaw0l2mr02ew57zk0auktn" - ), - entries: vec![ - UnbondingEntry { - balance: Uint128::new(10_000), - completion_time: Some(Timestamp::from_nanos(1704872890570185206)), - creation_height: 365, - initial_balance: Uint128::new(10_000), - }, - UnbondingEntry { - balance: Uint128::new(20_000), - completion_time: Some(Timestamp::from_nanos(1704872903002248037)), - creation_height: 377, - initial_balance: Uint128::new(20_000), - }, - ], - }] - } - ); -} +// use crate::bindings::types::StorageValue; +// use crate::interchain_queries::helpers::decode_and_convert; +// use crate::interchain_queries::types::KVReconstruct; +// use crate::interchain_queries::v045::helpers::create_params_store_key; +// use crate::interchain_queries::v045::types::KEY_BOND_DENOM; +// use crate::interchain_queries::v047::helpers::{ +// create_account_denom_balance_key, create_delegation_key, create_fee_pool_key, +// create_gov_proposal_key, create_total_denom_key, create_validator_key, +// create_validator_signing_info_key, +// }; +// use crate::interchain_queries::v047::types::{ +// Balances, Delegations, FeePool, GovernmentProposal, Proposal, SigningInfo, StakingValidator, +// StdDelegation, TallyResult, TotalSupply, UnbondingDelegations, UnbondingEntry, +// UnbondingResponse, Validator as ContractValidator, ValidatorSigningInfo, DECIMAL_PLACES, +// STAKING_PARAMS_KEY, STAKING_STORE_KEY, +// }; +// use crate::{NeutronError, NeutronResult}; +// use base64::prelude::*; +// use base64::Engine; +// use cosmos_sdk_proto::cosmos::base::v1beta1::{Coin, DecCoin}; +// use cosmos_sdk_proto::cosmos::distribution::v1beta1::FeePool as CosmosFeePool; +// use cosmos_sdk_proto::cosmos::gov::v1beta1::{ +// Proposal as CosmosProposal, TallyResult as CosmosTallyResult, +// }; +// use cosmos_sdk_proto::cosmos::slashing::v1beta1::ValidatorSigningInfo as CosmosValidatorSigningInfo; +// use cosmos_sdk_proto::cosmos::staking::v1beta1::{ +// Commission, CommissionRates, Delegation, Description, Params, Validator, +// }; +// use cosmos_sdk_proto::traits::Message; +// use cosmwasm_std::{Addr, Binary, Coin as StdCoin, Decimal, Timestamp, Uint128}; +// use hex; +// use std::ops::Mul; +// use std::str::FromStr; +// +// // raw hex data from KV storage created using https://github.com/neutron-org/icq-compliance-officer. +// pub const BALANCES_HEX_RESPONSE: &str = "343934323133353631"; +// pub const TOTAL_SUPPLY_HEX_RESPONSE: &str = "31363434313731393838393035373639"; +// pub const FEE_POOL_HEX_RESPONSE: &str = +// "0a630a446962632f31324441343233303445453143453936303731463731324141344435383138364144313143333136354330444344413731453031374135344633393335453636121b3434343235323231373030303030303030303030303030303030300a630a446962632f31344639424333453434423841394331424531464230383938304641423837303334433939303545463137434632463530303846433038353231383831314343121b3138393735333433323030303030303030303030303030303030300a620a446962632f31464244443538443433384234443034443236434246423245373232433138393834413046314135323436384334463432463337443130324633443346333939121a32353435353334383030303030303030303030303030303030300a620a446962632f32313831414142303231384541433234424339463836424431333634464242464133453645334643433235453838453345363843313544433645373532443836121a38393736343437323030303030303030303030303030303030300a5e0a446962632f323731373130394139353535394633413137454643304338393742373639314532324132323742333046433343354345374137434538383438313632393730341216393030303030303030303030303030303030303030300a640a446962632f34324534374135424137303845424536453043323237303036323534463237383445323039463444424433433642423737454443344232394546383735453845121c323332353636383932303030303030303030303030303030303030300a620a446962632f38314430384243333946423532304542443934384346303137393130444436393730324433344246354143313630463736443342354346433434344542434530121a33333633393935353030303030303030303030303030303030300a1c0a0574686574611213313531373130393430373239393334333933380a290a057561746f6d12203133353338343330393338303535303237343635383338343139363137323031"; +// pub const GOV_PROPOSAL_HEX_RESPONSE: &str = "08011291030a232f636f736d6f732e676f762e76312e4d7367457865634c6567616379436f6e74656e7412e9020ab7020a202f636f736d6f732e676f762e763162657461312e5465787450726f706f73616c1292020a4441646a7573746d656e74206f6620626c6f636b735f7065725f7965617220746f20636f6d6520616c69676e656420776974682061637475616c20626c6f636b2074696d6512c9015468697320676f7665726e616e63652070726f706f73616c20697320666f722061646a7573746d656e74206f6620626c6f636b735f7065725f7965617220706172616d6574657220746f206e6f726d616c697a652074686520696e666c6174696f6e207261746520616e642072657761726420726174652e5c6e2069706673206c696e6b3a2068747470733a2f2f697066732e696f2f697066732f516d587145427235367865557a4670676a736d444b4d5369743369716e4b6144454c347461627850586f7a397863122d636f736d6f73313064303779323635676d6d757674347a30773961773838306a6e73723730306a367a6e396b6e1803222f0a0e3937313138393033353236373939120c3430323338303537373233341a0c3332303534353430303030302201302a0b0897c1c7e40510e4838e13320b0897ab91e50510e4838e133a120a057561746f6d1209353132313030303030420c088fcccae405109399d2ac024a0c088fb694e505109399d2ac025a4441646a7573746d656e74206f6620626c6f636b735f7065725f7965617220746f20636f6d6520616c69676e656420776974682061637475616c20626c6f636b2074696d6562c9015468697320676f7665726e616e63652070726f706f73616c20697320666f722061646a7573746d656e74206f6620626c6f636b735f7065725f7965617220706172616d6574657220746f206e6f726d616c697a652074686520696e666c6174696f6e207261746520616e642072657761726420726174652e5c6e2069706673206c696e6b3a2068747470733a2f2f697066732e696f2f697066732f516d587145427235367865557a4670676a736d444b4d5369743369716e4b6144454c347461627850586f7a397863"; +// pub const STAKING_PARAMS_HEX_RESPONSE: &str = "0a040880c60a109601180720904e2a057561746f6d321135303030303030303030303030303030303a1532353030303030303030303030303030303030303042123235303030303030303030303030303030304a12353030303030303030303030303030303030"; +// pub const STAKING_VALIDATOR_HEX_RESPONSE: &str = "0a34636f736d6f7376616c6f70657231307636777664656e65653872396c36776c73706863677572326c746c387a746b6672766a396112430a1d2f636f736d6f732e63727970746f2e656432353531392e5075624b657912220a20da3f8d90a407031bb7eaf76ecb5b031c96487998e2ee7c67995222cefd3b329120032a0f32353030323832373430353233363432213235303032383237343035323336343030303030303030303030303030303030303a3f0a0a656172746820f09f8c8e1210436f696e6261736520437573746f64791a0a68797068612e636f6f702a134120746573746e65742076616c696461746f7240f4b5704a0c0893efd1f605109bfa83af02524d0a3e0a123230303030303030303030303030303030301213313030303030303030303030303030303030301a1331303030303030303030303030303030303030120b08ff98e8f10510b7c886275a0731303030303030721b3130323030303030333030303030303030303030303030303030307a1c38363935303034363237303030303030303030303030303030303030"; +// pub const DELEGATOR_DELEGATIONS_HEX_RESPONSE: &str = "0a2d636f736d6f7331706d6a776d306138707673326d3870617579673272756c6479386e657934716e387a676439361234636f736d6f7376616c6f70657231307636777664656e65653872396c36776c73706863677572326c746c387a746b6672766a39611a1635303030303030303030303030303030303030303030"; +// pub const DELEGATOR_UNBONDING_DELEGATIONS_HEX_RESPONSE: &str = "0a2d636f736d6f73316d396c33353878756e6868776473303536387a6134396d7a68767578783975787265357475641234636f736d6f7376616c6f7065723138686c356339786e35647a6532673530756177306c326d723032657735377a6b3061756b746e1a2108ed02120c08ba97f9ac0610f6abf18f021a0531303030302205313030303028011a2008f902120b08c797f9ac0610e59a89011a053230303030220532303030302802"; +// pub const VALIDATOR_SIGNING_INFO_HEX_RESPONSE: &str = "0a34636f736d6f7376616c636f6e73313966353366717132387636706d7a383737646e653735643464376c307236356432373530707718102200"; +// +// #[test] +// fn test_balance_reconstruct() { +// struct TestCase { +// addr: String, +// coins: Vec<(String, String)>, +// } +// let test_cases: Vec = vec![ +// TestCase { +// addr: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), +// coins: vec![("uosmo".to_string(), "100".to_string())], +// }, +// TestCase { +// addr: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), +// coins: vec![ +// ("uosmo".to_string(), "100".to_string()), +// ("uatom".to_string(), "500".to_string()), +// ("uluna".to_string(), "80".to_string()), +// ], +// }, +// TestCase { +// addr: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), +// coins: vec![("uluna".to_string(), "".to_string())], +// }, +// ]; +// +// for ts in test_cases { +// let mut st_values: Vec = vec![]; +// +// let converted_addr_bytes = decode_and_convert(ts.addr.as_str()).unwrap(); +// for coin in &ts.coins { +// let balance_key = +// create_account_denom_balance_key(converted_addr_bytes.clone(), &coin.0).unwrap(); +// +// let s = StorageValue { +// storage_prefix: "".to_string(), +// key: Binary::new(balance_key), +// value: Binary::new(coin.1.clone().into_bytes()), +// }; +// st_values.push(s); +// } +// +// let balances = Balances::reconstruct(&st_values).unwrap(); +// assert_eq!(balances.coins.len(), ts.coins.len()); +// for (i, coin) in balances.coins.iter().enumerate() { +// assert_eq!(coin.denom, ts.coins[i].0); +// // special testcase where value is an empty string +// if ts.coins[i].1.is_empty() { +// assert_eq!(coin.amount, Uint128::zero()); +// continue; +// } +// assert_eq!(coin.amount, Uint128::from_str(&ts.coins[i].1).unwrap()) +// } +// } +// } +// +// #[test] +// fn test_bank_total_supply_reconstruct() { +// struct TestValue { +// denom: String, +// amount: String, +// } +// struct TestCase { +// values: Vec, +// } +// +// let test_cases: Vec = vec![ +// TestCase { +// values: vec![TestValue { +// denom: "uatom".to_string(), +// amount: "100".to_string(), +// }], +// }, +// TestCase { +// values: vec![ +// TestValue { +// denom: "uatom".to_string(), +// amount: "100".to_string(), +// }, +// TestValue { +// denom: "uosmo".to_string(), +// amount: "200".to_string(), +// }, +// ], +// }, +// TestCase { values: vec![] }, +// ]; +// +// for ts in test_cases { +// let mut st_values: Vec = vec![]; +// +// for case in &ts.values { +// let denom_key = create_total_denom_key(case.denom.as_str()).unwrap(); +// let s = StorageValue { +// storage_prefix: "".to_string(), +// key: Binary::new(denom_key), +// value: Binary::new(case.amount.as_bytes().to_vec()), +// }; +// st_values.push(s); +// } +// +// let total_supply = TotalSupply::reconstruct(&st_values).unwrap(); +// assert_eq!(total_supply.coins.len(), ts.values.len()); +// for (i, coin) in total_supply.coins.iter().enumerate() { +// assert_eq!(coin.denom, ts.values[i].denom); +// assert_eq!( +// coin.amount, +// Uint128::from_str(ts.values[i].amount.as_str()).unwrap() +// ) +// } +// } +// } +// +// #[test] +// fn test_staking_validators_reconstruct() { +// struct TestCase { +// validators: Vec, +// expected_result: NeutronResult, +// } +// +// let test_cases: Vec = vec![ +// TestCase { +// validators: vec![Validator { +// operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), +// consensus_pubkey: None, +// jailed: false, +// status: 0, +// tokens: "1000000000000000000".to_string(), +// delegator_shares: "1000000000000000000".to_string(), +// description: None, +// unbonding_height: 0, +// unbonding_time: None, +// commission: None, +// min_self_delegation: "".to_string(), +// }], +// expected_result: Ok(StakingValidator { +// validators: vec![ContractValidator { +// operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3" +// .to_string(), +// status: 0, +// consensus_pubkey: None, +// tokens: "1000000000000000000".to_string(), +// delegator_shares: "1000000000000000000".to_string(), +// moniker: None, +// identity: None, +// website: None, +// security_contact: None, +// details: None, +// unbonding_height: 0, +// unbonding_time: None, +// rate: None, +// max_rate: None, +// max_change_rate: None, +// update_time: None, +// min_self_delegation: Decimal::from_str("0").unwrap(), +// jailed: false, +// }], +// }), +// }, +// TestCase { +// validators: vec![Validator { +// operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), +// consensus_pubkey: Some(prost_types::Any { +// type_url: "consensus_pubkey".to_string(), +// value: vec![], +// }), +// jailed: false, +// status: 0, +// tokens: "1000000000000000000".to_string(), +// delegator_shares: "1000000000000000000".to_string(), +// description: Some(Description { +// moniker: "Test validator".to_string(), +// identity: "JHFDHHFHF".to_string(), +// website: "https://neutron.org".to_string(), +// security_contact: "".to_string(), +// details: "Validator details".to_string(), +// }), +// unbonding_height: 0, +// unbonding_time: Some(prost_types::Timestamp { +// seconds: 1203981203, +// nanos: 123123, +// }), +// commission: Some(Commission { +// commission_rates: Some(CommissionRates { +// rate: "5000000000000000000".to_string(), // Dec(5) is 5+18 zeros +// max_rate: "20000000000000000000".to_string(), // Dec(20) is 20+18 zeros +// max_change_rate: "1000000000000000000".to_string(), // Dec(1) is 1+18 zeros +// }), +// update_time: Some(prost_types::Timestamp { +// seconds: 56324234, +// nanos: 1343, +// }), +// }), +// min_self_delegation: "".to_string(), +// }], +// expected_result: Ok(StakingValidator { +// validators: vec![ContractValidator { +// operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3" +// .to_string(), +// status: 0, +// consensus_pubkey: Some(vec![]), +// tokens: "1000000000000000000".to_string(), +// delegator_shares: "1000000000000000000".to_string(), +// moniker: Some("Test validator".to_string()), +// identity: Some("JHFDHHFHF".to_string()), +// website: Some("https://neutron.org".to_string()), +// security_contact: Some("".to_string()), +// details: Some("Validator details".to_string()), +// unbonding_height: 0, +// unbonding_time: Some(1203981203), +// rate: Some(Decimal::from_str("5").unwrap()), +// max_rate: Some(Decimal::from_str("20").unwrap()), +// max_change_rate: Some(Decimal::from_str("1").unwrap()), +// update_time: Some(56324234), +// min_self_delegation: Decimal::from_str("0").unwrap(), +// jailed: false, +// }], +// }), +// }, +// TestCase { +// validators: vec![ +// Validator { +// operator_address: "cosmosvaloper132juzk0gdmwuxvx4phug7m3ymyatxlh9734g4w" +// .to_string(), +// consensus_pubkey: Some(prost_types::Any { +// type_url: "consensus_pubkey".to_string(), +// value: vec![1u8, 2u8, 3u8, 4u8], +// }), +// jailed: false, +// status: 0, +// tokens: "1000000000000000000".to_string(), +// delegator_shares: "1000000000000000000".to_string(), +// description: None, +// unbonding_height: 0, +// unbonding_time: None, +// commission: None, +// min_self_delegation: "".to_string(), +// }, +// Validator { +// operator_address: "cosmosvaloper1sjllsnramtg3ewxqwwrwjxfgc4n4ef9u2lcnj0" +// .to_string(), +// consensus_pubkey: None, +// jailed: false, +// status: 0, +// tokens: "2000000000000000000".to_string(), +// delegator_shares: "3000000000000000000".to_string(), +// description: None, +// unbonding_height: 0, +// unbonding_time: None, +// commission: None, +// min_self_delegation: "".to_string(), +// }, +// ], +// expected_result: Ok(StakingValidator { +// validators: vec![ +// ContractValidator { +// operator_address: "cosmosvaloper132juzk0gdmwuxvx4phug7m3ymyatxlh9734g4w" +// .to_string(), +// status: 0, +// consensus_pubkey: Some(vec![1u8, 2u8, 3u8, 4u8]), +// tokens: "1000000000000000000".to_string(), +// delegator_shares: "1000000000000000000".to_string(), +// moniker: None, +// identity: None, +// website: None, +// security_contact: None, +// details: None, +// unbonding_height: 0, +// unbonding_time: None, +// rate: None, +// max_rate: None, +// max_change_rate: None, +// update_time: None, +// min_self_delegation: Decimal::from_str("0").unwrap(), +// jailed: false, +// }, +// ContractValidator { +// operator_address: "cosmosvaloper1sjllsnramtg3ewxqwwrwjxfgc4n4ef9u2lcnj0" +// .to_string(), +// status: 0, +// consensus_pubkey: None, +// tokens: "2000000000000000000".to_string(), +// delegator_shares: "3000000000000000000".to_string(), +// moniker: None, +// identity: None, +// website: None, +// security_contact: None, +// details: None, +// unbonding_height: 0, +// unbonding_time: None, +// rate: None, +// max_rate: None, +// max_change_rate: None, +// update_time: None, +// min_self_delegation: Decimal::from_str("0").unwrap(), +// jailed: false, +// }, +// ], +// }), +// }, +// TestCase { +// validators: vec![], +// expected_result: Ok(StakingValidator { validators: vec![] }), +// }, +// ]; +// +// for ts in test_cases { +// let mut st_values: Vec = vec![]; +// +// for validator in &ts.validators { +// let val_addr = decode_and_convert(validator.operator_address.as_str()).unwrap(); +// +// let validator_key = create_validator_key(&val_addr).unwrap(); +// let s = StorageValue { +// storage_prefix: "".to_string(), +// key: Binary::new(validator_key), +// value: Binary::new(validator.encode_to_vec()), +// }; +// st_values.push(s); +// } +// +// let stakin_validator = StakingValidator::reconstruct(&st_values); +// +// assert_eq!(stakin_validator, ts.expected_result) +// } +// } +// +// #[test] +// fn test_validators_signing_infos_reconstruct() { +// struct TestCase { +// signing_infos: Vec, +// expected_result: NeutronResult, +// } +// +// let test_cases: Vec = vec![ +// TestCase { +// signing_infos: vec![CosmosValidatorSigningInfo { +// address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), +// start_height: 1, +// index_offset: 1, +// jailed_until: None, +// tombstoned: false, +// missed_blocks_counter: 987675, +// }], +// expected_result: Ok(SigningInfo { +// signing_infos: vec![ValidatorSigningInfo { +// address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), +// start_height: 1, +// index_offset: 1, +// jailed_until: None, +// tombstoned: false, +// missed_blocks_counter: 987675, +// }], +// }), +// }, +// TestCase { +// signing_infos: vec![CosmosValidatorSigningInfo { +// address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), +// start_height: 1, +// index_offset: 1, +// jailed_until: Some(prost_types::Timestamp { +// seconds: 321654, +// nanos: 123123, +// }), +// tombstoned: false, +// missed_blocks_counter: 987675, +// }], +// expected_result: Ok(SigningInfo { +// signing_infos: vec![ValidatorSigningInfo { +// address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), +// start_height: 1, +// index_offset: 1, +// jailed_until: Some(321654), +// tombstoned: false, +// missed_blocks_counter: 987675, +// }], +// }), +// }, +// TestCase { +// signing_infos: vec![ +// CosmosValidatorSigningInfo { +// address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), +// start_height: 1, +// index_offset: 1, +// jailed_until: None, +// tombstoned: true, +// missed_blocks_counter: 987675, +// }, +// CosmosValidatorSigningInfo { +// address: "cosmosvalcons16tnak7apushwznnd3wtku8gm0rt3xytz6ut006".to_string(), +// start_height: 1, +// index_offset: 1, +// jailed_until: Some(prost_types::Timestamp { +// seconds: 321654, +// nanos: 123123, +// }), +// tombstoned: false, +// missed_blocks_counter: 345012, +// }, +// ], +// expected_result: Ok(SigningInfo { +// signing_infos: vec![ +// ValidatorSigningInfo { +// address: "cosmosvalcons1yjf46k064988jdjje068zmrqg8xh4fqqe2wwnl".to_string(), +// start_height: 1, +// index_offset: 1, +// jailed_until: None, +// tombstoned: true, +// missed_blocks_counter: 987675, +// }, +// ValidatorSigningInfo { +// address: "cosmosvalcons16tnak7apushwznnd3wtku8gm0rt3xytz6ut006".to_string(), +// start_height: 1, +// index_offset: 1, +// jailed_until: Some(321654), +// tombstoned: false, +// missed_blocks_counter: 345012, +// }, +// ], +// }), +// }, +// TestCase { +// signing_infos: vec![], +// expected_result: Ok(SigningInfo { +// signing_infos: vec![], +// }), +// }, +// ]; +// +// for ts in test_cases { +// let mut st_values: Vec = vec![]; +// +// for info in &ts.signing_infos { +// let val_addr = decode_and_convert(info.address.as_str()).unwrap(); +// +// let signing_info_key = create_validator_signing_info_key(&val_addr).unwrap(); +// let s = StorageValue { +// storage_prefix: "".to_string(), +// key: Binary::new(signing_info_key), +// value: Binary::new(info.encode_to_vec()), +// }; +// st_values.push(s); +// } +// +// let signing_infos = SigningInfo::reconstruct(&st_values); +// +// assert_eq!(signing_infos, ts.expected_result) +// } +// } +// +// #[test] +// fn test_government_proposals_reconstruct() { +// struct TestCase { +// proposals: Vec, +// expected_result: NeutronResult, +// } +// +// let test_cases: Vec = vec![ +// TestCase { +// proposals: vec![CosmosProposal { +// proposal_id: 1, +// content: Some(prost_types::Any { +// type_url: "proposal_type".to_string(), +// value: vec![], +// }), +// status: 1, +// final_tally_result: None, +// submit_time: None, +// deposit_end_time: None, +// total_deposit: vec![Coin { +// amount: "100000".to_string(), +// denom: "stake".to_string(), +// }], +// voting_start_time: None, +// voting_end_time: None, +// }], +// expected_result: Ok(GovernmentProposal { +// proposals: vec![Proposal { +// proposal_id: 1, +// proposal_type: Some("proposal_type".to_string()), +// total_deposit: vec![StdCoin::new(100000u128, "stake")], +// status: 1, +// submit_time: None, +// deposit_end_time: None, +// voting_start_time: None, +// voting_end_time: None, +// final_tally_result: None, +// }], +// }), +// }, +// TestCase { +// proposals: vec![CosmosProposal { +// proposal_id: 1, +// content: Some(prost_types::Any { +// type_url: "proposal_type".to_string(), +// value: vec![], +// }), +// status: 1, +// final_tally_result: Some(CosmosTallyResult { +// abstain: "1".to_string(), +// no: "2".to_string(), +// no_with_veto: "3".to_string(), +// yes: "4".to_string(), +// }), +// submit_time: Some(prost_types::Timestamp { +// seconds: 2222222, +// nanos: 123123, +// }), +// deposit_end_time: Some(prost_types::Timestamp { +// seconds: 3333333, +// nanos: 123123, +// }), +// total_deposit: vec![Coin { +// amount: "100000".to_string(), +// denom: "stake".to_string(), +// }], +// voting_start_time: Some(prost_types::Timestamp { +// seconds: 4444444, +// nanos: 123123, +// }), +// voting_end_time: Some(prost_types::Timestamp { +// seconds: 555555555, +// nanos: 123123, +// }), +// }], +// expected_result: Ok(GovernmentProposal { +// proposals: vec![Proposal { +// proposal_id: 1, +// proposal_type: Some("proposal_type".to_string()), +// total_deposit: vec![StdCoin::new(100000u128, "stake")], +// status: 1, +// submit_time: Some(2222222), +// deposit_end_time: Some(3333333), +// voting_start_time: Some(4444444), +// voting_end_time: Some(555555555), +// final_tally_result: Some(TallyResult { +// abstain: Uint128::from(1u128), +// no: Uint128::from(2u128), +// no_with_veto: Uint128::from(3u128), +// yes: Uint128::from(4u128), +// }), +// }], +// }), +// }, +// TestCase { +// proposals: vec![ +// CosmosProposal { +// proposal_id: 1, +// content: Some(prost_types::Any { +// type_url: "proposal_type1".to_string(), +// value: vec![], +// }), +// status: 1, +// final_tally_result: None, +// submit_time: None, +// deposit_end_time: None, +// total_deposit: vec![Coin { +// amount: "100000".to_string(), +// denom: "stake".to_string(), +// }], +// voting_start_time: None, +// voting_end_time: None, +// }, +// CosmosProposal { +// proposal_id: 2, +// content: Some(prost_types::Any { +// type_url: "proposal_type2".to_string(), +// value: vec![], +// }), +// status: 1, +// final_tally_result: None, +// submit_time: None, +// deposit_end_time: None, +// total_deposit: vec![Coin { +// amount: "200000".to_string(), +// denom: "osmo".to_string(), +// }], +// voting_start_time: None, +// voting_end_time: None, +// }, +// ], +// expected_result: Ok(GovernmentProposal { +// proposals: vec![ +// Proposal { +// proposal_id: 1, +// proposal_type: Some("proposal_type1".to_string()), +// total_deposit: vec![StdCoin::new(100000u128, "stake")], +// status: 1, +// submit_time: None, +// deposit_end_time: None, +// voting_start_time: None, +// voting_end_time: None, +// final_tally_result: None, +// }, +// Proposal { +// proposal_id: 2, +// proposal_type: Some("proposal_type2".to_string()), +// total_deposit: vec![StdCoin::new(200000u128, "osmo")], +// status: 1, +// submit_time: None, +// deposit_end_time: None, +// voting_start_time: None, +// voting_end_time: None, +// final_tally_result: None, +// }, +// ], +// }), +// }, +// TestCase { +// proposals: vec![], +// expected_result: Ok(GovernmentProposal { proposals: vec![] }), +// }, +// ]; +// +// for ts in test_cases { +// let mut st_values: Vec = vec![]; +// +// for proposal in &ts.proposals { +// let proposal_key = create_gov_proposal_key(proposal.proposal_id).unwrap(); +// let s = StorageValue { +// storage_prefix: "".to_string(), +// key: Binary::new(proposal_key), +// value: Binary::new(proposal.encode_to_vec()), +// }; +// st_values.push(s); +// } +// +// let gov_proposal = GovernmentProposal::reconstruct(&st_values); +// +// assert_eq!(gov_proposal, ts.expected_result) +// } +// } +// +// #[test] +// fn test_fee_pool_reconstruct() { +// struct TestCase { +// coins: Vec<(String, Uint128)>, +// } +// let test_cases: Vec = vec![ +// TestCase { +// coins: vec![("uosmo".to_string(), Uint128::from(100u128))], +// }, +// TestCase { +// coins: vec![ +// ("uosmo".to_string(), Uint128::from(100u128)), +// ("uatom".to_string(), Uint128::from(500u128)), +// ("uluna".to_string(), Uint128::from(80u128)), +// ], +// }, +// TestCase { coins: vec![] }, +// ]; +// +// for ts in test_cases { +// let mut coins: Vec = vec![]; +// +// for coin in &ts.coins { +// let balance_amount = DecCoin { +// denom: coin.0.clone(), +// amount: coin +// .1 +// .mul(Uint128::one().mul(Uint128::from(10u64).pow(DECIMAL_PLACES))) // adjust to Dec gogo proto format +// .to_string(), +// }; +// +// coins.push(balance_amount); +// } +// +// let fee_pool = CosmosFeePool { +// community_pool: coins, +// }; +// +// let fee_pool_key = create_fee_pool_key().unwrap(); +// +// let st_value = StorageValue { +// storage_prefix: "".to_string(), +// key: Binary::new(fee_pool_key), +// value: Binary::new(fee_pool.encode_to_vec()), +// }; +// +// let fee_pool_coins = FeePool::reconstruct(&[st_value]).unwrap(); +// assert_eq!(fee_pool_coins.coins.len(), ts.coins.len()); +// for (i, coin) in fee_pool_coins.coins.iter().enumerate() { +// assert_eq!(coin.denom, ts.coins[i].0); +// assert_eq!(coin.amount, ts.coins[i].1) +// } +// } +// } +// +// #[test] +// fn test_delegations_reconstruct() { +// struct TestCase { +// staking_params: Params, +// delegations: Vec, +// validators: Vec, +// expected_result: NeutronResult, +// } +// let test_cases: Vec = vec![ +// TestCase { +// staking_params: Params { +// unbonding_time: None, +// max_validators: 0, +// max_entries: 0, +// historical_entries: 0, +// bond_denom: "stake".to_string(), +// min_commission_rate: "".to_string(), +// }, +// delegations: vec![Delegation { +// delegator_address: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), +// validator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), +// shares: "1000000000000000000".to_string(), +// }], +// validators: vec![Validator { +// operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), +// consensus_pubkey: None, +// jailed: false, +// status: 0, +// tokens: "1000000000000000000".to_string(), +// delegator_shares: "1000000000000000000".to_string(), +// description: None, +// unbonding_height: 0, +// unbonding_time: None, +// commission: None, +// min_self_delegation: "".to_string(), +// }], +// expected_result: Ok(Delegations { +// delegations: vec![StdDelegation { +// delegator: Addr::unchecked("osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs"), +// validator: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), +// amount: StdCoin::new(1000000000000000000u128, "stake"), +// }], +// }), +// }, +// TestCase { +// staking_params: Params { +// unbonding_time: None, +// max_validators: 0, +// max_entries: 0, +// historical_entries: 0, +// bond_denom: "stake".to_string(), +// min_commission_rate: "".to_string(), +// }, +// delegations: vec![ +// Delegation { +// delegator_address: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), +// validator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3" +// .to_string(), +// shares: "1000000000000000000".to_string(), +// }, +// Delegation { +// delegator_address: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), +// validator_address: "osmovaloper1lzhlnpahvznwfv4jmay2tgaha5kmz5qxwmj9we" +// .to_string(), +// shares: "1000000000000000000".to_string(), +// }, +// ], +// validators: vec![ +// Validator { +// operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3" +// .to_string(), +// consensus_pubkey: None, +// jailed: false, +// status: 0, +// tokens: "1000000000000000000".to_string(), +// delegator_shares: "1000000000000000000".to_string(), +// description: None, +// unbonding_height: 0, +// unbonding_time: None, +// commission: None, +// min_self_delegation: "".to_string(), +// }, +// Validator { +// operator_address: "osmovaloper1lzhlnpahvznwfv4jmay2tgaha5kmz5qxwmj9we" +// .to_string(), +// consensus_pubkey: None, +// jailed: false, +// status: 0, +// tokens: "1000000000000000000".to_string(), +// delegator_shares: "1000000000000000000".to_string(), +// description: None, +// unbonding_height: 0, +// unbonding_time: None, +// commission: None, +// min_self_delegation: "".to_string(), +// }, +// ], +// expected_result: Ok(Delegations { +// delegations: vec![ +// StdDelegation { +// delegator: Addr::unchecked("osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs"), +// validator: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), +// amount: StdCoin::new(1000000000000000000u128, "stake"), +// }, +// StdDelegation { +// delegator: Addr::unchecked("osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs"), +// validator: "osmovaloper1lzhlnpahvznwfv4jmay2tgaha5kmz5qxwmj9we".to_string(), +// amount: StdCoin::new(1000000000000000000u128, "stake"), +// }, +// ], +// }), +// }, +// TestCase { +// staking_params: Params { +// unbonding_time: None, +// max_validators: 0, +// max_entries: 0, +// historical_entries: 0, +// bond_denom: "stake".to_string(), +// min_commission_rate: "".to_string(), +// }, +// delegations: vec![], +// validators: vec![], +// expected_result: Ok(Delegations { +// delegations: vec![], +// }), +// }, +// TestCase { +// staking_params: Default::default(), +// delegations: vec![], +// validators: vec![], +// expected_result: Err(NeutronError::InvalidQueryResultFormat( +// "params is empty".into(), +// )), +// }, +// TestCase { +// staking_params: Params { +// unbonding_time: None, +// max_validators: 0, +// max_entries: 0, +// historical_entries: 0, +// bond_denom: "stake".to_string(), +// min_commission_rate: "".to_string(), +// }, +// delegations: vec![Delegation { +// delegator_address: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), +// validator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), +// shares: "1000000000000000000".to_string(), +// }], +// validators: vec![], +// expected_result: Err(NeutronError::InvalidQueryResultFormat( +// "validator is empty".into(), +// )), +// }, +// ]; +// +// for ts in &test_cases { +// // prepare storage values +// let mut st_values: Vec = vec![StorageValue { +// storage_prefix: STAKING_STORE_KEY.to_string(), +// key: Binary::new(vec![STAKING_PARAMS_KEY]), +// value: { +// if ts.staking_params.bond_denom.is_empty() { +// return Default::default(); +// } +// Binary::from(ts.staking_params.encode_to_vec()) +// }, +// }]; +// +// for (i, d) in ts.delegations.iter().enumerate() { +// let delegator_addr = decode_and_convert(&d.delegator_address).unwrap(); +// let val_addr = decode_and_convert(&d.validator_address).unwrap(); +// +// st_values.push(StorageValue { +// storage_prefix: STAKING_STORE_KEY.to_string(), +// key: Binary::new(create_delegation_key(&delegator_addr, &val_addr).unwrap()), +// value: Binary::from(d.encode_to_vec()), +// }); +// +// if let Some(v) = ts.validators.get(i) { +// st_values.push(StorageValue { +// storage_prefix: STAKING_STORE_KEY.to_string(), +// key: Binary::new(create_validator_key(&val_addr).unwrap()), +// value: Binary::from(v.encode_to_vec()), +// }); +// } +// } +// +// // test reconstruction +// let delegations = Delegations::reconstruct(&st_values); +// +// assert_eq!(delegations, ts.expected_result) +// } +// } +// +// #[test] +// fn test_balance_reconstruct_from_hex() { +// let bytes = hex::decode(BALANCES_HEX_RESPONSE).unwrap(); // decode hex string to bytes +// let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string +// +// let s = StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::new(create_account_denom_balance_key("addr", "uatom").unwrap()), +// value: Binary::from_base64(base64_input.as_str()).unwrap(), +// }; +// let bank_balances = Balances::reconstruct(&[s]).unwrap(); +// assert_eq!( +// bank_balances, +// Balances { +// coins: vec![StdCoin::new(494213561u128, "uatom")] +// } +// ); +// } +// +// #[test] +// fn test_balance_reconstruct_from_empty_value() { +// let s = StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::new(create_account_denom_balance_key("addr", "uatom").unwrap()), +// value: Binary::from(vec![]), +// }; +// let bank_balances = Balances::reconstruct(&[s]).unwrap(); +// assert_eq!( +// bank_balances, +// Balances { +// coins: vec![StdCoin::new(0u128, "uatom")] +// } +// ); +// } +// +// #[test] +// fn test_bank_total_supply_reconstruct_from_hex() { +// let bytes = hex::decode(TOTAL_SUPPLY_HEX_RESPONSE).unwrap(); // decode hex string to bytes +// let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string +// +// let s = StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::new(create_total_denom_key("stake").unwrap()), +// value: Binary::from_base64(base64_input.as_str()).unwrap(), +// }; +// let total_supply = TotalSupply::reconstruct(&[s]).unwrap(); +// assert_eq!( +// total_supply, +// TotalSupply { +// coins: vec![StdCoin { +// denom: String::from("stake"), +// amount: Uint128::from(1644171988905769u64), // mutating +// }] +// } +// ); +// } +// +// #[test] +// fn test_delegations_reconstruct_overflow() { +// struct TestCase { +// staking_params: Params, +// delegations: Vec, +// validators: Vec, +// expected_result: NeutronResult, +// } +// let test_cases: Vec = vec![TestCase { +// staking_params: Params { +// unbonding_time: None, +// max_validators: 0, +// max_entries: 0, +// historical_entries: 0, +// bond_denom: "stake".to_string(), +// min_commission_rate: "".to_string(), +// }, +// delegations: vec![Delegation { +// delegator_address: "osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs".to_string(), +// validator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), +// shares: "340282366920938463463".to_string(), +// }], +// validators: vec![Validator { +// operator_address: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), +// consensus_pubkey: None, +// jailed: false, +// status: 0, +// tokens: "340282366920938463463".to_string(), +// delegator_shares: "340282366920938463463".to_string(), +// description: None, +// unbonding_height: 0, +// unbonding_time: None, +// commission: None, +// min_self_delegation: "".to_string(), +// }], +// expected_result: Ok(Delegations { +// delegations: vec![StdDelegation { +// delegator: Addr::unchecked("osmo1yz54ncxj9csp7un3xled03q6thrrhy9cztkfzs"), +// validator: "osmovaloper1r2u5q6t6w0wssrk6l66n3t2q3dw2uqny4gj2e3".to_string(), +// amount: StdCoin::new(340282366920938463463u128, "stake"), +// }], +// }), +// }]; +// +// for ts in &test_cases { +// // prepare storage values +// let mut st_values: Vec = vec![StorageValue { +// storage_prefix: STAKING_STORE_KEY.to_string(), +// key: Binary::new(create_params_store_key(STAKING_STORE_KEY, KEY_BOND_DENOM)), +// value: { +// if ts.staking_params.bond_denom.is_empty() { +// return Default::default(); +// } +// Binary::from(ts.staking_params.encode_to_vec()) +// }, +// }]; +// +// for (i, d) in ts.delegations.iter().enumerate() { +// let delegator_addr = decode_and_convert(&d.delegator_address).unwrap(); +// let val_addr = decode_and_convert(&d.validator_address).unwrap(); +// +// st_values.push(StorageValue { +// storage_prefix: STAKING_STORE_KEY.to_string(), +// key: Binary::new(create_delegation_key(&delegator_addr, &val_addr).unwrap()), +// value: Binary::from(d.encode_to_vec()), +// }); +// +// if let Some(v) = ts.validators.get(i) { +// st_values.push(StorageValue { +// storage_prefix: STAKING_STORE_KEY.to_string(), +// key: Binary::new(create_validator_key(&val_addr).unwrap()), +// value: Binary::from(v.encode_to_vec()), +// }); +// } +// } +// +// // test reconstruction +// let delegations = Delegations::reconstruct(&st_values); +// +// assert_eq!(delegations, ts.expected_result) +// } +// } +// +// #[test] +// fn test_staking_validators_reconstruct_from_hex() { +// let bytes = hex::decode(STAKING_VALIDATOR_HEX_RESPONSE).unwrap(); // decode hex string to bytes +// let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string +// +// let s = StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::default(), // not used in reconstruct +// value: Binary::from_base64(base64_input.as_str()).unwrap(), +// }; +// let staking_validator = StakingValidator::reconstruct(&[s]).unwrap(); +// assert_eq!( +// staking_validator, +// StakingValidator { +// validators: vec![ContractValidator { +// operator_address: String::from( +// "cosmosvaloper10v6wvdenee8r9l6wlsphcgur2ltl8ztkfrvj9a" // mutating +// ), +// consensus_pubkey: Some(vec![ +// 10, 32, 218, 63, 141, 144, 164, 7, 3, 27, 183, 234, 247, 110, 203, 91, 3, 28, +// 150, 72, 121, 152, 226, 238, 124, 103, 153, 82, 34, 206, 253, 59, 50, 145, +// ]), +// jailed: false, +// status: 3, +// tokens: String::from("250028274052364"), +// delegator_shares: String::from("250028274052364000000000000000000"), +// moniker: Some(String::from("earth 🌎")), +// identity: Some(String::from("Coinbase Custody")), +// website: Some(String::from("hypha.coop")), +// security_contact: Some(String::from("")), +// details: Some(String::from("A testnet validator")), +// unbonding_height: 1841908u64, +// unbonding_time: Some(1590982547u64), +// rate: Some(Decimal::from_str("0.200000000000000000").unwrap()), +// max_rate: Some(Decimal::from_str("1.00000000000000000").unwrap()), +// max_change_rate: Some(Decimal::from_str("1.000000000000000000").unwrap()), +// update_time: Some(1580862591u64), // mutating +// min_self_delegation: Decimal::from_str("1000000").unwrap(), +// }] +// } +// ); +// } +// +// #[test] +// fn test_validators_signing_infos_reconstruct_from_hex() { +// let bytes = hex::decode(VALIDATOR_SIGNING_INFO_HEX_RESPONSE).unwrap(); // decode hex string to bytes +// let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string +// +// let s = StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::default(), // not used in reconstruct +// value: Binary::from_base64(base64_input.as_str()).unwrap(), +// }; +// let signing_info = SigningInfo::reconstruct(&[s]).unwrap(); +// assert_eq!( +// signing_info, +// SigningInfo { +// signing_infos: vec![ValidatorSigningInfo { +// address: "cosmosvalcons19f53fqq28v6pmz877dne75d4d7l0r65d2750pw".to_string(), +// start_height: 0, +// index_offset: 16, +// jailed_until: Some(0), +// tombstoned: false, +// missed_blocks_counter: 0, +// }] +// } +// ); +// } +// +// #[test] +// fn test_government_proposals_reconstruct_from_hex() { +// let bytes = hex::decode(GOV_PROPOSAL_HEX_RESPONSE).unwrap(); // decode hex string to bytes +// let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string +// +// let s = StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::default(), // not used in reconstruct +// value: Binary::from_base64(base64_input.as_str()).unwrap(), +// }; +// let proposals = GovernmentProposal::reconstruct(&[s]).unwrap(); +// assert_eq!( +// proposals, +// GovernmentProposal { +// proposals: vec![Proposal { +// proposal_id: 1u64, +// proposal_type: Some(String::from("/cosmos.gov.v1.MsgExecLegacyContent")), +// total_deposit: vec![StdCoin { +// denom: String::from("uatom"), +// amount: Uint128::from(512100000u64), +// }], +// status: 3i32, +// submit_time: Some(1553064087u64), // mutating +// deposit_end_time: Some(1554273687u64), // mutating +// voting_start_time: Some(1553114639u64), // 0001-01-01T00:00:00Z +// voting_end_time: Some(1554324239u64), // 0001-01-01T00:00:00Z +// final_tally_result: Some(TallyResult { +// yes: Uint128::from(97118903526799u128), +// no: Uint128::from(320545400000u128), +// abstain: Uint128::from(402380577234u128), +// no_with_veto: Uint128::zero(), +// }), +// }] +// } +// ); +// } +// +// #[test] +// fn test_fee_pool_reconstruct_from_hex() { +// let bytes = hex::decode(FEE_POOL_HEX_RESPONSE).unwrap(); // decode hex string to bytes +// let base64_input = BASE64_STANDARD.encode(bytes); // encode bytes to base64 string +// +// let s = StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::default(), // not used in reconstruct +// value: Binary::from_base64(base64_input.as_str()).unwrap(), +// }; +// let fee_pool = FeePool::reconstruct(&[s]).unwrap(); +// assert_eq!( +// fee_pool, +// FeePool { +// coins: vec![ +// StdCoin { +// denom: String::from( +// "ibc/12DA42304EE1CE96071F712AA4D58186AD11C3165C0DCDA71E017A54F3935E66" +// ), +// amount: Uint128::from(444252217u64), // mutating +// }, +// StdCoin { +// denom: String::from( +// "ibc/14F9BC3E44B8A9C1BE1FB08980FAB87034C9905EF17CF2F5008FC085218811CC" +// ), +// amount: Uint128::from(189753432u64), // mutating +// }, +// StdCoin { +// denom: String::from( +// "ibc/1FBDD58D438B4D04D26CBFB2E722C18984A0F1A52468C4F42F37D102F3D3F399" +// ), +// amount: Uint128::from(25455348u64), // mutating +// }, +// StdCoin { +// denom: String::from( +// "ibc/2181AAB0218EAC24BC9F86BD1364FBBFA3E6E3FCC25E88E3E68C15DC6E752D86" +// ), +// amount: Uint128::from(89764472u64), // mutating +// }, +// StdCoin { +// denom: String::from( +// "ibc/2717109A95559F3A17EFC0C897B7691E22A227B30FC3C5CE7A7CE88481629704" +// ), +// amount: Uint128::from(9000u64), // mutating +// }, +// StdCoin { +// denom: String::from( +// "ibc/42E47A5BA708EBE6E0C227006254F2784E209F4DBD3C6BB77EDC4B29EF875E8E" +// ), +// amount: Uint128::from(2325668920u64), // mutating +// }, +// StdCoin { +// denom: String::from( +// "ibc/81D08BC39FB520EBD948CF017910DD69702D34BF5AC160F76D3B5CFC444EBCE0" +// ), +// amount: Uint128::from(33639955u64), // mutating +// }, +// StdCoin { +// denom: String::from("theta"), +// amount: Uint128::from(1u64), // mutating +// }, +// StdCoin { +// denom: String::from("uatom"), +// amount: Uint128::from(13538430938055u64), // mutating +// }, +// ] +// } +// ); +// } +// +// #[test] +// fn test_delegations_reconstruct_from_hex() { +// let staking_params_bytes = hex::decode(STAKING_PARAMS_HEX_RESPONSE).unwrap(); // decode hex string to bytes +// let staking_params_base64_input = BASE64_STANDARD.encode(staking_params_bytes); // encode bytes to base64 string +// let staking_validator_bytes = hex::decode(STAKING_VALIDATOR_HEX_RESPONSE).unwrap(); // decode hex string to bytes +// let staking_validator_base64_input = BASE64_STANDARD.encode(staking_validator_bytes); // encode bytes to base64 string +// let delegation_bytes = hex::decode(DELEGATOR_DELEGATIONS_HEX_RESPONSE).unwrap(); // decode hex string to bytes +// let delegation_base64_input = BASE64_STANDARD.encode(delegation_bytes); // encode bytes to base64 string +// +// let mut st_values: Vec = vec![StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::default(), // not used in reconstruct +// value: Binary::from_base64(staking_params_base64_input.as_str()).unwrap(), +// }]; +// st_values.push(StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::default(), // not used in reconstruct +// value: Binary::from_base64(delegation_base64_input.as_str()).unwrap(), +// }); +// st_values.push(StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::default(), // not used in reconstruct +// value: Binary::from_base64(staking_validator_base64_input.as_str()).unwrap(), +// }); +// +// let delegations = Delegations::reconstruct(&st_values).unwrap(); +// assert_eq!( +// delegations, +// Delegations { +// delegations: vec![StdDelegation { +// delegator: Addr::unchecked("cosmos1pmjwm0a8pvs2m8pauyg2ruldy8ney4qn8zgd96"), // mutating +// validator: String::from("cosmosvaloper10v6wvdenee8r9l6wlsphcgur2ltl8ztkfrvj9a"), // mutating +// amount: StdCoin { +// denom: String::from("uatom"), +// amount: Uint128::from(5000u64), +// }, +// }], +// } +// ); +// } +// +// #[test] +// fn test_unbonding_delegations_reconstruct_from_hex() { +// let unbonding_delegations_bytes = +// hex::decode(DELEGATOR_UNBONDING_DELEGATIONS_HEX_RESPONSE).unwrap(); // decode hex string to bytes +// let unbonding_delegations_base64_input = BASE64_STANDARD.encode(unbonding_delegations_bytes); // encode bytes to base64 string +// +// let st_values: Vec = vec![StorageValue { +// storage_prefix: String::default(), // not used in reconstruct +// key: Binary::default(), // not used in reconstruct +// value: Binary::from_base64(unbonding_delegations_base64_input.as_str()).unwrap(), +// }]; +// +// let unbonding_delegations = UnbondingDelegations::reconstruct(&st_values).unwrap(); +// assert_eq!( +// unbonding_delegations, +// UnbondingDelegations { +// unbonding_responses: vec![UnbondingResponse { +// delegator_address: Addr::unchecked("cosmos1m9l358xunhhwds0568za49mzhvuxx9uxre5tud"), +// validator_address: String::from( +// "cosmosvaloper18hl5c9xn5dze2g50uaw0l2mr02ew57zk0auktn" +// ), +// entries: vec![ +// UnbondingEntry { +// balance: Uint128::new(10_000), +// completion_time: Some(Timestamp::from_nanos(1704872890570185206)), +// creation_height: 365, +// initial_balance: Uint128::new(10_000), +// }, +// UnbondingEntry { +// balance: Uint128::new(20_000), +// completion_time: Some(Timestamp::from_nanos(1704872903002248037)), +// creation_height: 377, +// initial_balance: Uint128::new(20_000), +// }, +// ], +// }] +// } +// ); +// } diff --git a/packages/neutron-sdk/src/interchain_queries/v047/types.rs b/packages/neutron-sdk/src/interchain_queries/v047/types.rs index 38e3a00a..a0af6517 100644 --- a/packages/neutron-sdk/src/interchain_queries/v047/types.rs +++ b/packages/neutron-sdk/src/interchain_queries/v047/types.rs @@ -1,136 +1,136 @@ -use std::ops::Div; -// import all types from v045 package -// to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual -pub use crate::interchain_queries::v045::types::*; - -// But at the same time we replace some structs from v045 with structs below to create structures -// compatible with Cosmos SDK 0.47 - -use crate::interchain_queries::types::KVReconstruct; -use crate::{bindings::types::StorageValue, errors::error::NeutronResult, NeutronError}; - -use crate::interchain_queries::helpers::uint256_to_u128; -use crate::interchain_queries::v047::helpers::deconstruct_account_denom_balance_key; -use cosmos_sdk_proto::cosmos::staking::v1beta1::{ - Delegation, Params, Validator as CosmosValidator, -}; -use cosmos_sdk_proto::traits::Message; -use cosmwasm_std::{Addr, Coin, Decimal256, Uint128, Uint256}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; -use std::str::FromStr; - -/// Key for Staking Params in the **staking** module's storage -/// -pub const STAKING_PARAMS_KEY: u8 = 0x51; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -/// A structure that can be reconstructed from **StorageValues**'s for the **Balance Interchain Query**. -/// Contains amounts of coins that are held by some account on remote chain. -pub struct Balances { - pub coins: Vec, -} - -impl KVReconstruct for Balances { - fn reconstruct(storage_values: &[StorageValue]) -> NeutronResult { - let mut coins: Vec = Vec::with_capacity(storage_values.len()); - - for kv in storage_values { - let (_, denom) = deconstruct_account_denom_balance_key(kv.key.to_vec())?; - let amount = if kv.value.is_empty() { - Uint128::zero() - } else { - Uint128::from_str(&String::from_utf8(kv.value.to_vec())?)? - }; - - coins.push(Coin::new(amount.u128(), denom)) - } - - Ok(Balances { coins }) - } -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -/// A structure that can be reconstructed from **StorageValues**'s for the **Delegator Delegation Interchain Query**. -/// Contains delegations which some delegator has on remote chain. -pub struct Delegations { - pub delegations: Vec, -} - -impl KVReconstruct for Delegations { - fn reconstruct(storage_values: &[StorageValue]) -> NeutronResult { - // We are taking 2 items chunks from starage_value to calculate one delegation - let mut delegations: Vec = Vec::with_capacity(storage_values.len() / 2); - - if storage_values.is_empty() { - return Err(NeutronError::InvalidQueryResultFormat( - "storage_values length is 0".into(), - )); - } - // first StorageValue is staking params - if storage_values[0].value.is_empty() { - // Incoming params cannot be empty, it should always be configured on chain. - // If we receive empty params, that means incoming data structure is corrupted - // and we cannot build `cosmwasm_std::Delegation`'s using this data. - return Err(NeutronError::InvalidQueryResultFormat( - "params is empty".into(), - )); - } - let params: Params = Params::decode(storage_values[0].value.as_slice())?; - - // the rest are delegations and validators alternately - for chunk in storage_values[1..].chunks(2) { - if chunk[0].value.is_empty() { - // Incoming delegation can actually be empty, this just means that delegation - // is not present on remote chain, which is to be expected. So, if it doesn't - // exist, we can safely skip this and following chunk. - continue; - } - let delegation_sdk: Delegation = Delegation::decode(chunk[0].value.as_slice())?; - - let mut delegation_std = StdDelegation { - delegator: Addr::unchecked(delegation_sdk.delegator_address.as_str()), - validator: delegation_sdk.validator_address, - amount: Default::default(), - }; - - if chunk[1].value.is_empty() { - // At this point, incoming validator cannot be empty, that would be invalid, - // because delegation is already defined, so, building `cosmwasm_std::Delegation` - // from this data is impossible, incoming data is corrupted.post - return Err(NeutronError::InvalidQueryResultFormat( - "validator is empty".into(), - )); - } - let validator: CosmosValidator = CosmosValidator::decode(chunk[1].value.as_slice())?; - - let delegation_shares = Decimal256::from_atomics( - Uint256::from_str(&delegation_sdk.shares)?, - DECIMAL_PLACES, - )?; - - let delegator_shares = Decimal256::from_atomics( - Uint256::from_str(&validator.delegator_shares)?, - DECIMAL_PLACES, - )?; - - let validator_tokens = - Decimal256::from_atomics(Uint128::from_str(&validator.tokens)?, 0)?; - - // https://github.com/cosmos/cosmos-sdk/blob/35ae2c4c72d4aeb33447d5a7af23ca47f786606e/x/staking/keeper/querier.go#L463 - // delegated_tokens = quotient(delegation.shares * validator.tokens / validator.total_shares); - let delegated_tokens = delegation_shares - .checked_mul(validator_tokens)? - .div(delegator_shares) - .atomics() - .div(Uint256::from_u128(DECIMAL_FRACTIONAL)); - - delegation_std.amount = - Coin::new(uint256_to_u128(delegated_tokens)?, ¶ms.bond_denom); - - delegations.push(delegation_std); - } - - Ok(Delegations { delegations }) - } -} +// use std::ops::Div; +// // import all types from v045 package +// // to make it available from v047 package (kinda proxy) since they work with Cosmos SDK 0.47 as usual +// pub use crate::interchain_queries::v045::types::*; +// +// // But at the same time we replace some structs from v045 with structs below to create structures +// // compatible with Cosmos SDK 0.47 +// +// use crate::interchain_queries::types::KVReconstruct; +// use crate::{bindings::types::StorageValue, errors::error::NeutronResult, NeutronError}; +// +// use crate::interchain_queries::helpers::uint256_to_u128; +// use crate::interchain_queries::v047::helpers::deconstruct_account_denom_balance_key; +// use cosmos_sdk_proto::cosmos::staking::v1beta1::{ +// Delegation, Params, Validator as CosmosValidator, +// }; +// use cosmos_sdk_proto::traits::Message; +// use cosmwasm_std::{Addr, Coin, Decimal256, Uint128, Uint256}; +// use schemars::JsonSchema; +// use serde::{Deserialize, Serialize}; +// use std::str::FromStr; +// +// /// Key for Staking Params in the **staking** module's storage +// /// +// pub const STAKING_PARAMS_KEY: u8 = 0x51; +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// /// A structure that can be reconstructed from **StorageValues**'s for the **Balance Interchain Query**. +// /// Contains amounts of coins that are held by some account on remote chain. +// pub struct Balances { +// pub coins: Vec, +// } +// +// impl KVReconstruct for Balances { +// fn reconstruct(storage_values: &[StorageValue]) -> NeutronResult { +// let mut coins: Vec = Vec::with_capacity(storage_values.len()); +// +// for kv in storage_values { +// let (_, denom) = deconstruct_account_denom_balance_key(kv.key.to_vec())?; +// let amount = if kv.value.is_empty() { +// Uint128::zero() +// } else { +// Uint128::from_str(&String::from_utf8(kv.value.to_vec())?)? +// }; +// +// coins.push(Coin::new(amount.u128(), denom)) +// } +// +// Ok(Balances { coins }) +// } +// } +// +// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] +// /// A structure that can be reconstructed from **StorageValues**'s for the **Delegator Delegation Interchain Query**. +// /// Contains delegations which some delegator has on remote chain. +// pub struct Delegations { +// pub delegations: Vec, +// } +// +// impl KVReconstruct for Delegations { +// fn reconstruct(storage_values: &[StorageValue]) -> NeutronResult { +// // We are taking 2 items chunks from starage_value to calculate one delegation +// let mut delegations: Vec = Vec::with_capacity(storage_values.len() / 2); +// +// if storage_values.is_empty() { +// return Err(NeutronError::InvalidQueryResultFormat( +// "storage_values length is 0".into(), +// )); +// } +// // first StorageValue is staking params +// if storage_values[0].value.is_empty() { +// // Incoming params cannot be empty, it should always be configured on chain. +// // If we receive empty params, that means incoming data structure is corrupted +// // and we cannot build `cosmwasm_std::Delegation`'s using this data. +// return Err(NeutronError::InvalidQueryResultFormat( +// "params is empty".into(), +// )); +// } +// let params: Params = Params::decode(storage_values[0].value.as_slice())?; +// +// // the rest are delegations and validators alternately +// for chunk in storage_values[1..].chunks(2) { +// if chunk[0].value.is_empty() { +// // Incoming delegation can actually be empty, this just means that delegation +// // is not present on remote chain, which is to be expected. So, if it doesn't +// // exist, we can safely skip this and following chunk. +// continue; +// } +// let delegation_sdk: Delegation = Delegation::decode(chunk[0].value.as_slice())?; +// +// let mut delegation_std = StdDelegation { +// delegator: Addr::unchecked(delegation_sdk.delegator_address.as_str()), +// validator: delegation_sdk.validator_address, +// amount: Default::default(), +// }; +// +// if chunk[1].value.is_empty() { +// // At this point, incoming validator cannot be empty, that would be invalid, +// // because delegation is already defined, so, building `cosmwasm_std::Delegation` +// // from this data is impossible, incoming data is corrupted.post +// return Err(NeutronError::InvalidQueryResultFormat( +// "validator is empty".into(), +// )); +// } +// let validator: CosmosValidator = CosmosValidator::decode(chunk[1].value.as_slice())?; +// +// let delegation_shares = Decimal256::from_atomics( +// Uint256::from_str(&delegation_sdk.shares)?, +// DECIMAL_PLACES, +// )?; +// +// let delegator_shares = Decimal256::from_atomics( +// Uint256::from_str(&validator.delegator_shares)?, +// DECIMAL_PLACES, +// )?; +// +// let validator_tokens = +// Decimal256::from_atomics(Uint128::from_str(&validator.tokens)?, 0)?; +// +// // https://github.com/cosmos/cosmos-sdk/blob/35ae2c4c72d4aeb33447d5a7af23ca47f786606e/x/staking/keeper/querier.go#L463 +// // delegated_tokens = quotient(delegation.shares * validator.tokens / validator.total_shares); +// let delegated_tokens = delegation_shares +// .checked_mul(validator_tokens)? +// .div(delegator_shares) +// .atomics() +// .div(Uint256::from_u128(DECIMAL_FRACTIONAL)); +// +// delegation_std.amount = +// Coin::new(uint256_to_u128(delegated_tokens)?, ¶ms.bond_denom); +// +// delegations.push(delegation_std); +// } +// +// Ok(Delegations { delegations }) +// } +// } diff --git a/packages/neutron-sdk/src/lib.rs b/packages/neutron-sdk/src/lib.rs index ac788cfc..b419643d 100644 --- a/packages/neutron-sdk/src/lib.rs +++ b/packages/neutron-sdk/src/lib.rs @@ -12,7 +12,6 @@ pub mod interchain_queries; pub mod interchain_txs; #[allow(deprecated, clippy::module_inception)] pub mod proto_types; -pub mod query; mod serde; pub mod shim; pub mod sudo; diff --git a/packages/neutron-sdk/src/query/min_ibc_fee.rs b/packages/neutron-sdk/src/query/min_ibc_fee.rs deleted file mode 100644 index 42e27c72..00000000 --- a/packages/neutron-sdk/src/query/min_ibc_fee.rs +++ /dev/null @@ -1,18 +0,0 @@ -use crate::{ - bindings::{msg::IbcFee, query::NeutronQuery}, - NeutronResult, -}; -use cosmwasm_std::Deps; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct MinIbcFeeResponse { - pub min_fee: IbcFee, -} - -pub fn query_min_ibc_fee(deps: Deps) -> NeutronResult { - let query = NeutronQuery::MinIbcFee {}; - Ok(deps.querier.query(&query.into())?) -} diff --git a/packages/neutron-sdk/src/query/mod.rs b/packages/neutron-sdk/src/query/mod.rs deleted file mode 100644 index aea5e3f8..00000000 --- a/packages/neutron-sdk/src/query/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod min_ibc_fee; -pub mod token_factory; -pub mod total_burned_neutrons; diff --git a/packages/neutron-sdk/src/query/token_factory.rs b/packages/neutron-sdk/src/query/token_factory.rs deleted file mode 100644 index 82060562..00000000 --- a/packages/neutron-sdk/src/query/token_factory.rs +++ /dev/null @@ -1,54 +0,0 @@ -use crate::{bindings::query::NeutronQuery, NeutronResult}; -use cosmwasm_std::Deps; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct FullDenomResponse { - pub denom: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct DenomAdminResponse { - pub admin: String, -} - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct BeforeSendHookResponse { - pub contract_addr: String, -} - -pub fn query_full_denom( - deps: Deps, - creator_addr: impl Into, - subdenom: impl Into, -) -> NeutronResult { - let query = NeutronQuery::FullDenom { - creator_addr: creator_addr.into(), - subdenom: subdenom.into(), - }; - Ok(deps.querier.query(&query.into())?) -} - -pub fn query_denom_admin( - deps: Deps, - subdenom: impl Into, -) -> NeutronResult { - let query = NeutronQuery::DenomAdmin { - subdenom: subdenom.into(), - }; - Ok(deps.querier.query(&query.into())?) -} - -pub fn query_before_send_hook( - deps: Deps, - denom: impl Into, -) -> NeutronResult { - let query = NeutronQuery::BeforeSendHook { - denom: denom.into(), - }; - Ok(deps.querier.query(&query.into())?) -} diff --git a/packages/neutron-sdk/src/query/total_burned_neutrons.rs b/packages/neutron-sdk/src/query/total_burned_neutrons.rs deleted file mode 100644 index 61d8fe21..00000000 --- a/packages/neutron-sdk/src/query/total_burned_neutrons.rs +++ /dev/null @@ -1,18 +0,0 @@ -use crate::{bindings::query::NeutronQuery, NeutronResult}; -use cosmwasm_std::{Coin, Deps}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub struct TotalBurnedNeutronsAmountResponse { - pub coin: Coin, -} - -/// Returns total amount of burned neutron fees -pub fn query_total_burned_neutrons( - deps: Deps, -) -> NeutronResult { - let query = NeutronQuery::TotalBurnedNeutronsAmount {}; - Ok(deps.querier.query(&query.into())?) -}