Skip to content

Commit

Permalink
Add reserved balance in Spot order rpc (paritytech#219)
Browse files Browse the repository at this point in the history
* Add reserved_balance in xspot_getOrdersByAccount RPC

* Remove an duplicated event and make the order event more descriptive

* Split out weight_info.rs in Spot

* Update MiningAssetInfo type

* Split out WeightInfo into weight_info.rs

So that we could use a script to generate the weights later.

* Rename PutOrder to NewOrder, etc

Also the other event renamings
  • Loading branch information
liuchengxu authored Sep 4, 2020
1 parent 6a1e7dd commit 000fdd2
Show file tree
Hide file tree
Showing 12 changed files with 216 additions and 183 deletions.
13 changes: 13 additions & 0 deletions scripts/chainx-js/chainx_types_manual.json
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,14 @@
"last_vote_weight_update": "BlockNumber",
"unbonded_chunks": "Vec<RpcUnbonded>"
},
"MiningAssetInfo": {
"asset_id": "AssetId",
"mining_power": "FixedAssetPower",
"reward_pot": "AccountId",
"reward_pot_balance": "RpcBalance",
"last_total_mining_weight": "RpcWeightType",
"last_total_mining_weight_update": "BlockNumber"
},
"Unbonded": {
"value": "Balance",
"locked_until": "BlockNumber"
Expand All @@ -245,6 +253,11 @@
"asks": "Vec<(RpcPrice, RpcBalance)>",
"bids": "Vec<(RpcPrice, RpcBalance)>"
},
"Page": {
"page_index": "u32",
"page_size": "u32",
"data": "Vec<RpcOrder>"
},
"String": "Text",
"RpcPrice": "String",
"RpcBalance": "String",
Expand Down
3 changes: 2 additions & 1 deletion scripts/chainx-js/res/chainx_types.json
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@
"miningPower": "FixedAssetPower",
"rewardPot": "AccountId",
"rewardPotBalance": "RpcBalance",
"ledgerInfo": "RpcAssetLedger<BlockNumber>"
"lastTotalMiningWeight": "RpcWeightType",
"lastTotalMiningWeightUpdate": "BlockNumber"
},
"AssetLedger": {
"lastTotalMiningWeight": "MiningWeight",
Expand Down
25 changes: 2 additions & 23 deletions xpallets/assets-registrar/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod benchmarking;
#[cfg(test)]
mod tests;
mod verifier;
mod weight_info;

use sp_std::{prelude::*, result, slice::Iter};

Expand All @@ -23,7 +24,6 @@ use frame_support::{
dispatch::{DispatchError, DispatchResult},
ensure,
traits::Get,
weights::Weight,
IterableStorageMap, RuntimeDebug,
};
use frame_system::ensure_root;
Expand All @@ -33,30 +33,9 @@ use chainx_primitives::{AssetId, Decimals, Desc, Token};
use xpallet_support::info;

pub use verifier::*;
pub use weight_info::WeightInfo;
pub use xp_assets_registrar::RegistrarHandler;

pub trait WeightInfo {
fn register() -> Weight;
fn deregister() -> Weight;
fn recover() -> Weight;
fn update_asset_info() -> Weight;
}

impl WeightInfo for () {
fn register() -> Weight {
1_000_000_000
}
fn deregister() -> Weight {
1_000_000_000
}
fn recover() -> Weight {
1_000_000_000
}
fn update_asset_info() -> Weight {
1_000_000_000
}
}

#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Copy, Encode, Decode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum Chain {
Expand Down
23 changes: 23 additions & 0 deletions xpallets/assets-registrar/src/weight_info.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use frame_support::weights::Weight;

pub trait WeightInfo {
fn register() -> Weight;
fn deregister() -> Weight;
fn recover() -> Weight;
fn update_asset_info() -> Weight;
}

impl WeightInfo for () {
fn register() -> Weight {
1_000_000_000
}
fn deregister() -> Weight {
1_000_000_000
}
fn recover() -> Weight {
1_000_000_000
}
fn update_asset_info() -> Weight {
1_000_000_000
}
}
32 changes: 16 additions & 16 deletions xpallets/dex/spot/src/execution/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use super::*;
use sp_runtime::traits::CheckedAdd;
use sp_std::cmp::Ordering;

impl<T: Trait> Module<T> {
/// When the price is far from the current handicap, i.e.,
Expand Down Expand Up @@ -45,8 +46,6 @@ impl<T: Trait> Module<T> {
} else {
Self::match_order(&pair, order, &handicap);
}

Self::deposit_event(RawEvent::UpdateOrder(order.clone()));
}

/// Insert a fresh order and return the inserted result.
Expand All @@ -72,7 +71,7 @@ impl<T: Trait> Module<T> {
// The order count of user should be increased after a new order is created.
<OrderCountOf<T>>::insert(&who, order_id + 1);

Self::deposit_event(RawEvent::PutOrder(order.clone()));
Self::deposit_event(RawEvent::NewOrder(order.clone()));

order
}
Expand Down Expand Up @@ -111,8 +110,10 @@ impl<T: Trait> Module<T> {
)
}

/// Match the new putted order. When the matching is complete, we should check
/// if the order has been fulfilled and update the handicap.
/// Match the newly created order.
///
/// When the matching is complete, we should check if the order has been
/// fulfilled and update the handicap.
fn match_order(
pair: &TradingPairProfile,
order: &mut OrderInfo<T>,
Expand Down Expand Up @@ -265,7 +266,7 @@ impl<T: Trait> Module<T> {
let (lowest_ask, highest_bid) = (handicap.lowest_ask, handicap.highest_bid);

// Buy: [ lowest_ask , my_quote ]
// Sell: [ my_quote , highest_bid ]
// Sell: [ my_quote , highest_bid ]
match taker_order.side() {
Side::Buy => Self::match_taker_order_buy(taker_order, pair, lowest_ask),
Side::Sell => Self::match_taker_order_sell(taker_order, pair, highest_bid),
Expand Down Expand Up @@ -303,14 +304,13 @@ impl<T: Trait> Module<T> {
None => panic!("add order.already_filled overflow"),
};

order.status = if order.already_filled == order.amount() {
OrderStatus::Filled
} else if order.already_filled < order.amount() {
OrderStatus::ParitialFill
} else {
panic!("Already filled of an order can't greater than the order's amount.");
order.status = match order.already_filled.cmp(&order.amount()) {
Ordering::Greater => {
panic!("Already filled of an order can't greater than the order's amount.");
}
Ordering::Less => OrderStatus::ParitialFill,
Ordering::Equal => OrderStatus::Filled,
};

order.last_update_at = <frame_system::Module<T>>::block_number();
}

Expand Down Expand Up @@ -380,8 +380,8 @@ impl<T: Trait> Module<T> {
Self::insert_executed_order(maker_order);
Self::insert_executed_order(taker_order);

Self::deposit_event(RawEvent::UpdateOrder(maker_order.clone()));
Self::deposit_event(RawEvent::UpdateOrder(taker_order.clone()));
Self::deposit_event(RawEvent::MakerOrderUpdated(maker_order.clone()));
Self::deposit_event(RawEvent::TakerOrderUpdated(taker_order.clone()));
Self::deposit_event(RawEvent::OrderExecuted(OrderExecutedInfo::new(
trading_history_idx,
pair_id,
Expand Down Expand Up @@ -414,7 +414,7 @@ impl<T: Trait> Module<T> {

OrderInfoOf::<T>::insert(order.submitter(), order.id(), order.clone());

Self::deposit_event(RawEvent::UpdateOrder(order.clone()));
Self::deposit_event(RawEvent::CanceledOrderUpdated(order.clone()));

Ok(())
}
Expand Down
69 changes: 20 additions & 49 deletions xpallets/dex/spot/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
mod execution;
mod rpc;
mod types;
mod weight_info;

#[cfg(any(feature = "runtime-benchmarks", test))]
mod benchmarking;
Expand All @@ -27,7 +28,6 @@ use frame_support::{
dispatch::{DispatchError, DispatchResult},
ensure,
traits::{Currency, Get, ReservableCurrency},
weights::Weight,
Parameter,
};
use frame_system::{ensure_root, ensure_signed};
Expand All @@ -38,6 +38,7 @@ use xpallet_support::info;

pub use rpc::*;
pub use types::*;
pub use weight_info::WeightInfo;

/// Maximum of backlog orders.
const MAX_BACKLOG_ORDER: usize = 1000;
Expand All @@ -58,39 +59,15 @@ pub type BalanceOf<T> = <<T as xpallet_assets::Trait>::Currency as Currency<
<T as frame_system::Trait>::AccountId,
>>::Balance;

pub trait WeightInfo {
fn put_order() -> Weight;
fn cancel_order() -> Weight;
fn force_cancel_order() -> Weight;
fn set_handicap() -> Weight;
fn set_price_fluctuation() -> Weight;
fn add_trading_pair() -> Weight;
fn update_trading_pair() -> Weight;
}
pub type OrderInfo<T> = Order<
TradingPairId,
<T as frame_system::Trait>::AccountId,
BalanceOf<T>,
<T as Trait>::Price,
<T as frame_system::Trait>::BlockNumber,
>;

impl WeightInfo for () {
fn put_order() -> Weight {
1_000_000_000
}
fn cancel_order() -> Weight {
1_000_000_000
}
fn force_cancel_order() -> Weight {
1_000_000_000
}
fn set_handicap() -> Weight {
1_000_000_000
}
fn set_price_fluctuation() -> Weight {
1_000_000_000
}
fn add_trading_pair() -> Weight {
1_000_000_000
}
fn update_trading_pair() -> Weight {
1_000_000_000
}
}
pub type HandicapInfo<T> = Handicap<<T as Trait>::Price>;

pub trait Trait: xpallet_assets::Trait {
/// The overarching event type.
Expand All @@ -109,16 +86,6 @@ pub trait Trait: xpallet_assets::Trait {
type WeightInfo: WeightInfo;
}

pub type OrderInfo<T> = Order<
TradingPairId,
<T as frame_system::Trait>::AccountId,
BalanceOf<T>,
<T as Trait>::Price,
<T as frame_system::Trait>::BlockNumber,
>;

pub type HandicapInfo<T> = Handicap<<T as Trait>::Price>;

decl_storage! {
trait Store for Module<T: Trait> as XSpot {
/// How many trading pairs so far.
Expand Down Expand Up @@ -188,13 +155,17 @@ decl_event!(
<T as Trait>::Price,
{
/// A new order is created.
PutOrder(Order<TradingPairId, AccountId, Balance, Price, BlockNumber>),
/// There is an update to the order due to it's canceled or get executed.
UpdateOrder(Order<TradingPairId, AccountId, Balance, Price, BlockNumber>),
/// The order gets executed.
NewOrder(Order<TradingPairId, AccountId, Balance, Price, BlockNumber>),
/// There is an update to the order due to it gets executed.
MakerOrderUpdated(Order<TradingPairId, AccountId, Balance, Price, BlockNumber>),
/// There is an update to the order due to it gets executed.
TakerOrderUpdated(Order<TradingPairId, AccountId, Balance, Price, BlockNumber>),
/// Overall information about the maker and taker orders when there is an order execution.
OrderExecuted(OrderExecutedInfo<AccountId, Balance, BlockNumber, Price>),
/// There is an update to the order due to it gets canceled.
CanceledOrderUpdated(Order<TradingPairId, AccountId, Balance, Price, BlockNumber>),
/// A new trading pair is added.
AddTradingPair(TradingPairProfile),
TradingPairAdded(TradingPairProfile),
/// Trading pair profile has been updated.
TradingPairUpdated(TradingPairProfile),
/// Price fluctuation of trading pair has been updated.
Expand Down Expand Up @@ -427,7 +398,7 @@ impl<T: Trait> Module<T> {

TradingPairCount::put(pair_id + 1);

Self::deposit_event(RawEvent::AddTradingPair(pair));
Self::deposit_event(RawEvent::TradingPairAdded(pair));
}

fn apply_update_trading_pair(pair_id: TradingPairId, tick_decimals: u32, tradable: bool) {
Expand Down
39 changes: 23 additions & 16 deletions xpallets/dex/spot/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ pub struct RpcOrder<PairId, AccountId, RpcBalance, RpcPrice, BlockNumber> {
pub executed_indices: Vec<TradingHistoryIndex>,
/// The amount of executed, measured by the **base** currency.
pub already_filled: RpcBalance,
/// Current locked asset balance in this order.
pub reserved_balance: RpcBalance,
/// Block number at which the order details updated.
pub last_update_at: BlockNumber,
}
Expand Down Expand Up @@ -201,22 +203,27 @@ impl<T: Trait> Module<T> {
>,
> {
OrderInfoOf::<T>::iter_prefix_values(who)
.map(|order| {
let props: RpcOrderProperty<
TradingPairId,
T::AccountId,
RpcBalance<BalanceOf<T>>,
RpcPrice<T::Price>,
T::BlockNumber,
> = order.props.into();
RpcOrder {
props,
status: order.status,
remaining: order.remaining.into(),
executed_indices: order.executed_indices,
already_filled: order.already_filled.into(),
last_update_at: order.last_update_at,
}
.flat_map(|order| {
Self::trading_pair(order.pair_id())
.ok()
.and_then(|pair| match order.props.side {
Side::Buy => Self::convert_base_to_quote(
order.remaining_in_base(),
order.props.price,
&pair,
)
.ok(),
Side::Sell => Some(order.remaining),
})
.map(|reserved_balance| RpcOrder {
props: order.props.into(),
reserved_balance: reserved_balance.into(),
status: order.status,
remaining: order.remaining.into(),
executed_indices: order.executed_indices,
already_filled: order.already_filled.into(),
last_update_at: order.last_update_at,
})
})
.skip((page_index * page_size) as usize)
.take(page_size as usize)
Expand Down
Loading

0 comments on commit 000fdd2

Please sign in to comment.