Skip to content

Commit

Permalink
fix transient spot test
Browse files Browse the repository at this point in the history
  • Loading branch information
jbernal87 committed Apr 29, 2024
1 parent bb0fc63 commit 232e4b5
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 33 deletions.
6 changes: 3 additions & 3 deletions contracts/injective-cosmwasm-stargate-example/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
handle::{handle_test_transient_derivative_order, handle_test_transient_spot_order},
msg::{ExecuteMsg, InstantiateMsg, QueryMsg},
query::handle_query_stargate,
reply::{handle_create_derivative_order_reply, handle_create_order_reply},
reply::{handle_create_derivative_order_reply_stargate, handle_create_order_reply_stargate},
};
use cosmwasm_std::{entry_point, Binary, Deps, DepsMut, Env, MessageInfo, Reply, Response, StdResult};
use cw2::set_contract_version;
Expand Down Expand Up @@ -54,8 +54,8 @@ pub fn query(deps: Deps<InjectiveQueryWrapper>, _env: Env, msg: QueryMsg) -> Std
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn reply(deps: DepsMut<InjectiveQueryWrapper>, _env: Env, msg: Reply) -> Result<Response, ContractError> {
match msg.id {
CREATE_SPOT_ORDER_REPLY_ID => handle_create_order_reply(deps, &msg),
CREATE_DERIVATIVE_ORDER_REPLY_ID => handle_create_derivative_order_reply(deps, &msg),
CREATE_SPOT_ORDER_REPLY_ID => handle_create_order_reply_stargate(deps, &msg),
CREATE_DERIVATIVE_ORDER_REPLY_ID => handle_create_derivative_order_reply_stargate(deps, &msg),
_ => Err(ContractError::UnrecognizedReply(msg.id)),
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use prost::Message;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine;

pub fn encode_proto_message<T: Message>(msg: T) -> String {
let mut buf = vec![];
T::encode(&msg, &mut buf).unwrap();
BASE64_STANDARD.encode(&buf)
}
1 change: 1 addition & 0 deletions contracts/injective-cosmwasm-stargate-example/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ mod testing;
mod types;
#[cfg(test)]
pub mod utils;
mod encode_helper;

pub use crate::error::ContractError;
35 changes: 28 additions & 7 deletions contracts/injective-cosmwasm-stargate-example/src/reply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,38 @@ use crate::state::ORDER_CALL_CACHE;
use crate::ContractError;
use cosmwasm_std::{DepsMut, Event, Reply, Response};
use injective_cosmwasm::{InjectiveQuerier, InjectiveQueryWrapper};
use crate::encode_helper::encode_proto_message;
use crate::query::handle_query_stargate;

pub fn handle_create_order_reply(deps: DepsMut<InjectiveQueryWrapper>, _msg: &Reply) -> Result<Response, ContractError> {
let mut response_str = "Something went wrong".to_string();

let querier: InjectiveQuerier = InjectiveQuerier::new(&deps.querier);
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, Eq, ::prost::Message, ::serde::Serialize, ::serde::Deserialize, ::schemars::JsonSchema)]
pub struct QueryTraderSpotOrdersRequest {
/// Market ID for the market
#[prost(string, tag = "1")]
#[serde(alias = "marketID")]
pub market_id: ::prost::alloc::string::String,
/// SubaccountID of the trader
#[prost(string, tag = "2")]
#[serde(alias = "subaccountID")]
pub subaccount_id: ::prost::alloc::string::String,
}

pub fn handle_create_order_reply_stargate(deps: DepsMut<InjectiveQueryWrapper>, _msg: &Reply) -> Result<Response, ContractError> {
let mut response_str = "Something went wrong".to_string();
if let Some(mut cache) = ORDER_CALL_CACHE.may_load(deps.storage)? {
if !cache.is_empty() {
let order_info = &cache[0];
let response = querier.query_trader_transient_spot_orders(&order_info.market_id, &order_info.subaccount);
response_str = format!("{:?}", &response);
let encode_query_message = encode_proto_message(QueryTraderSpotOrdersRequest {
market_id: order_info.market_id.clone().into(),
subaccount_id: order_info.subaccount.clone().into(),
});
let stargate_response = handle_query_stargate(&deps.querier, "/injective.exchange.v1beta1.Query/TraderSpotTransientOrders".to_string(), encode_query_message);
response_str = match stargate_response {
Ok(binary) => {
String::from_utf8(binary.0).unwrap_or_else(|e| format!("Failed to decode binary to string: {:?}", e))
},
Err(e) => format!("Error: {:?}", e),
};
cache.clear();
ORDER_CALL_CACHE.save(deps.storage, &cache)?;
}
Expand All @@ -21,7 +42,7 @@ pub fn handle_create_order_reply(deps: DepsMut<InjectiveQueryWrapper>, _msg: &Re
Ok(Response::new().add_event(Event::new("transient_order").add_attributes([("query_str", response_str)])))
}

pub fn handle_create_derivative_order_reply(deps: DepsMut<InjectiveQueryWrapper>, _msg: &Reply) -> Result<Response, ContractError> {
pub fn handle_create_derivative_order_reply_stargate(deps: DepsMut<InjectiveQueryWrapper>, _msg: &Reply) -> Result<Response, ContractError> {
let mut response_str = "Something went wrong".to_string();
let querier: InjectiveQuerier = InjectiveQuerier::new(&deps.querier);

Expand Down
2 changes: 1 addition & 1 deletion contracts/injective-cosmwasm-stargate-example/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use cosmwasm_schema::cw_serde;
use cw_storage_plus::Item;
use injective_cosmwasm::{MarketId, SubaccountId};

pub const ORDER_CALL_CACHE: Item<Vec<CacheOrderInfo>> = Item::new("order_call_cache");
pub const ORDER_CALL_CACHE: Item<Vec<CacheOrderInfo>> = Item::new("order_call_cache_stargate");

#[cw_serde]
pub struct CacheOrderInfo {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ use crate::utils::{add_spot_initial_liquidity, execute_all_authorizations, scale
use crate::{
msg::{QueryMsg, QueryStargateResponse},
testing::type_helpers::{ExchangeParams, ParamResponse},
utils::{encode_proto_message, human_to_dec, human_to_proto, str_coin, ExchangeType, Setup, BASE_DECIMALS, BASE_DENOM, QUOTE_DECIMALS},
utils::{BASE_DECIMALS, BASE_DENOM, ExchangeType, human_to_dec, human_to_proto, QUOTE_DECIMALS, Setup, str_coin},
};
use cosmwasm_std::{from_json, Addr};
use cosmwasm_std::{Addr, from_json};
use injective_cosmwasm::{checked_address_to_subaccount_id, MarketId, SubaccountDepositResponse};
use injective_std::types::injective::exchange::v1beta1::{Deposit, MsgDeposit, QuerySubaccountDepositRequest, QuerySubaccountDepositsRequest};
use injective_test_tube::{Account, Exchange, Module, Wasm};
use crate::encode_helper::encode_proto_message;

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
Expand Down Expand Up @@ -90,7 +91,6 @@ fn test_query_subaccount_deposit() {
let contract_response: QueryStargateResponse = wasm.query(&env.contract_address, &query_msg).unwrap();
let contract_response = contract_response.value;
let contract_response: SubaccountDepositResponse = serde_json::from_str(&contract_response).unwrap();
println!("{:?}", contract_response);
let deposit = contract_response.deposits;
assert_eq!(deposit.total_balance, human_to_dec("10.0", BASE_DECIMALS));
}
Expand Down Expand Up @@ -130,6 +130,6 @@ fn test_query_trader_transient_spot_orders() {
.and_then(|event| event.attributes.iter().find(|a| a.key == "query_str"));

assert!(transient_query.is_some());
let expected_order_info = "TraderSpotOrdersResponse { orders: Some([TrimmedSpotLimitOrder { price: FPDecimal { num: 9800000, sign: 1 }, quantity: FPDecimal { num: 1000000000000000000000000000000000000, sign: 1 }";
let expected_order_info = "{\"value\":\"{\\\"orders\\\":[{\\\"price\\\":\\\"0.000000000009800000\\\",\\\"quantity\\\":\\\"1000000000000000000.000000000000000000\\\",\\\"fillable\\\":\\\"1000000000000000000.000000000000000000\\\",\\\"isBuy\\\":false,";
assert!(transient_query.unwrap().value.contains(expected_order_info));
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ use crate::{
msg::QueryMsg,
testing::type_helpers::{MyDerivativeMarketResponse, MyPerpetualMarketFundingResponse, MyPerpetualMarketInfoResponse},
utils::{
add_derivative_order_as, add_derivative_orders, add_perp_initial_liquidity, dec_to_proto, encode_proto_message,
get_initial_perp_liquidity_orders_vector, get_perpetual_market_id, get_stargate_query_result, human_to_dec, scale_price_quantity_perp_market,
ExchangeType, HumanOrder, Setup, BASE_DENOM, QUOTE_DECIMALS, QUOTE_DENOM,
add_derivative_order_as, add_derivative_orders, add_perp_initial_liquidity, BASE_DENOM,
dec_to_proto, ExchangeType, get_initial_perp_liquidity_orders_vector, get_perpetual_market_id, get_stargate_query_result,
human_to_dec, HumanOrder, QUOTE_DECIMALS, QUOTE_DENOM, scale_price_quantity_perp_market, Setup,
},
};
use cosmwasm_std::{Addr, Int64};
Expand All @@ -20,7 +20,8 @@ use injective_std::types::injective::exchange::v1beta1::{
QueryPerpetualMarketFundingRequest, QueryPerpetualMarketInfoRequest, QuerySubaccountEffectivePositionInMarketRequest,
QuerySubaccountPositionInMarketRequest, QueryTraderDerivativeOrdersRequest,
};
use injective_test_tube::{injective_cosmwasm::get_default_subaccount_id_for_checked_address, Account, Exchange, Module, Wasm};
use injective_test_tube::{Account, Exchange, injective_cosmwasm::get_default_subaccount_id_for_checked_address, Module, Wasm};
use crate::encode_helper::encode_proto_message;

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::msg::QueryMsg;
use crate::testing::type_helpers::{MyOraclePriceResponse, MyPythPriceResponse, MyVolatilityResponse};
use crate::utils::{
create_some_inj_price_attestation, encode_proto_message, get_stargate_query_result, relay_pyth_price, set_address_of_pyth_contract, str_coin,
ExchangeType, Setup, BASE_DECIMALS, BASE_DENOM, INJ_PYTH_PRICE_ID,
BASE_DECIMALS, BASE_DENOM, create_some_inj_price_attestation, ExchangeType, get_stargate_query_result,
INJ_PYTH_PRICE_ID, relay_pyth_price, set_address_of_pyth_contract, Setup, str_coin,
};
use injective_cosmwasm::OracleType;
use injective_math::scale::Scaled;
Expand All @@ -11,6 +11,7 @@ use injective_std::types::injective::oracle::v1beta1::{
OracleHistoryOptions, OracleInfo, QueryOraclePriceRequest, QueryOracleVolatilityRequest, QueryPythPriceRequest,
};
use injective_test_tube::{Module, Oracle, Wasm};
use crate::encode_helper::encode_proto_message;

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
Expand Down
16 changes: 4 additions & 12 deletions contracts/injective-cosmwasm-stargate-example/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use crate::msg::{InstantiateMsg, QueryStargateResponse, MSG_CREATE_DERIVATIVE_LIMIT_ORDER_ENDPOINT, MSG_CREATE_SPOT_LIMIT_ORDER_ENDPOINT};
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use cosmwasm_std::{coin, Addr, Coin};
use crate::msg::{InstantiateMsg, MSG_CREATE_DERIVATIVE_LIMIT_ORDER_ENDPOINT, MSG_CREATE_SPOT_LIMIT_ORDER_ENDPOINT, QueryStargateResponse};
use cosmwasm_std::{Addr, coin, Coin};
use injective_cosmwasm::{checked_address_to_subaccount_id, SubaccountId};
use injective_math::{scale::Scaled, FPDecimal};
use injective_math::{FPDecimal, scale::Scaled};
use injective_std::{
shim::{Any, Timestamp},
types::{
Expand All @@ -29,7 +27,7 @@ use injective_std::{
},
};
use injective_test_tube::{
injective_cosmwasm::get_default_subaccount_id_for_checked_address, Account, Authz, Bank, Exchange, ExecuteResponse, Gov, InjectiveTestApp,
Account, Authz, Bank, Exchange, ExecuteResponse, Gov, injective_cosmwasm::get_default_subaccount_id_for_checked_address, InjectiveTestApp,
Insurance, Module, Oracle, Runner, RunnerResult, SigningAccount, Wasm,
};
use injective_testing::human_to_i64;
Expand Down Expand Up @@ -837,12 +835,6 @@ pub fn create_some_usdt_price_attestation(human_price: &str, decimal_precision:
}
}

pub fn encode_proto_message<T: Message>(msg: T) -> String {
let mut buf = vec![];
T::encode(&msg, &mut buf).unwrap();
BASE64_STANDARD.encode(&buf)
}

pub fn get_stargate_query_result<T: DeserializeOwned>(contract_response: RunnerResult<QueryStargateResponse>) -> serde_json::Result<T> {
let contract_response = contract_response.unwrap().value;
serde_json::from_str::<T>(&contract_response).map_err(|error| {
Expand Down

0 comments on commit 232e4b5

Please sign in to comment.