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 14 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
8 changes: 8 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 @@ -134,6 +136,12 @@ 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,
start_after,
limit,
} => query::its_chains(deps, filter, start_after, limit)
.change_context(Error::QueryAllChainConfigs),
QueryMsg::TokenInstance { chain, token_id } => {
query::token_instance(deps, chain, token_id).change_context(Error::QueryTokenInstance)
}
Expand Down
37 changes: 36 additions & 1 deletion contracts/interchain-token-service/src/contract/query.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
use axelar_wasm_std::{killswitch, IntoContractError};
use cosmwasm_std::{to_json_binary, Binary, Deps};
use cosmwasm_std::{to_json_binary, Binary, Deps, Order};
use cw_storage_plus::Bound;
use error_stack::{Result, ResultExt};
use itertools::Itertools;
use router_api::ChainNameRaw;

use crate::{msg, state, TokenId};

// Pagination limit
const DEFAULT_LIMIT: u32 = u32::MAX;

#[derive(thiserror::Error, Debug, IntoContractError)]
pub enum Error {
#[error("failed to serialize data to JSON")]
Expand Down Expand Up @@ -34,6 +39,36 @@ 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>,
start_after: Option<ChainNameRaw>,
limit: Option<u32>,
) -> Result<Binary, Error> {
let state_chain_configs = state::load_chain_configs();

let limit = limit.unwrap_or(DEFAULT_LIMIT) as usize;
let start = start_after.as_ref().map(Bound::exclusive);

let filtered_chain_configs: Vec<_> = state_chain_configs
.range(deps.storage, start, 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
.filter_ok(|config| !filter.clone().is_some_and(|f| !f.matches(config)))
.take(limit)
.try_collect()?;

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
40 changes: 40 additions & 0 deletions contracts/interchain-token-service/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,35 @@
EnableExecution,
}

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

#[cw_serde]
pub struct ChainFilter {
pub 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.status {
Some(frozen_status) => frozen_status.matches(config),
None => true,

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L78 was not covered by tests
}
}
}

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

/// Query all chain configs with optional frozen filter
// The list is paginated by:
// - start_after: the chain name to start after, which the next page of results should start.
// - limit: limit the number of chains returned, default is u32::MAX.
#[returns(Vec<ChainConfigResponse>)]
ItsChains {
filter: Option<ChainFilter>,
start_after: Option<ChainNameRaw>,
limit: Option<u32>,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
limit: Option<u32>,
#[serde(default = "default_pagination_limit"]
limit: u32,

with

const fn default_pagination_limit() -> u32{
    DEFAULT_LIMIT
}

this makes it clearer that we never do an unbounded search

},

/// 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
181 changes: 150 additions & 31 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::{Uint128, 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,18 +97,24 @@ 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(),
Uint128::MAX.try_into().unwrap(),
Uint256::MAX.try_into().unwrap(),
18,
));

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 @@ -129,3 +180,71 @@ 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, None, 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 {
status: Some(ChainStatusFilter::Active),
}),
None,
None,
)
.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 {
status: Some(ChainStatusFilter::Frozen),
}),
None,
None,
)
.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 {
status: Some(ChainStatusFilter::Frozen),
}),
None,
None,
)
.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 {
status: Some(ChainStatusFilter::Active),
}),
None,
None,
)
.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 @@ -147,6 +147,15 @@ pub fn update_chains(
)
}

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
Loading
Loading