Skip to content

Commit

Permalink
initial test
Browse files Browse the repository at this point in the history
query exchange param test
query exchange spot market test
query subaccount deposit test
  • Loading branch information
jbernal87 committed Feb 5, 2024
1 parent aa4f051 commit cbfd7a7
Show file tree
Hide file tree
Showing 9 changed files with 398 additions and 175 deletions.
98 changes: 49 additions & 49 deletions Cargo.lock

Large diffs are not rendered by default.

23 changes: 13 additions & 10 deletions contracts/injective-cosmwasm-mock/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ crate-type = [ "cdylib", "rlib" ]
backtraces = [ "cosmwasm-std/backtraces" ]
# use library feature to disable all instantiate/execute/query exports
library = [ ]
integration = [ ]

[package.metadata.scripts]
optimize = """docker run --rm -v "$(pwd)":/code \
Expand All @@ -29,13 +30,15 @@ optimize = """docker run --rm -v "$(pwd)":/code \
"""

[dependencies]
cosmwasm-std = { version = "1.5.0", features = [ "abort", "cosmwasm_1_2", "cosmwasm_1_3", "cosmwasm_1_4", "iterator", "stargate" ] }
cw-storage-plus = "1.2.0"
cw2 = "0.16.0"
injective-cosmwasm = { path = "../../packages/injective-cosmwasm" }
injective-math = { path = "../../packages/injective-math" }
injective-std = { version = "0.1.5" }
injective-test-tube = "1.1.6"
schemars = "0.8.8"
serde = { version = "1.0.137", default-features = false, features = [ "derive" ] }
thiserror = { version = "1.0.31" }
cosmwasm-std = { version = "1.5.0", features = [ "abort", "cosmwasm_1_2", "cosmwasm_1_3", "cosmwasm_1_4", "iterator", "stargate" ] }
cw-storage-plus = "1.2.0"
cw2 = "0.16.0"
injective-cosmwasm = { path = "../../packages/injective-cosmwasm" }
injective-math = { path = "../../packages/injective-math" }
schemars = { version ="0.8.16"}
serde = { version = "1.0.196", default-features = false, features = [ "derive" ] }
thiserror = { version = "1.0.56" }

[dev-dependencies]
injective-test-tube = "1.1.7"
injective-std = { version = "0.1.5" }
17 changes: 10 additions & 7 deletions contracts/injective-cosmwasm-mock/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use crate::{
error::ContractError,
msg::{ExecuteMsg, InstantiateMsg, QueryMsg},
};
use cosmwasm_std::{to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult};
use cw2::set_contract_version;

use injective_cosmwasm::{create_deposit_msg, InjectiveMsgWrapper, InjectiveQuerier, InjectiveQueryWrapper};

use crate::error::ContractError;
use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg};
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;

const CONTRACT_NAME: &str = "crates.io:injective:dummy";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
Expand All @@ -33,9 +34,11 @@ pub fn execute(

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps<InjectiveQueryWrapper>, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
let querier = InjectiveQuerier::new(&deps.querier);
let querier: InjectiveQuerier = InjectiveQuerier::new(&deps.querier);

match msg {
QueryMsg::TestSpotMarketQuery { market_id } => to_json_binary(&querier.query_spot_market(&market_id)?.market),
QueryMsg::TestSpotMarketQuery { market_id } => to_json_binary(&querier.query_spot_market(&market_id)?),
QueryMsg::TestExchangeParamsQuery {} => to_json_binary(&querier.query_exchange_params()?),
QueryMsg::TestSubAccountDepositQuery { subaccount_id, denom } => to_json_binary(&querier.query_subaccount_deposit(&subaccount_id, &denom)?),
}
}
2 changes: 2 additions & 0 deletions contracts/injective-cosmwasm-mock/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ mod error;
pub mod msg;
#[cfg(test)]
mod testing;

#[cfg(test)]
pub mod utils;

pub use crate::error::ContractError;
2 changes: 2 additions & 0 deletions contracts/injective-cosmwasm-mock/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,7 @@ pub enum ExecuteMsg {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
TestExchangeParamsQuery {},
TestSpotMarketQuery { market_id: MarketId },
TestSubAccountDepositQuery { subaccount_id: SubaccountId, denom: String },
}
2 changes: 1 addition & 1 deletion contracts/injective-cosmwasm-mock/src/testing/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
mod query_spot_market_test;
mod query_exchange_test;
196 changes: 196 additions & 0 deletions contracts/injective-cosmwasm-mock/src/testing/query_exchange_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
use crate::{
msg::{ExecuteMsg, QueryMsg},
utils::{human_to_dec, human_to_proto, str_coin, Setup, BASE_DECIMALS, BASE_DENOM, QUOTE_DECIMALS, QUOTE_DENOM},
};

use cosmwasm_std::Coin;
use injective_cosmwasm::{ExchangeParamsResponse, MarketId, SubaccountDepositResponse};
use injective_math::{scale::Scaled, FPDecimal};
use injective_std::types::injective::exchange::v1beta1::{
Deposit, MsgDeposit, MsgInstantSpotMarketLaunch, QuerySpotMarketsRequest, QuerySubaccountDepositsRequest,
};
use injective_test_tube::{injective_cosmwasm::SpotMarketResponse, Account, Exchange, Module, RunnerResult, Wasm};

pub fn dec_to_proto(val: FPDecimal) -> String {
val.scaled(18).to_string()
}

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_msg_deposit() {
let env = Setup::new();

let wasm = Wasm::new(&env.app);
let user = &env.users[0];

// Execute contract
let res = wasm.execute(
&env.contract_address,
&ExecuteMsg::TestDepositMsg {
subaccount_id: user.subaccount_id.clone(),
amount: Coin::new(100, "usdt"),
},
&[Coin::new(100, "usdt")],
&user.account,
);
assert!(res.is_ok(), "Execution failed with error: {:?}", res.unwrap_err());
}

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_exchange_params() {
let env = Setup::new();
let wasm = Wasm::new(&env.app);
let res: ExchangeParamsResponse = wasm.query(&env.contract_address, &QueryMsg::TestExchangeParamsQuery {}).unwrap();

assert!(res.params.is_some());
let params = res.params.unwrap();

let listing_fee_coin = str_coin("1000", BASE_DENOM, BASE_DECIMALS);
assert_eq!(params.spot_market_instant_listing_fee, listing_fee_coin);
assert_eq!(params.derivative_market_instant_listing_fee, listing_fee_coin);
assert_eq!(params.trading_rewards_vesting_duration, 604800);
assert_eq!(params.is_instant_derivative_market_launch_enabled, Some(true));
}

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_spot_market_no_market_on_exchange() {
let env = Setup::new();
let wasm = Wasm::new(&env.app);

// Query
let market_id = MarketId::new("0xd5a22be807011d5e42d5b77da3f417e22676efae494109cd01c242ad46630115").unwrap();
let query_msg = QueryMsg::TestSpotMarketQuery { market_id };
let res: RunnerResult<SpotMarketResponse> = wasm.query(&env.contract_address, &query_msg);
assert_eq!(res, Ok(SpotMarketResponse { market: None }));
}

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_spot_market() {
let env = Setup::new();

let wasm = Wasm::new(&env.app);
let exchange = Exchange::new(&env.app);

// Instantiate spot market
let ticker = "INJ/USDT".to_string();
let min_price_tick_size = FPDecimal::must_from_str("0.000000000000001");
let min_quantity_tick_size = FPDecimal::must_from_str("1000000000000000");

exchange
.instant_spot_market_launch(
MsgInstantSpotMarketLaunch {
sender: env.signer.address(),
ticker: ticker.clone(),
base_denom: BASE_DENOM.to_string(),
quote_denom: QUOTE_DENOM.to_string(),
min_price_tick_size: dec_to_proto(min_price_tick_size),
min_quantity_tick_size: dec_to_proto(min_quantity_tick_size),
},
&env.signer,
)
.unwrap();

let spot_markets = exchange
.query_spot_markets(&QuerySpotMarketsRequest {
status: "Active".to_string(),
market_ids: vec![],
})
.unwrap()
.markets;

let market = spot_markets.iter().find(|m| m.ticker == ticker).unwrap();
let spot_market_id = market.market_id.to_string();

// Query
let market_id = MarketId::new(spot_market_id.clone()).unwrap();
let query_msg = QueryMsg::TestSpotMarketQuery { market_id };
let res: SpotMarketResponse = wasm.query(&env.contract_address, &query_msg).unwrap();

let response_market = res.market.unwrap();
assert_eq!(response_market.market_id.as_str(), spot_market_id);
assert_eq!(response_market.ticker.as_str(), ticker);
assert_eq!(response_market.base_denom.as_str(), BASE_DENOM);
assert_eq!(response_market.quote_denom.as_str(), QUOTE_DENOM);
assert_eq!(response_market.min_price_tick_size.clone().to_string(), min_price_tick_size.to_string());
assert_eq!(response_market.min_quantity_tick_size.to_string(), min_quantity_tick_size.to_string());
}

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_subaccount_deposit() {
let env = Setup::new();

let exchange = Exchange::new(&env.app);
let wasm = Wasm::new(&env.app);

{
exchange
.deposit(
MsgDeposit {
sender: env.users[0].account.address(),
subaccount_id: env.users[0].subaccount_id.to_string(),
amount: Some(injective_std::types::cosmos::base::v1beta1::Coin {
amount: "10000000000000000000".to_string(),
denom: env.denoms["base"].clone(),
}),
},
&env.users[0].account,
)
.unwrap();
}

{
exchange
.deposit(
MsgDeposit {
sender: env.users[0].account.address(),
subaccount_id: env.users[0].subaccount_id.to_string(),
amount: Some(injective_std::types::cosmos::base::v1beta1::Coin {
amount: "100000000".to_string(),
denom: env.denoms["quote"].clone(),
}),
},
&env.users[0].account,
)
.unwrap();
}

let response = exchange
.query_subaccount_deposits(&QuerySubaccountDepositsRequest {
subaccount_id: env.users[0].subaccount_id.clone().to_string(),
subaccount: None,
})
.unwrap();

assert_eq!(
response.deposits[&env.denoms["base"].clone()],
Deposit {
available_balance: human_to_proto("10.0", BASE_DECIMALS),
total_balance: human_to_proto("10.0", BASE_DECIMALS),
}
);
assert_eq!(
response.deposits[&env.denoms["quote"].clone()],
Deposit {
available_balance: human_to_proto("100.0", QUOTE_DECIMALS),
total_balance: human_to_proto("100.0", QUOTE_DECIMALS),
}
);

let query_msg = QueryMsg::TestSubAccountDepositQuery {
subaccount_id: env.users[0].subaccount_id.clone(),
denom: BASE_DENOM.to_string(),
};
let contract_response: SubaccountDepositResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert_eq!(contract_response.deposits.total_balance, human_to_dec("10.0", BASE_DECIMALS));

let query_msg = QueryMsg::TestSubAccountDepositQuery {
subaccount_id: env.users[0].subaccount_id.clone(),
denom: QUOTE_DENOM.to_string(),
};
let contract_response: SubaccountDepositResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
assert_eq!(contract_response.deposits.available_balance, human_to_dec("100.0", QUOTE_DECIMALS));
}

This file was deleted.

Loading

0 comments on commit cbfd7a7

Please sign in to comment.