Skip to content
This repository has been archived by the owner on Nov 15, 2024. It is now read-only.

Commit

Permalink
feat: update missing fields
Browse files Browse the repository at this point in the history
  • Loading branch information
cryptokage1996 committed Sep 21, 2024
1 parent 4848a09 commit 6a55533
Show file tree
Hide file tree
Showing 23 changed files with 351 additions and 74 deletions.
2 changes: 2 additions & 0 deletions bindings/src/trade_shield/states/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ mod limit_order;
mod number_of_order;
mod params;
mod perpetual_order;
mod perpetual_order_v2;
mod reply_info;
mod spot_order;

Expand All @@ -14,6 +15,7 @@ pub use params::{
pub use perpetual_order::{
PENDING_PERPETUAL_ORDER, PERPETUAL_ORDER, SORTED_PENDING_PERPETUAL_ORDER, USER_PERPETUAL_ORDER,
};
pub use perpetual_order_v2::{PENDING_PERPETUAL_ORDER_V2, PERPETUAL_ORDER_V2};
pub use reply_info::{MAX_REPLY_ID, REPLY_INFO};
pub use spot_order::{
PENDING_SPOT_ORDER, SORTED_PENDING_SPOT_ORDER, SPOT_ORDER, SPOT_ORDER_MAX_ID, USER_SPOT_ORDER,
Expand Down
7 changes: 7 additions & 0 deletions bindings/src/trade_shield/states/perpetual_order_v2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use crate::trade_shield::types::PerpetualOrderV2;
use cw_storage_plus::Map;

pub const PERPETUAL_ORDER_V2: Map<u64, PerpetualOrderV2> = Map::new("perpetual order2_v2");

pub const PENDING_PERPETUAL_ORDER_V2: Map<u64, PerpetualOrderV2> =
Map::new("unprocess perpetual order_v2");
23 changes: 23 additions & 0 deletions bindings/src/trade_shield/types/from_perpetual_order_to_v2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use super::{PerpetualOrder, PerpetualOrderV2};

impl Into<PerpetualOrderV2> for PerpetualOrder {
fn into(self) -> PerpetualOrderV2 {
PerpetualOrderV2 {
order_id: self.order_id,
owner: self.owner,
order_type: self.order_type,
position: self.position,
trigger_price: self.trigger_price,
collateral: self.collateral,
trading_asset: self.trading_asset,
leverage: self.leverage,
take_profit_price: self.take_profit_price,
position_id: self.position_id,
status: self.status,
size: None,
liquidation: None,
borrow_fee: None,
funding_fee: None,
}
}
}
3 changes: 3 additions & 0 deletions bindings/src/trade_shield/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ mod coin_value;
mod date;
mod denom;
mod fees;
mod from_perpetual_order_to_v2;
mod perpetual_assets;
mod perpetual_order;
mod perpetual_order_plus;
mod perpetual_order_type;
mod perpetual_order_v2;
mod perpetual_position_plus;
mod reply_info;
mod status;
Expand All @@ -31,6 +33,7 @@ pub use perpetual_assets::{PerpetualAsset, PerpetualAssets};
pub use perpetual_order::PerpetualOrder;
pub use perpetual_order_plus::PerpetualOrderPlus;
pub use perpetual_order_type::PerpetualOrderType;
pub use perpetual_order_v2::PerpetualOrderV2;
pub use perpetual_position_plus::PerpetualPositionPlus;
pub use reply_info::ReplyInfo;
pub use spot_order::spot_order::SpotOrder;
Expand Down
6 changes: 3 additions & 3 deletions bindings/src/trade_shield/types/perpetual_order_plus.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{coin, Coin, Decimal, SignedDecimal, StdError, StdResult};

use super::{OrderPrice, PerpetualOrder};
use super::{OrderPrice, PerpetualOrderV2};

#[cw_serde]
pub struct PerpetualOrderPlus {
pub order: PerpetualOrder,
pub order: PerpetualOrderV2,
pub order_price: Option<Decimal>,
pub custody: Coin,
}
Expand Down Expand Up @@ -38,7 +38,7 @@ impl PerpetualOrderPlus {
Ok(coin(custody_value.to_uint_floor().u128(), trading_asset))
}

pub fn new(order: PerpetualOrder) -> StdResult<Self> {
pub fn new(order: PerpetualOrderV2) -> StdResult<Self> {
if order.trigger_price.is_none() {
return Ok(Self {
custody: coin(0, &order.trading_asset),
Expand Down
216 changes: 216 additions & 0 deletions bindings/src/trade_shield/types/perpetual_order_v2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
use std::str::FromStr;

use crate::{trade_shield::states::PENDING_PERPETUAL_ORDER_V2, types::PerpetualPosition};
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{
Coin, DecCoin, Decimal256, OverflowError, SignedDecimal, SignedDecimal256, StdError, StdResult,
Storage,
};

use super::{Fee, OrderPrice, PerpetualOrderType, Status};

#[cw_serde]
pub struct PerpetualOrderV2 {
pub order_id: u64,
pub owner: String,
pub order_type: PerpetualOrderType,
pub position: PerpetualPosition,
pub trigger_price: Option<OrderPrice>,
pub collateral: Coin,
pub trading_asset: String,
pub leverage: SignedDecimal,
pub take_profit_price: Option<SignedDecimal256>,
pub position_id: Option<u64>,
pub status: Status,
pub size: Option<DecCoin>,
pub liquidation: Option<SignedDecimal>,
pub borrow_fee: Option<Fee>,
pub funding_fee: Option<Fee>,
}

impl PerpetualOrderV2 {
pub fn new_open(
owner: impl Into<String>,
position: &PerpetualPosition,
order_type: &PerpetualOrderType,
collateral: &Coin,
trading_asset: impl Into<String>,
leverage: &SignedDecimal,
take_profit_price: &Option<SignedDecimal256>,
trigger_price: &Option<OrderPrice>,
order_vec: &Vec<PerpetualOrderV2>,
size: DecCoin,
liquidation: SignedDecimal,
borrow_fee: Fee,
funding_fee: Fee,
) -> StdResult<Self> {
let status = if order_type == &PerpetualOrderType::MarketOpen {
Status::Executed
} else {
Status::Pending
};

let order_id = get_new_id(&order_vec)?;

let order = Self {
order_id,
owner: owner.into(),
position: position.to_owned(),
collateral: collateral.to_owned(),
trading_asset: trading_asset.into(),
leverage: leverage.to_owned(),
take_profit_price: take_profit_price.to_owned(),
order_type: order_type.to_owned(),
trigger_price: trigger_price.to_owned(),
status,
position_id: None,
size: Some(size),
liquidation: Some(liquidation),
borrow_fee: Some(borrow_fee),
funding_fee: Some(funding_fee),
};

return Ok(order);
}
pub fn new_close(
owner: impl Into<String>,
position: i32,
order_type: &PerpetualOrderType,
collateral: &Coin,
trading_asset: impl Into<String>,
leverage: &SignedDecimal,
position_id: u64,
trigger_price: &Option<OrderPrice>,
take_profit_price: &Option<SignedDecimal256>,
order_vec: &Vec<PerpetualOrderV2>,
) -> StdResult<Self> {
let order_id: u64 = get_new_id(&order_vec)?;

let status = if order_type == &PerpetualOrderType::MarketClose {
Status::Executed
} else {
Status::Pending
};

let position = PerpetualPosition::try_from_i32(position)?;

let order: PerpetualOrderV2 = Self {
order_id,
status,
order_type: order_type.to_owned(),
position,
owner: owner.into(),
trigger_price: trigger_price.to_owned(),
collateral: collateral.to_owned(),
trading_asset: trading_asset.into(),
position_id: Some(position_id),
leverage: leverage.to_owned(),
take_profit_price: take_profit_price.to_owned(),
size: Some(DecCoin::new(Decimal256::zero(), "")),
liquidation: Some(SignedDecimal::zero()),
borrow_fee: Some(Fee::default()),
funding_fee: Some(Fee::default()),
};

Ok(order)
}

pub fn binary_search(
trigger_price: &Option<OrderPrice>,
storage: &dyn Storage,
list: &Vec<u64>,
) -> StdResult<usize> {
let mut low = 0;
let mut high = list.len();
let rate = match trigger_price {
Some(price) => &price.rate,
None => {
return Err(StdError::generic_err(
"perpetual: binary search: price not found",
))
}
};

while low < high {
let mid = low + (high - low) / 2;
let PerpetualOrderV2 { trigger_price, .. } =
match PENDING_PERPETUAL_ORDER_V2.may_load(storage, list[mid])? {
Some(order) => order,
None => {
return Err(StdError::generic_err(
"perpetual: binary search: order not found",
))
}
};
if trigger_price.is_none() {
return Err(StdError::generic_err(
"perpetual: binary search: price not found",
));
}

if trigger_price.unwrap().rate < *rate {
low = mid + 1;
} else {
high = mid;
}
}
Ok(low)
}

pub fn gen_key(&self) -> StdResult<String> {
if self.order_type == PerpetualOrderType::MarketClose
|| self.order_type == PerpetualOrderType::MarketOpen
{
return Err(StdError::generic_err("gen a key on a market order"));
}
if let Some(price) = &self.trigger_price {
Ok(self.position.to_string()
+ "\n"
+ &self.order_type.to_string()
+ "\n"
+ &price.base_denom
+ "\n"
+ &price.quote_denom)
} else {
Err(StdError::not_found("trigger price not found"))
}
}

pub fn from_key(
key: &str,
) -> StdResult<(PerpetualPosition, PerpetualOrderType, String, String)> {
let vec: Vec<&str> = key.split('\n').collect();
if vec.len() != 4 {
return Err(StdError::generic_err("Wrong Key"));
}

let order_position = PerpetualPosition::from_str(vec[0])?;
let order_type = PerpetualOrderType::from_str(vec[1])?;
if order_type == PerpetualOrderType::MarketClose
|| order_type == PerpetualOrderType::MarketOpen
{
return Err(StdError::generic_err("Market Order"));
}

Ok((
order_position,
order_type,
vec[2].to_string(),
vec[3].to_string(),
))
}
}

fn get_new_id(orders: &[PerpetualOrderV2]) -> StdResult<u64> {
match orders.iter().max_by_key(|s| s.order_id) {
Some(order) => match order.order_id.checked_add(1) {
Some(id) => Ok(id),
None => Err(StdError::overflow(OverflowError::new(
cosmwasm_std::OverflowOperation::Add,
"perpetual_order_max_id",
"increment one",
))),
},
None => Ok(0),
}
}
6 changes: 3 additions & 3 deletions bindings/src/trade_shield/types/perpetual_position_plus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{types::Mtp, ElysQuerier};
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Order, SignedDecimal, StdError, StdResult, Storage};

use crate::trade_shield::{states::PENDING_PERPETUAL_ORDER, types::PerpetualOrder};
use crate::trade_shield::{states::PENDING_PERPETUAL_ORDER_V2, types::PerpetualOrderV2};

use super::{OrderPrice, PerpetualOrderType, PerpetualPosition};

Expand Down Expand Up @@ -153,7 +153,7 @@ impl PerpetualPositionPlus {
}

fn get_stop_loss_price(mtp: &Mtp, storage: &dyn Storage) -> Option<OrderPrice> {
let perpetual_order: Option<PerpetualOrder> = PENDING_PERPETUAL_ORDER
let perpetual_order: Option<PerpetualOrderV2> = PENDING_PERPETUAL_ORDER_V2
.prefix_range(storage, None, None, Order::Ascending)
.filter_map(|res| res.ok().map(|r| r.1))
.find(|order| {
Expand All @@ -168,7 +168,7 @@ impl PerpetualPositionPlus {
}

fn get_stop_loss_prices(mtps: &Vec<Mtp>, storage: &dyn Storage) -> Vec<Option<OrderPrice>> {
let perpetual_orders: Vec<PerpetualOrder> = PENDING_PERPETUAL_ORDER
let perpetual_orders: Vec<PerpetualOrderV2> = PENDING_PERPETUAL_ORDER_V2
.prefix_range(storage, None, None, Order::Ascending)
.filter_map(|res| res.ok().map(|r| r.1))
.collect();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub fn cancel_perpetual_order(
if PERPETUAL_ENABLED.load(deps.storage)? == false {
return Err(StdError::generic_err("perpetual endpoint are disable").into());
}
let order = match PERPETUAL_ORDER.may_load(deps.storage, order_id)? {
let order = match PERPETUAL_ORDER_V2.may_load(deps.storage, order_id)? {
Some(order) => order,
None => return Err(ContractError::OrderNotFound { order_id }),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ pub fn cancel_perpetual_orders(
if PERPETUAL_ENABLED.load(deps.storage)? == false {
return Err(StdError::generic_err("perpetual endpoint are disable").into());
}
let orders: Vec<PerpetualOrder> = if let Some(ids) = &order_ids {
let orders: Vec<PerpetualOrderV2> = if let Some(ids) = &order_ids {
if ids.is_empty() {
return Err(StdError::generic_err("order_ids is defined empty").into());
};
let orders = ids
.iter()
.map(|id| PERPETUAL_ORDER.load(deps.storage, *id))
.collect::<Result<Vec<PerpetualOrder>, StdError>>()?;
.map(|id| PERPETUAL_ORDER_V2.load(deps.storage, *id))
.collect::<Result<Vec<PerpetualOrderV2>, StdError>>()?;

if orders
.iter()
Expand All @@ -44,11 +44,11 @@ pub fn cancel_perpetual_orders(

orders
} else {
let orders: Vec<PerpetualOrder> =
let orders: Vec<PerpetualOrderV2> =
match USER_PERPETUAL_ORDER.may_load(deps.storage, info.sender.as_str())? {
Some(v) => v
.iter()
.filter_map(|id| match PERPETUAL_ORDER.load(deps.storage, *id) {
.filter_map(|id| match PERPETUAL_ORDER_V2.load(deps.storage, *id) {
Ok(order)
if order.status == Status::Pending
&& order.order_type != PerpetualOrderType::MarketOpen
Expand Down Expand Up @@ -92,15 +92,15 @@ pub fn cancel_perpetual_orders(
}

fn filter_order_by_type(
orders: Vec<PerpetualOrder>,
orders: Vec<PerpetualOrderV2>,
order_type: Option<PerpetualOrderType>,
) -> Result<Vec<PerpetualOrder>, ContractError> {
) -> Result<Vec<PerpetualOrderV2>, ContractError> {
let order_type = match order_type {
Some(order_type) => order_type,
None => return Ok(orders),
};

let filtered_order: Vec<PerpetualOrder> = orders
let filtered_order: Vec<PerpetualOrderV2> = orders
.iter()
.filter(|order| order.order_type == order_type)
.cloned()
Expand Down
Loading

0 comments on commit 6a55533

Please sign in to comment.