Skip to content
This repository has been archived by the owner on Dec 29, 2023. It is now read-only.

Commit

Permalink
fix: marketBuy type (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
politeWall authored Nov 25, 2023
1 parent 3beb612 commit 64ad795
Show file tree
Hide file tree
Showing 34 changed files with 151 additions and 94 deletions.
4 changes: 2 additions & 2 deletions front_end_script/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ This function allows you to create a new spot order by sending a transaction to

#### Parameters

- `order_price` ({`base_denom`:String, `quote_denom`:String, `rate` :String}): Price relates two assets exchange rate that the user should define
- `order_price` ({`base_denom`:String, `quote_denom`:String, `rate` :String} or null): Price relates two assets exchange rate that the user should define, can only be null if the order type is "market_type"
- `order_type` (String): The type of the order (e.g., "stop_loss", "limit_sell", "limit_buy", "market_buy").
- `amount_send` (String): The amount of cryptocurrency to send in the order.
- `denom_send` (String): The denomination of the cryptocurrency to send.
Expand Down Expand Up @@ -161,7 +161,7 @@ This function allows you to create a margin order by sending a transaction to th
- `borrow_asset` (String): The asset to borrow for the margin order.
- `take_profit_price` (String): The price at which the order will take profit.
- `order_type` (String): The type of the order (e.g., "stop_loss", "limit_sell", "limit_buy").
- `trigger_price` ({`base_denom`:String, `quote_denom`:String, `rate` :String}): Price relates two assets exchange rate that the user should define
- `trigger_price` ({`base_denom`:String, `quote_denom`:String, `rate` :String} or null): Price relates two assets exchange rate that the user should define, can only be null if the order type is "market_type"

#### Usage

Expand Down
2 changes: 1 addition & 1 deletion scripts/test_amm.sh
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ addr=$(extract_contract_address elysd q tx $instantiate_hash)
sleep 2
elysd tx amm create-pool 100uatom,100uusdc 100000000000uatom,100000000000uusdc --swap-fee=0.00 --exit-fee=0.00 --use-oracle=false --from=treasury --keyring-backend=test --chain-id=elystestnet-1 --yes --gas=1000000
sleep 2
elysd tx wasm exec $addr '{"create_spot_order": { "order_price" : {"base_denom": "uusdc","quote_denom" : "uatom" ,"rate" : "1"}, "order_type" : "stop_loss", "order_target_denom" : "uatom", "order_source_denom" : "uusdc"}}' --from treasury --gas-prices 0.25uelys --gas auto --gas-adjustment 1.3 -b sync -y --keyring-backend=test --chain-id=elystestnet-1 --amount=200uusdc
elysd tx wasm exec $addr '{"create_spot_order": { "order_price" : {"base_denom": "uusdc","quote_denom" : "uatom" ,"rate" : "1"}, "order_type" : "market_buy", "order_target_denom" : "uatom", "order_source_denom" : "uusdc"}}' --from treasury --gas-prices 0.25uelys --gas auto --gas-adjustment 1.3 -b sync -y --keyring-backend=test --chain-id=elystestnet-1 --amount=200uusdc
sleep 2
balance_before=$(elysd q bank balances $addr)
#NOT WORKING ANYMORE
Expand Down
50 changes: 17 additions & 33 deletions src/action/execute/create_margin_order.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use super::*;
use crate::msg::ReplyType;
use cosmwasm_std::{Coin, Decimal, Int128, StdError, StdResult, Storage, SubMsg};
use cosmwasm_std::{Coin, Decimal, Int128, StdError, StdResult};

pub fn create_margin_order(
info: MessageInfo,
Expand All @@ -12,7 +11,7 @@ pub fn create_margin_order(
borrow_asset: String,
take_profit_price: Decimal,
order_type: OrderType,
trigger_price: OrderPrice,
trigger_price: Option<OrderPrice>,
) -> Result<Response<ElysMsg>, ContractError> {
if info.funds.len() != 1 {
return Err(ContractError::CoinNumber);
Expand All @@ -22,6 +21,10 @@ pub fn create_margin_order(
return Err(ContractError::CollateralAmount);
}

if trigger_price.is_none() && order_type != OrderType::MarketBuy {
return Err(StdError::not_found("order price").into());
}

if position == MarginPosition::Short && collateral.denom != "uusdc" {
return Err(
StdError::generic_err("the collateral asset for a short can only be UUSDC").into(),
Expand All @@ -44,7 +47,7 @@ pub fn create_margin_order(
&order_vec,
);

let resp = create_response(deps.storage, &order, env.contract.address)?;
let resp = create_response(&order, env.contract.address)?;

if order.order_type != OrderType::MarketBuy {
order_vec.push(order);
Expand All @@ -56,42 +59,23 @@ pub fn create_margin_order(
}

fn create_response(
storage: &mut dyn Storage,
order: &MarginOrder,
contract_addr: impl Into<String>,
) -> StdResult<Response<ElysMsg>> {
if order.order_type != OrderType::MarketBuy {
return Ok(Response::new().add_attribute("order_id", order.order_id.to_string()));
}

let mut reply_infos = REPLY_INFO.load(storage)?;

let reply_info_id = match reply_infos.iter().max_by_key(|info| info.id) {
Some(info) => info.id + 1,
None => 0,
};

let reply_info = ReplyInfo {
id: reply_info_id,
reply_type: ReplyType::MarginBrokerOpenMarketBuy,
data: None,
};

reply_infos.push(reply_info);

let submsg: SubMsg<ElysMsg> = SubMsg::reply_always(
ElysMsg::margin_broker_open_position(
contract_addr,
&order.collateral.denom,
Int128::new(order.collateral.amount.u128() as i128),
&order.borrow_asset,
order.position.clone() as i32,
order.leverage,
order.take_profit_price,
&order.owner,
),
reply_info_id,
let msg: ElysMsg = ElysMsg::margin_broker_open_position(
contract_addr,
&order.collateral.denom,
Int128::new(order.collateral.amount.u128() as i128),
&order.borrow_asset,
order.position.clone() as i32,
order.leverage,
order.take_profit_price,
&order.owner,
);

Ok(Response::new().add_submessage(submsg))
Ok(Response::new().add_message(msg))
}
14 changes: 10 additions & 4 deletions src/action/execute/create_spot_order.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use cosmwasm_std::{to_json_binary, Decimal, Int128, StdResult, Storage, SubMsg};
use cosmwasm_std::{to_json_binary, Decimal, Int128, StdError, StdResult, Storage, SubMsg};
use elys_bindings::query_resp::AmmSwapEstimationByDenomResponse;

use crate::msg::ReplyType;
Expand All @@ -12,14 +12,18 @@ pub fn create_spot_order(
order_type: OrderType,
order_source_denom: String,
order_target_denom: String,
order_price: OrderPrice,
order_price: Option<OrderPrice>,
) -> Result<Response<ElysMsg>, ContractError> {
if info.funds.len() != 1 {
return Err(ContractError::CoinNumber);
};

let querier = ElysQuerier::new(&deps.querier);

if order_price.is_none() && order_type != OrderType::MarketBuy {
return Err(StdError::not_found("order price").into());
}

check_denom_error(
&order_source_denom,
&order_target_denom,
Expand Down Expand Up @@ -69,7 +73,7 @@ pub fn create_spot_order(
fn check_denom_error(
order_source_denom: &str,
order_target_denom: &str,
order_price: &OrderPrice,
order_price: &Option<OrderPrice>,
order_type: &OrderType,
funds_send_denom: &str,
) -> Result<(), ContractError> {
Expand All @@ -85,6 +89,8 @@ fn check_denom_error(
return Ok(());
}

let order_price = order_price.clone().unwrap();

if (order_price.base_denom != order_source_denom
&& order_price.base_denom != order_target_denom)
|| (order_price.quote_denom != order_source_denom
Expand Down Expand Up @@ -129,7 +135,7 @@ fn create_resp(

reply_infos.push(ReplyInfo {
id: info_id,
reply_type: ReplyType::SpotOrder,
reply_type: ReplyType::SpotOrderMarketBuy,
data: Some(to_json_binary(&new_order.order_id)?),
});

Expand Down
2 changes: 2 additions & 0 deletions src/action/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,12 @@ pub mod reply {
mod close_margin_position;
mod create_margin_order;
mod spot_order;
mod spot_order_market;

pub use close_margin_position::reply_to_close_margin_order;
pub use create_margin_order::reply_to_create_margin_order;
pub use spot_order::reply_to_spot_order;
pub use spot_order_market::reply_to_spot_order_market;
}

pub mod sudo {
Expand Down
49 changes: 49 additions & 0 deletions src/action/reply/spot_order_market.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use cosmwasm_std::{coins, from_json, Binary, DepsMut, StdError, SubMsgResult};

use super::*;

pub fn reply_to_spot_order_market(
deps: DepsMut<ElysQuery>,
data: Option<Binary>,
module_resp: SubMsgResult,
) -> Result<Response<ElysMsg>, ContractError> {
let response = match module_resp.into_result() {
Ok(response) => response,
Err(err) => return Err(StdError::generic_err(err).into()),
};

let meta_data = match response.data {
Some(data) => data,
None => return Err(StdError::generic_err("No Data").into()),
};

let amm_response: AmmSwapExactAmountInResp = from_json(&meta_data)?;

let orders: Vec<SpotOrder> = SPOT_ORDER.load(deps.storage)?;

let order_id: u64 = match data {
Some(order_id) => from_json(&order_id)?,
None => return Err(StdError::generic_err("no meta_data".to_string()).into()),
};

let order: SpotOrder = match orders.iter().find(|order| order.order_id == order_id) {
Some(order) => order.to_owned(),
None => return Err(ContractError::OrderNotFound { order_id }),
};

let bank_msg = BankMsg::Send {
to_address: order.owner_address.to_string(),
amount: coins(
amm_response.token_out_amount.i64() as u128,
order.order_target_denom.to_string(),
),
};

let mut processd_spot_orders = PROCESSED_SPOT_ORDER.load(deps.storage)?;
processd_spot_orders.push((order_id, bank_msg));
PROCESSED_SPOT_ORDER.save(deps.storage, &processd_spot_orders)?;

let resp: Response<ElysMsg> = Response::new();

Ok(resp)
}
2 changes: 1 addition & 1 deletion src/action/sudo/process_spot_orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ fn send_token(

fn check_order(order: &SpotOrder, amm_swap_estimation: &AmmSwapEstimationByDenomResponse) -> bool {
if order.order_type == OrderType::MarketBuy {
return true;
return false;
}

let order_spot_price = match order.order_amount.denom == order.order_price.base_denom {
Expand Down
1 change: 1 addition & 0 deletions src/entry_point/reply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ pub fn reply(
ReplyType::SpotOrder => reply_to_spot_order(deps, info.data, module_resp),
ReplyType::MarginBrokerOpenMarketBuy => reply_to_create_margin_order(module_resp),
ReplyType::MarginBrokerClose => reply_to_close_margin_order(module_resp),
ReplyType::SpotOrderMarketBuy => reply_to_spot_order_market(deps, info.data, module_resp),
_ => return Err(StdError::generic_err("submsg unimplemented").into()),
}
}
4 changes: 2 additions & 2 deletions src/msg/execute_msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub enum ExecuteMsg {
order_type: OrderType,
order_source_denom: String,
order_target_denom: String,
order_price: OrderPrice,
order_price: Option<OrderPrice>,
},
CancelSpotOrder {
order_id: u64,
Expand All @@ -26,7 +26,7 @@ pub enum ExecuteMsg {
borrow_asset: String,
take_profit_price: Decimal,
order_type: OrderType,
trigger_price: OrderPrice,
trigger_price: Option<OrderPrice>,
},

CancelMarginOrder {
Expand Down
1 change: 1 addition & 0 deletions src/msg/reply_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ pub enum ReplyType {
MarginBrokerOpen,
MarginBrokerClose,
MarginBrokerOpenMarketBuy,
SpotOrderMarketBuy,
}
4 changes: 2 additions & 2 deletions src/tests/cancel_margin_order/succesful_cancel_an_order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ fn succesful_cancel_an_order() {
&Decimal::one(),
&Decimal::one(),
&OrderType::LimitBuy,
&OrderPrice {
&Some(OrderPrice {
base_denom: "btc".to_string(),
quote_denom: "usdc".to_string(),
rate: Decimal::one(),
},
}),
&vec![],
)],
};
Expand Down
4 changes: 2 additions & 2 deletions src/tests/cancel_margin_order/unauthorize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ fn unauthorize() {
&Decimal::one(),
&Decimal::one(),
&OrderType::LimitBuy,
&OrderPrice {
&Some(OrderPrice {
base_denom: "btc".to_string(),
quote_denom: "usdc".to_string(),
rate: Decimal::one(),
},
}),
&vec![],
)],
};
Expand Down
4 changes: 2 additions & 2 deletions src/tests/cancel_spot_order/process_spot_order_processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ fn process_spot_order_processing() {
// Create a "limit buy" order (dummy order) with a specific rate and balance.
let dummy_order = SpotOrder::new(
OrderType::LimitBuy,
OrderPrice {
Some(OrderPrice {
base_denom: "ubtc".to_string(),
quote_denom: "usdc".to_string(),
rate: Decimal::from_atomics(Uint128::new(38), 0).unwrap(), // Rate at which ubtc will be bought (38 USDC per ubtc).
},
}),
coin(120, "usdc"), // 120 USDC to be used for buying.
Addr::unchecked("user"),
"ubtc".to_string(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ fn successful_cancel_order_with_created_order() {
addr.clone(),
&ExecuteMsg::CreateSpotOrder {
order_type: OrderType::StopLoss,
order_price: OrderPrice {
order_price: Some(OrderPrice {
rate: Decimal::from_atomics(Uint128::new(18), 0).unwrap(),
base_denom: "btc".to_string(),
quote_denom: "eth".to_string(),
},
}),
order_source_denom: "eth".to_owned(),
order_target_denom: "btc".to_string(),
},
Expand Down
4 changes: 2 additions & 2 deletions src/tests/create_margin_order/coin_number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ fn coin_number() {
borrow_asset: "uatom".to_string(),
take_profit_price: Decimal::from_atomics(Uint128::new(500), 2).unwrap(),
order_type: OrderType::LimitSell,
trigger_price: OrderPrice {
trigger_price: Some(OrderPrice {
base_denom: "uatom".to_string(),
quote_denom: "uusdc".to_string(),
rate: Decimal::from_str("1.5").unwrap(),
},
}),
},
&[],
)
Expand Down
4 changes: 2 additions & 2 deletions src/tests/create_margin_order/collateral_amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ fn collateral_amount() {
borrow_asset: "uatom".to_string(),
take_profit_price: Decimal::from_atomics(Uint128::new(500), 2).unwrap(),
order_type: OrderType::StopLoss,
trigger_price: OrderPrice {
trigger_price: Some(OrderPrice {
base_denom: "uatom".to_string(),
quote_denom: "uusdc".to_string(),
rate: Decimal::from_str("1.25").unwrap(),
},
}),
},
&[coin(45, "usdc")],
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ fn non_usdc_collateral_for_short() {
borrow_asset: "btc".to_string(),
take_profit_price: Decimal::from_atomics(Uint128::new(200), 2).unwrap(),
order_type: OrderType::LimitSell,
trigger_price: OrderPrice {
trigger_price: Some(OrderPrice {
base_denom: "btc".to_string(),
quote_denom: "usdc".to_string(),
rate: Decimal::from_str("1.7").unwrap(),
},
}),
},
&coins(10, "btc"), // User's BTC balance.
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ fn successful_create_margin_market_order() {
borrow_asset: "btc".to_string(),
take_profit_price: Decimal::from_atomics(Uint128::new(200), 2).unwrap(),
order_type: OrderType::MarketBuy,
trigger_price: OrderPrice {
trigger_price: Some(OrderPrice {
base_denom: "btc".to_string(),
quote_denom: "usdc".to_string(),
rate: Decimal::from_str("1.7").unwrap(),
},
}),
},
&coins(10, "btc"), // User's BTC balance.
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ fn successful_create_margin_order() {
borrow_asset: "btc".to_string(),
take_profit_price: Decimal::from_atomics(Uint128::new(200), 2).unwrap(),
order_type: OrderType::LimitSell,
trigger_price: OrderPrice {
trigger_price: Some(OrderPrice {
base_denom: "btc".to_string(),
quote_denom: "usdc".to_string(),
rate: Decimal::from_str("1.7").unwrap(),
},
}),
},
&coins(10, "btc"), // User's BTC balance.
)
Expand Down
Loading

0 comments on commit 64ad795

Please sign in to comment.