Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(minor-interchain-token-service): all chains with optional filter query message #754

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions contracts/interchain-token-service/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ pub enum Error {
QueryTokenConfig,
#[error("failed to query the status of contract")]
QueryContractStatus,
#[error("failed to query chain configs")]
QueryAllChainConfigs,
}

#[cfg_attr(not(feature = "library"), entry_point)]
Expand Down Expand Up @@ -137,6 +139,9 @@ pub fn query(deps: Deps, _: Env, msg: QueryMsg) -> Result<Binary, ContractError>
QueryMsg::AllItsContracts => {
query::all_its_contracts(deps).change_context(Error::QueryAllItsContracts)
}
QueryMsg::ItsChains { filter } => {
maancham marked this conversation as resolved.
Show resolved Hide resolved
query::its_chains(deps, filter).change_context(Error::QueryAllChainConfigs)
}
QueryMsg::TokenInstance { chain, token_id } => {
query::token_instance(deps, chain, token_id).change_context(Error::QueryTokenInstance)
}
Expand Down
30 changes: 29 additions & 1 deletion contracts/interchain-token-service/src/contract/query.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use axelar_wasm_std::{killswitch, IntoContractError};
use cosmwasm_std::{to_json_binary, Binary, Deps};
use cosmwasm_std::{to_json_binary, Binary, Deps, Order};
use error_stack::{Result, ResultExt};
use itertools::Itertools;
use router_api::ChainNameRaw;

use crate::{msg, state, TokenId};
Expand Down Expand Up @@ -34,6 +35,33 @@ pub fn all_its_contracts(deps: Deps) -> Result<Binary, Error> {
to_json_binary(&contract_addresses).change_context(Error::JsonSerialization)
}

pub fn its_chains(deps: Deps, filter: Option<msg::ChainFilter>) -> Result<Binary, Error> {
let state_chain_configs = state::load_chain_configs();

let chain_config_responses: Vec<msg::ChainConfigResponse> = state_chain_configs
maancham marked this conversation as resolved.
Show resolved Hide resolved
.range(deps.storage, None, None, Order::Ascending)
.map(|r| r.change_context(Error::State))
.map_ok(|(chain, config)| msg::ChainConfigResponse {
chain,
its_edge_contract: config.its_address,
truncation: msg::TruncationConfig {
max_uint: config.truncation.max_uint,
max_decimals_when_truncating: config.truncation.max_decimals_when_truncating,
},
frozen: config.frozen,
})
maancham marked this conversation as resolved.
Show resolved Hide resolved
.try_collect()?;

let filtered_chain_configs = match &filter {
Some(filter) => chain_config_responses
.into_iter()
.filter(|config| filter.matches(config))
.collect(),
None => chain_config_responses,
};
to_json_binary(&filtered_chain_configs).change_context(Error::JsonSerialization)
}

pub fn token_instance(deps: Deps, chain: ChainNameRaw, token_id: TokenId) -> Result<Binary, Error> {
let token_instance = state::may_load_token_instance(deps.storage, chain, token_id)
.change_context(Error::State)?;
Expand Down
33 changes: 33 additions & 0 deletions contracts/interchain-token-service/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,35 @@
EnableExecution,
}

#[cw_serde]
pub enum ChainStatusFilter {
Frozen,
Active,
}

#[cw_serde]
pub struct ChainFilter {
pub frozen_status: Option<ChainStatusFilter>,
maancham marked this conversation as resolved.
Show resolved Hide resolved
}

impl ChainStatusFilter {
pub fn matches(&self, config: &ChainConfigResponse) -> bool {
match self {
ChainStatusFilter::Frozen => config.frozen,
ChainStatusFilter::Active => !config.frozen,
}
}
}

impl ChainFilter {
pub fn matches(&self, config: &ChainConfigResponse) -> bool {
match &self.frozen_status {
Some(frozen_status) => frozen_status.matches(config),
None => true,

Check warning on line 80 in contracts/interchain-token-service/src/msg.rs

View check run for this annotation

Codecov / codecov/patch

contracts/interchain-token-service/src/msg.rs#L80

Added line #L80 was not covered by tests
}
maancham marked this conversation as resolved.
Show resolved Hide resolved
}
}

#[cw_serde]
pub struct ChainConfig {
pub chain: ChainNameRaw,
Expand Down Expand Up @@ -85,6 +114,10 @@
#[returns(HashMap<ChainNameRaw, Address>)]
AllItsContracts,

/// Query all chain configs with optional frozen filter
#[returns(Vec<ChainConfigResponse>)]
ItsChains { filter: Option<ChainFilter> },

/// Query a token instance on a specific chain
#[returns(Option<TokenInstance>)]
TokenInstance {
Expand Down
4 changes: 4 additions & 0 deletions contracts/interchain-token-service/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ pub fn load_chain_config(
.ok_or_else(|| report!(Error::ChainNotFound(chain.to_owned())))
}

pub fn load_chain_configs() -> Map<&'static ChainNameRaw, ChainConfig> {
CHAIN_CONFIGS
maancham marked this conversation as resolved.
Show resolved Hide resolved
}

pub fn save_chain_config(
storage: &mut dyn Storage,
chain: &ChainNameRaw,
Expand Down
171 changes: 141 additions & 30 deletions contracts/interchain-token-service/tests/query.rs
Original file line number Diff line number Diff line change
@@ -1,49 +1,94 @@
use std::collections::HashMap;

use assert_ok::assert_ok;
use cosmwasm_std::testing::mock_dependencies;
use cosmwasm_std::Uint256;
use interchain_token_service::msg::{ChainConfigResponse, TruncationConfig};
use cosmwasm_std::testing::{mock_dependencies, MockApi, MockQuerier, MockStorage};
use cosmwasm_std::{Empty, OwnedDeps, Uint256};
use interchain_token_service::msg::{
ChainConfigResponse, ChainFilter, ChainStatusFilter, TruncationConfig,
};
use interchain_token_service::TokenId;
use router_api::{Address, ChainNameRaw};

mod utils;

#[test]
fn query_chain_config() {
let mut deps = mock_dependencies();
utils::instantiate_contract(deps.as_mut()).unwrap();
struct ChainConfigTest {
deps: OwnedDeps<MockStorage, MockApi, MockQuerier, Empty>,
eth: utils::ChainData,
polygon: utils::ChainData,
}

let chain: ChainNameRaw = "Ethereum".parse().unwrap();
let address: Address = "0x1234567890123456789012345678901234567890"
.parse()
impl ChainConfigTest {
fn setup() -> Self {
let mut deps = mock_dependencies();
utils::instantiate_contract(deps.as_mut()).unwrap();

let eth = utils::ChainData {
chain: "Ethereum".parse().unwrap(),
address: "0x1234567890123456789012345678901234567890"
.parse()
.unwrap(),
max_uint: Uint256::MAX.try_into().unwrap(),
max_decimals: u8::MAX,
};

let polygon = utils::ChainData {
chain: "Polygon".parse().unwrap(),
address: "0x1234567890123456789012345678901234567890"
.parse()
.unwrap(),
max_uint: Uint256::MAX.try_into().unwrap(),
max_decimals: u8::MAX,
};

let mut test_config = Self { deps, eth, polygon };
test_config.register_test_chains();
test_config
}

fn register_test_chains(&mut self) {
utils::register_chain(
self.deps.as_mut(),
self.eth.chain.clone(),
self.eth.address.clone(),
self.eth.max_uint,
self.eth.max_decimals,
)
.unwrap();

utils::register_chain(
deps.as_mut(),
chain.clone(),
address.clone(),
Uint256::MAX.try_into().unwrap(),
u8::MAX,
)
.unwrap();
utils::register_chain(
self.deps.as_mut(),
self.polygon.chain.clone(),
self.polygon.address.clone(),
self.polygon.max_uint,
self.polygon.max_decimals,
)
.unwrap();
}
}

#[test]
fn query_chain_config() {
let mut test_config = ChainConfigTest::setup();

let original_chain_config = ChainConfigResponse {
chain: chain.clone(),
its_edge_contract: address.clone(),
let eth_expected_config_response = ChainConfigResponse {
chain: test_config.eth.chain.clone(),
its_edge_contract: test_config.eth.address.clone(),
truncation: TruncationConfig {
max_uint: Uint256::MAX.try_into().unwrap(),
max_decimals_when_truncating: u8::MAX,
max_uint: test_config.eth.max_uint,
max_decimals_when_truncating: test_config.eth.max_decimals,
},
frozen: false,
};

let chain_config = assert_ok!(utils::query_its_chain(deps.as_ref(), chain.clone()));
assert_eq!(chain_config.unwrap(), original_chain_config);
let eth_chain_config = assert_ok!(utils::query_its_chain(
test_config.deps.as_ref(),
test_config.eth.chain.clone()
));
assert_eq!(eth_chain_config.unwrap(), eth_expected_config_response);

// case sensitive query
let chain_config = assert_ok!(utils::query_its_chain(
deps.as_ref(),
test_config.deps.as_ref(),
"ethereum".parse().unwrap()
));
assert_eq!(chain_config, None);
Expand All @@ -52,16 +97,22 @@ fn query_chain_config() {
.parse()
.unwrap();
assert_ok!(utils::update_chain(
deps.as_mut(),
chain.clone(),
test_config.deps.as_mut(),
test_config.eth.chain.clone(),
new_address.clone()
));

let chain_config = assert_ok!(utils::query_its_chain(deps.as_ref(), chain.clone()));
let chain_config = assert_ok!(utils::query_its_chain(
test_config.deps.as_ref(),
test_config.eth.chain.clone()
));
assert_eq!(chain_config.unwrap().its_edge_contract, new_address);

let non_existent_chain: ChainNameRaw = "non-existent-chain".parse().unwrap();
let chain_config = assert_ok!(utils::query_its_chain(deps.as_ref(), non_existent_chain));
let chain_config = assert_ok!(utils::query_its_chain(
test_config.deps.as_ref(),
non_existent_chain
));
assert_eq!(chain_config, None);
}

Expand Down Expand Up @@ -127,3 +178,63 @@ fn query_contract_enable_disable_lifecycle() {
let enabled = utils::query_is_contract_enabled(deps.as_ref()).unwrap();
assert!(!enabled);
}

#[test]
fn query_chains_config() {
let mut test_config = ChainConfigTest::setup();

// Test all chains
let all_chains = utils::query_its_chains(test_config.deps.as_ref(), None).unwrap();
let expected = vec![
utils::create_config_response(&test_config.eth, false),
utils::create_config_response(&test_config.polygon, false),
];
utils::assert_configs_equal(&all_chains, &expected);

// Test active chains
let active_chains = utils::query_its_chains(
test_config.deps.as_ref(),
Some(ChainFilter {
frozen_status: Some(ChainStatusFilter::Active),
}),
)
.unwrap();
utils::assert_configs_equal(&active_chains, &expected);

// Test frozen chains (empty)
let frozen_chains = utils::query_its_chains(
test_config.deps.as_ref(),
Some(ChainFilter {
frozen_status: Some(ChainStatusFilter::Frozen),
}),
)
.unwrap();
assert!(frozen_chains.is_empty());

// Test after freezing eth chain
utils::freeze_chain(test_config.deps.as_mut(), test_config.eth.chain.clone()).unwrap();

let frozen_chains = utils::query_its_chains(
test_config.deps.as_ref(),
Some(ChainFilter {
frozen_status: Some(ChainStatusFilter::Frozen),
}),
)
.unwrap();
utils::assert_configs_equal(
&frozen_chains,
&[utils::create_config_response(&test_config.eth, true)],
);

let active_chains = utils::query_its_chains(
test_config.deps.as_ref(),
Some(ChainFilter {
frozen_status: Some(ChainStatusFilter::Active),
}),
)
.unwrap();
utils::assert_configs_equal(
&active_chains,
&[utils::create_config_response(&test_config.polygon, false)],
);
}
9 changes: 9 additions & 0 deletions contracts/interchain-token-service/tests/utils/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,15 @@ pub fn update_chain(
)
}

pub fn freeze_chain(deps: DepsMut, chain: ChainNameRaw) -> Result<Response, ContractError> {
contract::execute(
deps,
mock_env(),
message_info(&MockApi::default().addr_make(params::GOVERNANCE), &[]),
ExecuteMsg::FreezeChain { chain },
)
}

pub fn disable_contract_execution(deps: DepsMut) -> Result<Response, ContractError> {
contract::execute(
deps,
Expand Down
37 changes: 36 additions & 1 deletion contracts/interchain-token-service/tests/utils/query.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::collections::HashMap;

use axelar_wasm_std::error::ContractError;
use axelar_wasm_std::nonempty;
use cosmwasm_std::testing::mock_env;
use cosmwasm_std::{from_json, Deps};
use interchain_token_service::contract::query;
use interchain_token_service::msg::{ChainConfigResponse, QueryMsg};
use interchain_token_service::msg::{ChainConfigResponse, ChainFilter, QueryMsg, TruncationConfig};
use interchain_token_service::{TokenConfig, TokenId, TokenInstance};
use router_api::{Address, ChainNameRaw};

Expand Down Expand Up @@ -48,3 +49,37 @@ pub fn query_is_contract_enabled(deps: Deps) -> Result<bool, ContractError> {
let bin = query(deps, mock_env(), QueryMsg::IsEnabled {})?;
Ok(from_json(bin)?)
}

pub fn query_its_chains(
deps: Deps,
filter: Option<ChainFilter>,
) -> Result<Vec<ChainConfigResponse>, ContractError> {
let bin = query(deps, mock_env(), QueryMsg::ItsChains { filter })?;
Ok(from_json(bin)?)
}

pub struct ChainData {
pub chain: ChainNameRaw,
pub address: Address,
pub max_uint: nonempty::Uint256,
pub max_decimals: u8,
}

pub fn create_config_response(chain_data: &ChainData, frozen: bool) -> ChainConfigResponse {
ChainConfigResponse {
chain: chain_data.chain.clone(),
its_edge_contract: chain_data.address.clone(),
truncation: TruncationConfig {
max_uint: chain_data.max_uint,
max_decimals_when_truncating: chain_data.max_decimals,
},
frozen,
}
}

pub fn assert_configs_equal(actual: &[ChainConfigResponse], expected: &[ChainConfigResponse]) {
assert_eq!(actual.len(), expected.len(), "Different number of configs");
for (a, e) in actual.iter().zip(expected.iter()) {
assert_eq!(a, e, "Config mismatch for chain {}", e.chain);
}
}
Loading