Skip to content

Commit

Permalink
feat: add more stargate examples
Browse files Browse the repository at this point in the history
  • Loading branch information
gorgos committed Jun 28, 2024
1 parent a20cb20 commit a8c5aee
Show file tree
Hide file tree
Showing 20 changed files with 195 additions and 39 deletions.
1 change: 1 addition & 0 deletions contracts/atomic-order-example/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ fn create_spot_market_handler() -> impl HandlesMarketIdQuery {
status: MarketStatus::Active,
min_price_tick_size: FPDecimal::from_str("0.000000000000001").unwrap(),
min_quantity_tick_size: FPDecimal::from_str("1000000000000000").unwrap(),
min_notional: FPDecimal::ONE,
}),
};
SystemResult::Ok(ContractResult::from(to_json_binary(&response)))
Expand Down
2 changes: 1 addition & 1 deletion contracts/injective-cosmwasm-mock/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
error::ContractError,
handle::{handle_test_transient_derivative_order, handle_test_transient_spot_order},
handle::{handle_test_market_spot_order, handle_test_transient_derivative_order, handle_test_transient_spot_order},
msg::{ExecuteMsg, InstantiateMsg, QueryMsg},
query::{
handle_aggregate_account_volume_query, handle_aggregate_market_volume_query, handle_contract_registration_info_query,
Expand Down
1 change: 1 addition & 0 deletions contracts/injective-cosmwasm-mock/src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::{
contract::{CREATE_DERIVATIVE_ORDER_REPLY_ID, CREATE_SPOT_ORDER_REPLY_ID, MSG_EXEC},
msg::{MSG_CREATE_DERIVATIVE_LIMIT_ORDER_ENDPOINT, MSG_CREATE_SPOT_LIMIT_ORDER_ENDPOINT},
order_management::{create_derivative_limit_order, create_spot_limit_order, create_stargate_msg, encode_bytes_message},
spot_market_order_msg::create_spot_market_order_message,
state::{CacheOrderInfo, ORDER_CALL_CACHE},
ContractError,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ fn test_query_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");
let min_notional = FPDecimal::must_from_str("1");

exchange
.instant_spot_market_launch(
Expand All @@ -158,6 +159,7 @@ fn test_query_spot_market() {
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),
min_notional: dec_to_proto(min_notional),
},
&env.signer,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ fn test_query_derivative_market() {
let maintenance_margin_ratio = FPDecimal::must_from_str("0.05");
let min_price_tick_size = FPDecimal::must_from_str("1000.0");
let min_quantity_tick_size = FPDecimal::must_from_str("1000000000000000");
let min_notional = FPDecimal::must_from_str("1");
let quote_denom = QUOTE_DENOM.to_string();
let maker_fee_rate = FPDecimal::ZERO;
let taker_fee_rate = FPDecimal::ZERO;
Expand All @@ -69,6 +70,7 @@ fn test_query_derivative_market() {
maintenance_margin_ratio: dec_to_proto(maintenance_margin_ratio),
min_price_tick_size: dec_to_proto(min_price_tick_size),
min_quantity_tick_size: dec_to_proto(min_quantity_tick_size),
min_notional: dec_to_proto(min_notional),
},
&env.signer,
)
Expand Down
2 changes: 2 additions & 0 deletions contracts/injective-cosmwasm-mock/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ pub fn launch_spot_market(exchange: &Exchange<InjectiveTestApp>, signer: &Signin
quote_denom: QUOTE_DENOM.to_string(),
min_price_tick_size: dec_to_proto(FPDecimal::must_from_str("0.000000000000001")),
min_quantity_tick_size: dec_to_proto(FPDecimal::must_from_str("1")),
min_notional: dec_to_proto(FPDecimal::must_from_str("1")),
},
signer,
)
Expand Down Expand Up @@ -364,6 +365,7 @@ pub fn launch_perp_market(exchange: &Exchange<InjectiveTestApp>, signer: &Signin
maintenance_margin_ratio: "50000000000000000".to_owned(),
min_price_tick_size: "1000000000000000000000".to_owned(),
min_quantity_tick_size: "1000000000000000".to_owned(),
min_notional: dec_to_proto(FPDecimal::must_from_str("1")),
},
signer,
)
Expand Down
14 changes: 11 additions & 3 deletions contracts/injective-cosmwasm-stargate-example/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::{
error::ContractError,
handle::{handle_test_transient_derivative_order, handle_test_transient_spot_order},
handle::{handle_test_market_spot_order, handle_test_transient_derivative_order, handle_test_transient_spot_order},
msg::{ExecuteMsg, InstantiateMsg, QueryMsg},
query::handle_query_stargate,
query::{handle_query_bank_params, handle_query_spot_market, handle_query_stargate_raw},
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};
Expand Down Expand Up @@ -34,6 +34,12 @@ pub fn execute(
price,
quantity,
} => handle_test_transient_spot_order(deps, env, &info, market_id, subaccount_id, price, quantity),
ExecuteMsg::TestMarketOrderStargate {
market_id,
subaccount_id,
price,
quantity,
} => handle_test_market_spot_order(deps, env.contract.address.as_str(), market_id, subaccount_id, price, quantity),
ExecuteMsg::TestTraderTransientDerivativeOrders {
market_id,
subaccount_id,
Expand All @@ -47,7 +53,9 @@ pub fn execute(
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps<InjectiveQueryWrapper>, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::QueryStargate { path, query_request } => handle_query_stargate(&deps.querier, path, query_request),
QueryMsg::QueryStargateRaw { path, query_request } => handle_query_stargate_raw(&deps.querier, path, query_request),
QueryMsg::QueryBankParams {} => handle_query_bank_params(deps),
QueryMsg::QuerySpotMarket { market_id } => handle_query_spot_market(deps, &market_id),
}
}

Expand Down
25 changes: 25 additions & 0 deletions contracts/injective-cosmwasm-stargate-example/src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::{
contract::{CREATE_DERIVATIVE_ORDER_REPLY_ID, CREATE_SPOT_ORDER_REPLY_ID},
msg::{MSG_CREATE_DERIVATIVE_LIMIT_ORDER_ENDPOINT, MSG_CREATE_SPOT_LIMIT_ORDER_ENDPOINT},
order_management::{create_derivative_limit_order, create_spot_limit_order, create_stargate_msg, encode_bytes_message},
spot_market_order_msg::create_spot_market_order_message,
state::{CacheOrderInfo, ORDER_CALL_CACHE},
ContractError,
};
Expand All @@ -12,6 +13,30 @@ use injective_math::{scale::Scaled, FPDecimal};

pub const MSG_EXEC: &str = "/cosmos.authz.v1beta1.MsgExec";

pub fn handle_test_market_spot_order(
deps: DepsMut<InjectiveQueryWrapper>,
sender: &str,
market_id: MarketId,
subaccount_id: SubaccountId,
price: String,
quantity: String,
) -> Result<Response<InjectiveMsgWrapper>, ContractError> {
let querier = InjectiveQuerier::new(&deps.querier);
let spot_market = querier.query_spot_market(&market_id).unwrap().market.unwrap();

let order_msg = create_spot_market_order_message(
FPDecimal::must_from_str(price.as_str()),
FPDecimal::must_from_str(quantity.as_str()),
OrderType::Sell,
sender,
subaccount_id.as_str(),
"",
&spot_market,
)?;

Ok(Response::new().add_message(order_msg))
}

pub fn handle_test_transient_spot_order(
deps: DepsMut<InjectiveQueryWrapper>,
env: Env,
Expand Down
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 @@ -6,6 +6,7 @@ pub mod msg;
mod order_management;
mod query;
mod reply;
mod spot_market_order_msg;
mod state;
#[cfg(test)]
mod testing;
Expand Down
10 changes: 9 additions & 1 deletion contracts/injective-cosmwasm-stargate-example/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,20 @@ pub enum ExecuteMsg {
quantity: String,
margin: String,
},
TestMarketOrderStargate {
market_id: MarketId,
subaccount_id: SubaccountId,
price: String,
quantity: String,
},
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
QueryStargate { path: String, query_request: String },
QueryStargateRaw { path: String, query_request: String },
QueryBankParams {},
QuerySpotMarket { market_id: String },
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
Expand Down
15 changes: 13 additions & 2 deletions contracts/injective-cosmwasm-stargate-example/src/query.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use crate::msg::QueryStargateResponse;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use cosmwasm_std::{to_json_binary, to_json_vec, Binary, ContractResult, QuerierWrapper, QueryRequest, StdError, StdResult, SystemResult};
use cosmwasm_std::{to_json_binary, to_json_vec, Binary, ContractResult, Deps, QuerierWrapper, QueryRequest, StdError, StdResult, SystemResult};
use injective_cosmwasm::InjectiveQueryWrapper;
use injective_std::types::{cosmos::bank::v1beta1::BankQuerier, injective::exchange::v1beta1::ExchangeQuerier};

pub fn handle_query_stargate(querier: &QuerierWrapper<InjectiveQueryWrapper>, path: String, query_request: String) -> StdResult<Binary> {
pub fn handle_query_stargate_raw(querier: &QuerierWrapper<InjectiveQueryWrapper>, path: String, query_request: String) -> StdResult<Binary> {
let data = Binary::from_base64(&query_request)?;
let request = &QueryRequest::<InjectiveQueryWrapper>::Stargate { path, data };
let raw = to_json_vec(request).map_err(|serialize_err| StdError::generic_err(format!("Serializing QueryRequest: {}", serialize_err)))?;
Expand All @@ -23,3 +24,13 @@ pub fn handle_query_stargate(querier: &QuerierWrapper<InjectiveQueryWrapper>, pa
value: String::from_utf8(decoded_value)?,
})
}

pub fn handle_query_spot_market(deps: Deps<InjectiveQueryWrapper>, market_id: &str) -> StdResult<Binary> {
let querier = ExchangeQuerier::new(&deps.querier);
to_json_binary(&querier.spot_market(market_id.to_string())?)
}

pub fn handle_query_bank_params(deps: Deps<InjectiveQueryWrapper>) -> StdResult<Binary> {
let querier = BankQuerier::new(&deps.querier);
to_json_binary(&querier.params()?)
}
6 changes: 3 additions & 3 deletions contracts/injective-cosmwasm-stargate-example/src/reply.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{encode_helper::encode_proto_message, query::handle_query_stargate, state::ORDER_CALL_CACHE, ContractError};
use crate::{encode_helper::encode_proto_message, query::handle_query_stargate_raw, state::ORDER_CALL_CACHE, ContractError};
use cosmwasm_std::{DepsMut, Event, Reply, Response};
use injective_cosmwasm::InjectiveQueryWrapper;

Expand Down Expand Up @@ -37,7 +37,7 @@ pub fn handle_create_order_reply_stargate(deps: DepsMut<InjectiveQueryWrapper>,
market_id: order_info.market_id.clone().into(),
subaccount_id: order_info.subaccount.clone().into(),
});
let stargate_response = handle_query_stargate(
let stargate_response = handle_query_stargate_raw(
&deps.querier,
"/injective.exchange.v1beta1.Query/TraderSpotTransientOrders".to_string(),
encode_query_message,
Expand All @@ -64,7 +64,7 @@ pub fn handle_create_derivative_order_reply_stargate(deps: DepsMut<InjectiveQuer
market_id: order_info.market_id.clone().into(),
subaccount_id: order_info.subaccount.clone().into(),
});
let stargate_response = handle_query_stargate(
let stargate_response = handle_query_stargate_raw(
&deps.querier,
"/injective.exchange.v1beta1.Query/TraderDerivativeTransientOrders".to_string(),
encode_query_message,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use cosmwasm_std::{CosmosMsg, StdResult};
use injective_cosmwasm::{InjectiveMsgWrapper, OrderType, SpotMarket};
use injective_math::{display::ToProto, round_to_min_tick, round_to_nearest_tick, FPDecimal};
use injective_std::types::injective::exchange::v1beta1 as Exchange;
use prost::Message;

pub fn create_spot_market_order_message(
price: FPDecimal,
quantity: FPDecimal,
order_type: OrderType,
sender: &str,
subaccount_id: &str,
fee_recipient: &str,
market: &SpotMarket,
) -> StdResult<CosmosMsg<InjectiveMsgWrapper>> {
let msg = create_spot_market_order(price, quantity, order_type, sender, subaccount_id, fee_recipient, market);

let mut order_bytes = vec![];
Exchange::MsgCreateSpotMarketOrder::encode(&msg, &mut order_bytes).unwrap();

Ok(CosmosMsg::Stargate {
type_url: Exchange::MsgCreateSpotMarketOrder::TYPE_URL.to_string(),
value: order_bytes.into(),
})
}

fn create_spot_market_order(
price: FPDecimal,
quantity: FPDecimal,
order_type: OrderType,
sender: &str,
subaccount_id: &str,
fee_recipient: &str,
market: &SpotMarket,
) -> Exchange::MsgCreateSpotMarketOrder {
let rounded_quantity = round_to_min_tick(quantity, market.min_quantity_tick_size);
let rounded_price = round_to_nearest_tick(price, market.min_price_tick_size);

Exchange::MsgCreateSpotMarketOrder {
sender: sender.to_string(),
order: Some(Exchange::SpotOrder {
market_id: market.market_id.as_str().into(),
order_info: Some(Exchange::OrderInfo {
subaccount_id: subaccount_id.to_string(),
fee_recipient: fee_recipient.to_string(),
price: rounded_price.to_proto_string(),
quantity: rounded_quantity.to_proto_string(),
cid: "".to_string(),
}),
order_type: order_type as i32,
trigger_price: "".to_string(),
}),
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub struct LastAuctionResult {
fn test_current_auction_basket() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);
let query_msg = QueryMsg::QueryStargate {
let query_msg = QueryMsg::QueryStargateRaw {
path: "/injective.auction.v1beta1.Query/CurrentAuctionBasket".to_string(),
query_request: "".to_string(),
};
Expand All @@ -69,7 +69,7 @@ fn test_current_auction_basket() {
fn test_auction_params() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);
let query_msg = QueryMsg::QueryStargate {
let query_msg = QueryMsg::QueryStargateRaw {
path: "/injective.auction.v1beta1.Query/AuctionParams".to_string(),
query_request: "".to_string(),
};
Expand All @@ -87,7 +87,7 @@ fn test_auction_params() {
fn test_last_auction_result() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);
let query_msg = QueryMsg::QueryStargate {
let query_msg = QueryMsg::QueryStargateRaw {
path: "/injective.auction.v1beta1.Query/LastAuctionResult".to_string(),
query_request: "".to_string(),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use injective_test_tube::{Account, Module, Wasm};
fn test_query_auth_params() {
let env = Setup::new(ExchangeType::None);
let wasm = Wasm::new(&env.app);
let query_msg = QueryMsg::QueryStargate {
let query_msg = QueryMsg::QueryStargateRaw {
path: "/cosmos.auth.v1beta1.Query/Params".to_string(),
query_request: "".to_string(),
};
Expand All @@ -30,7 +30,7 @@ fn test_query_auth_account() {
let wasm = Wasm::new(&env.app);

let user_address = env.users[0].account.address().to_string();
let query_msg = QueryMsg::QueryStargate {
let query_msg = QueryMsg::QueryStargateRaw {
path: "/cosmos.auth.v1beta1.Query/Account".to_string(),
query_request: encode_proto_message(QueryAccountRequest {
address: user_address.to_owned(),
Expand Down
Loading

0 comments on commit a8c5aee

Please sign in to comment.