Skip to content

Commit

Permalink
chore: refactored out given in querys for e2e
Browse files Browse the repository at this point in the history
  • Loading branch information
crnbarr93 committed Jul 3, 2024
1 parent 64c2f4d commit b3f60d3
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 64 deletions.
20 changes: 7 additions & 13 deletions contracts/sumtree-orderbook/src/tests/e2e/cases/test_fuzz.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::time::{Duration, SystemTime};

use cosmwasm_std::{Coin, Decimal};
use cosmwasm_std::Coin;
use cosmwasm_std::{Decimal256, Uint128};
use osmosis_test_tube::{Account, Module, OsmosisTestApp};
use rand::seq::SliceRandom;
Expand All @@ -10,7 +10,7 @@ use rand::{rngs::StdRng, SeedableRng};

use super::utils::{assert, orders};
use crate::constants::MIN_TICK;
use crate::msg::{CalcOutAmtGivenInResponse, QueryMsg};
use crate::msg::QueryMsg;
use crate::tests::e2e::modules::cosmwasm_pool::CosmwasmPool;
use crate::tick_math::{amount_to_value, tick_to_price, RoundingDirection};
use crate::{
Expand Down Expand Up @@ -647,10 +647,10 @@ fn place_random_market(
order_direction: OrderDirection,
) -> u128 {
// Get the appropriate denom for the chosen direction
let (token_in_denom, token_out_denom) = if order_direction == OrderDirection::Bid {
("quote", "base")
let token_in_denom = if order_direction == OrderDirection::Bid {
"quote"
} else {
("base", "quote")
"base"
};

// Select a random amount of the token in to swap
Expand All @@ -663,16 +663,10 @@ fn place_random_market(
}

// Calculate the expected amount of token out
let expected_out =
t.contract
.query::<CalcOutAmtGivenInResponse>(&QueryMsg::CalcOutAmountGivenIn {
token_in: Coin::new(amount, token_in_denom.to_string()),
token_out_denom: token_out_denom.to_string(),
swap_fee: Decimal::zero(),
});
let expected_out = t.contract.get_out_given_in(order_direction, amount);

if let Ok(expected_out) = expected_out {
if expected_out.token_out.amount == "0" {
if expected_out.amount == "0" {
return 0;
}
} else if expected_out.is_err() {
Expand Down
60 changes: 14 additions & 46 deletions contracts/sumtree-orderbook/src/tests/e2e/cases/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,14 @@ pub mod assert {

use crate::{
msg::{
CalcOutAmtGivenInResponse, DenomsResponse, GetTotalPoolLiquidityResponse,
GetUnrealizedCancelsResponse, QueryMsg, SpotPriceResponse, TickIdAndState,
DenomsResponse, GetTotalPoolLiquidityResponse, GetUnrealizedCancelsResponse, QueryMsg,
SpotPriceResponse, TickIdAndState,
},
tests::e2e::test_env::TestEnv,
tick_math::{amount_to_value, tick_to_price, RoundingDirection},
types::{OrderDirection, Orderbook},
};
use cosmwasm_std::{Coin, Coins, Decimal, Fraction, Uint128};
use cosmwasm_std::{Coin, Coins, Fraction, Uint128};
use osmosis_test_tube::{cosmrs::proto::prost::Message, RunnerExecuteResult};

// -- Contract State Assertions
Expand Down Expand Up @@ -291,46 +291,29 @@ pub mod assert {
}
}

// Asserts that a new market order will return a lower or equal expected amount that a previous market expected output
pub(crate) fn decrementing_market_order_output(
t: &TestEnv,
previous_market_value: u128,
amount_to_run: u128,
direction: OrderDirection,
) -> Uint128 {
let DenomsResponse {
quote_denom,
base_denom,
} = t.contract.get_denoms();

let token_in_denom = if direction == OrderDirection::Bid {
quote_denom.clone()
} else {
base_denom.clone()
};
let token_out_denom = if direction == OrderDirection::Bid {
base_denom
} else {
quote_denom
};

let maybe_expected_output = t.contract.query(&QueryMsg::CalcOutAmountGivenIn {
token_in: Coin::new(amount_to_run, token_in_denom),
token_out_denom,
swap_fee: Decimal::zero(),
});
// Calculate the expected output for a market order of the given amount
let maybe_expected_output = t.contract.get_out_given_in(direction, amount_to_run);

// If the expected output errors we return zero
let expected_output = maybe_expected_output
.map_or(Uint128::zero(), |r: CalcOutAmtGivenInResponse| {
Uint128::from_str(&r.token_out.amount).unwrap()
});
.map_or(Uint128::zero(), |r| Uint128::from_str(&r.amount).unwrap());

// Assert that the expected output is less than or equal to the previous market value
assert!(
expected_output.u128() <= previous_market_value,
"subsequent market orders increased unexpectedly, got: {}, expected: {}",
expected_output,
previous_market_value
);

// Return the expected output
expected_output
}

Expand Down Expand Up @@ -458,7 +441,7 @@ pub mod assert {
pub mod orders {
use std::str::FromStr;

use cosmwasm_std::{coins, Coin, Decimal, Decimal256, Uint128, Uint256};
use cosmwasm_std::{coins, Coin, Decimal256, Uint128, Uint256};

use osmosis_std::types::{
cosmwasm::wasm::v1::MsgExecuteContractResponse,
Expand All @@ -469,7 +452,7 @@ pub mod orders {
use osmosis_test_tube::{Account, OsmosisTestApp, RunnerExecuteResult};

use crate::{
msg::{CalcOutAmtGivenInResponse, DenomsResponse, ExecuteMsg, QueryMsg},
msg::{DenomsResponse, ExecuteMsg, QueryMsg},
tests::e2e::{modules::cosmwasm_pool::CosmwasmPool, test_env::TestEnv},
tick_math::{amount_to_value, tick_to_price, RoundingDirection},
types::{LimitOrder, OrderDirection},
Expand Down Expand Up @@ -556,26 +539,11 @@ pub mod orders {
sender: &str,
) -> RunnerExecuteResult<MsgSwapExactAmountInResponse> {
let quantity_u128: Uint128 = quantity.clone().into();
let DenomsResponse {
base_denom,
quote_denom,
} = t.contract.query(&QueryMsg::Denoms {}).unwrap();

// Determine denom ordering based on order direction
let (token_in_denom, token_out_denom) = if order_direction == OrderDirection::Bid {
(quote_denom.clone(), base_denom.clone())
} else {
(base_denom.clone(), quote_denom.clone())
};

// DEV NOTE: is there a way to remove circular dependency for output expectancy?
let CalcOutAmtGivenInResponse { token_out } = t
let token_out = t
.contract
.query(&QueryMsg::CalcOutAmountGivenIn {
token_in: Coin::new(quantity_u128.u128(), token_in_denom.clone()),
token_out_denom,
swap_fee: Decimal::zero(),
})
.get_out_given_in(order_direction, quantity_u128.u128())
.unwrap();

assert::balance_changes(
Expand Down
30 changes: 25 additions & 5 deletions contracts/sumtree-orderbook/src/tests/e2e/test_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@ use std::{collections::HashMap, path::PathBuf, str::FromStr};
use crate::{
constants::{MAX_TICK, MIN_TICK},
msg::{
AuthExecuteMsg, DenomsResponse, ExecuteMsg, GetTotalPoolLiquidityResponse,
GetUnrealizedCancelsResponse, InstantiateMsg, OrdersResponse, QueryMsg, SudoMsg,
TickIdAndState, TickUnrealizedCancels, TicksResponse,
AuthExecuteMsg, CalcOutAmtGivenInResponse, DenomsResponse, ExecuteMsg,
GetTotalPoolLiquidityResponse, GetUnrealizedCancelsResponse, InstantiateMsg,
OrdersResponse, QueryMsg, SudoMsg, TickIdAndState, TickUnrealizedCancels, TicksResponse,
},
tests::test_utils::decimal256_from_u128,
tick_math::{amount_to_value, tick_to_price, RoundingDirection},
types::{LimitOrder, OrderDirection},
ContractError,
};

use cosmwasm_std::{to_json_binary, Addr, Coin, Coins, Decimal256, Uint128, Uint256};
use cosmwasm_std::{to_json_binary, Addr, Coin, Coins, Decimal, Decimal256, Uint128, Uint256};
use osmosis_std::types::{
cosmos::bank::v1beta1::QueryAllBalancesRequest,
cosmos::{bank::v1beta1::QueryAllBalancesRequest, base::v1beta1::Coin as ProtoCoin},
cosmwasm::wasm::v1::MsgExecuteContractResponse,
osmosis::cosmwasmpool::v1beta1::{
ContractInfoByPoolIdRequest, ContractInfoByPoolIdResponse, MsgCreateCosmWasmPool,
Expand Down Expand Up @@ -413,6 +413,26 @@ impl<'a> OrderbookContract<'a> {
}
max_amount.u128()
}

// Calculate the expected output for a given input amount/direction using the CosmWasm pool query
pub(crate) fn get_out_given_in(
&self,
direction: OrderDirection,
amount: impl Into<u128>,
) -> RunnerResult<ProtoCoin> {
let (token_in_denom, token_out_denom) = if direction == OrderDirection::Bid {
(self.get_denoms().quote_denom, self.get_denoms().base_denom)
} else {
(self.get_denoms().base_denom, self.get_denoms().quote_denom)
};

self.query(&QueryMsg::CalcOutAmountGivenIn {
token_in: Coin::new(amount.into(), token_in_denom),
token_out_denom,
swap_fee: Decimal::zero(),
})
.map(|r: CalcOutAmtGivenInResponse| r.token_out)
}
}

pub fn _assert_contract_err(expected: ContractError, actual: RunnerError) {
Expand Down

0 comments on commit b3f60d3

Please sign in to comment.