Skip to content

Commit

Permalink
refactor pendingorders orderpair key type (paritytech#120)
Browse files Browse the repository at this point in the history
* change pendingorders orderpair {first, second, precision} => {first, second}
* format code and modify test
  • Loading branch information
Aton authored Nov 23, 2018
1 parent 02c8eb7 commit 9c6bdc1
Show file tree
Hide file tree
Showing 12 changed files with 310 additions and 199 deletions.
155 changes: 95 additions & 60 deletions Cargo.lock

Large diffs are not rendered by default.

11 changes: 5 additions & 6 deletions cxrml/associations/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,21 +156,20 @@ impl<T: Trait> Module<T> {

if Self::exchange_relationship(&who).is_some() {
return Err("has register this account");
}
}

ExchangeRelationship::<T>::insert(&who, from.clone());

Self::deposit_event(RawEvent::InitExchangeAccount(from, who));
Ok(())
}
pub fn init_channel_relationship( channel: Vec<u8>,who: &T::AccountId) -> Result {

pub fn init_channel_relationship(channel: Vec<u8>, who: &T::AccountId) -> Result {
if Self::channel_relationship(&channel).is_some() {
return Err("has register this channel");
}
}

ChannelRelationship::<T>::insert(channel.clone(), who.clone());
RevChannelRelationship::<T>::insert(who.clone(),channel.clone());
RevChannelRelationship::<T>::insert(who.clone(), channel.clone());

Self::deposit_event(RawEvent::InitChannelRelationship(channel, who.clone()));
Ok(())
Expand Down
2 changes: 1 addition & 1 deletion cxrml/bridge/btc/src/tx/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ impl<T: Trait> TxStorage<T> {
let mut n = Node::new(log);
// insert to the storage, same to TxSet::<T>::insert(hash, xxx)
n.init_storage::<LinkedNodes<T>>();
if let Some(mut tail_index) = TxSetTail::<T>::get() {
if let Some(tail_index) = TxSetTail::<T>::get() {
// get tail
if let Some(mut tail) = TxSet::<T>::get(tail_index.index()) {
// add tx to tail
Expand Down
18 changes: 13 additions & 5 deletions cxrml/exchange/matchorder/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,13 @@ impl associations::Trait for Test {
type OnCalcFee = cxsupport::Module<Test>;
type Event = ();
}

impl cxsupport::Trait for Test {}

impl pendingorders::Trait for Test {
type Event = ();
type Amount = u128;
type Price = u128;
const FEE_BUY_ACCOUNT: <Self as system::Trait>::AccountId = 1;
const FEE_DESTROY_ACCOUNT: <Self as system::Trait>::AccountId = 0;
}

// define tokenbalances module type
Expand Down Expand Up @@ -155,7 +154,10 @@ fn test_match_part() {
let t_eth: Token = Token::new(t_sym_eth.clone(), t_desc_eth.clone(), precision);
assert_eq!(TokenBalances::register_token(t_eth, 0, 0), Ok(()));

let p1 = OrderPair::new(t_sym_eos.clone(), t_sym_eth.clone(), 0);
let p1 = OrderPair {
first: t_sym_eos.clone(),
second: t_sym_eth.clone(),
};

// 增加交易对
PendingOrders::add_pair(p1.clone()).unwrap();
Expand Down Expand Up @@ -251,7 +253,10 @@ fn test_match_all() {
let t_eth: Token = Token::new(t_sym_eth.clone(), t_desc_eth.clone(), precision);
assert_eq!(TokenBalances::register_token(t_eth, 0, 0), Ok(()));

let p1 = OrderPair::new(t_sym_eos.clone(), t_sym_eth.clone(), 0);
let p1 = OrderPair {
first: t_sym_eos.clone(),
second: t_sym_eth.clone(),
};

// 增加交易对
PendingOrders::add_pair(p1.clone()).unwrap();
Expand Down Expand Up @@ -353,7 +358,10 @@ fn test_match_no() {
let t_eth: Token = Token::new(t_sym_eth.clone(), t_desc_eth.clone(), precision);
assert_eq!(TokenBalances::register_token(t_eth, 0, 0), Ok(()));

let p1 = OrderPair::new(t_sym_eos.clone(), t_sym_eth.clone(), 0);
let p1 = OrderPair {
first: t_sym_eos.clone(),
second: t_sym_eth.clone(),
};

// 增加交易对
PendingOrders::add_pair(p1.clone()).unwrap();
Expand Down
106 changes: 59 additions & 47 deletions cxrml/exchange/pendingorders/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ extern crate srml_balances as balances;
extern crate srml_system as system;

// for chainx runtime module lib
extern crate cxrml_support as cxsupport;
extern crate cxrml_tokenbalances as tokenbalances;
extern crate cxrml_associations as associations;
extern crate cxrml_support as cxsupport;
extern crate cxrml_system as cxsystem;
extern crate cxrml_tokenbalances as tokenbalances;

#[cfg(test)]
mod tests;
Expand Down Expand Up @@ -124,7 +124,9 @@ decl_event!(
decl_storage! {
trait Store for Module<T: Trait> as PendingOrders {
pub OrderFee get(order_fee) config(): T::Balance;
pub OrderPairList get(pair_list) config(): Vec<OrderPair> ;
pub OrderPairList get(pair_list) : Vec<OrderPair> ;
pub OrderPairDetailMap get(pair_detail_of) :map OrderPair => Option<OrderPairDetail>;

pub FillIndexOf get(fill_index_of): map OrderPair => u128; //交易对的成交历史的index
pub OrdersOf get(order_of):map (T::AccountId, OrderPair,u64) => Option<OrderT<T>>;
pub LastOrderIndexOf get(last_order_index_of): map(T::AccountId,OrderPair)=>Option<u64>;
Expand All @@ -140,6 +142,21 @@ decl_storage! {
FeeBuyOrder get(fee_buy_order) : map( u64 )=>Option<(OrderPair,T::Amount,T::Price,T::AccountId)>; //存储块尾的买单
FeeBuyOrderMax get(fee_buy_order_max) : u64;
}
add_extra_genesis {
config(pair_list): Vec<(OrderPair, u32)>;
build(
|storage: &mut runtime_primitives::StorageMap, config: &GenesisConfig<T>| {
use codec::Encode;

let mut p_list: Vec<OrderPair> = Vec::new();
for (pair,precision) in config.pair_list.iter() {
let detail = OrderPairDetail{ precision: *precision };
storage.insert(GenesisConfig::<T>::hash(&<OrderPairDetailMap<T>>::key_for(pair)).to_vec(), detail.encode());
p_list.push(pair.clone());
}
storage.insert(GenesisConfig::<T>::hash(&<OrderPairList<T>>::key()).to_vec(), p_list.encode());
});
}
}

impl<T: Trait> OnFinalise<T::BlockNumber> for Module<T> {
Expand Down Expand Up @@ -215,14 +232,20 @@ impl<T: Trait> Module<T> {
<LastAveragePrice<T>>::insert(pair.clone(), price);
}
Some(p) => {
let average_sum: T::Amount = As::sa(
10_u128.pow(pair.precision().as_()) * Self::average_price_len().as_(),
); //将精度考虑进去
let last_average_price: T::Price = As::sa(
(p.as_() * average_sum.as_() + amount.as_() * price.as_())
/ (average_sum.as_() + amount.as_()),
);
<LastAveragePrice<T>>::insert(pair.clone(), last_average_price);
match Self::pair_detail_of(pair.clone()) {
Some(order_pair_detail) => {
let average_sum: T::Amount = As::sa(
10_u128.pow(order_pair_detail.precision.as_())
* Self::average_price_len().as_(),
); //将精度考虑进去
let last_average_price: T::Price = As::sa(
(p.as_() * average_sum.as_() + amount.as_() * price.as_())
/ (average_sum.as_() + amount.as_()),
);
<LastAveragePrice<T>>::insert(pair.clone(), last_average_price);
}
None => {}
}
}
}
}
Expand Down Expand Up @@ -357,10 +380,11 @@ impl<T: Trait> Module<T> {
}
let transactor = ensure_signed(origin)?;
//从channel模块获得channel_name对应的account
let channel: T::AccountId = match <associations::Module<T>>::channel_relationship(&channel_name) {
Some(relation)=>relation,
None=>transactor.clone(),
};
let channel: T::AccountId =
match <associations::Module<T>>::channel_relationship(&channel_name) {
Some(relation) => relation,
None => transactor.clone(),
};
Self::do_put_order(&transactor, &pair, ordertype, amount, price, &channel)
}
pub fn update_command_of(command_id: u64, bid: u128) {
Expand Down Expand Up @@ -610,23 +634,29 @@ impl<T: Trait> Module<T> {
//计算关联账户的额度
let free_token =
<tokenbalances::Module<T>>::free_token(&(account.clone(), symbol.clone()));
let father_free_token:<T as tokenbalances::Trait>::TokenBalance = match <associations::Module<T>>::exchange_relationship(account){
Some(father)=> <tokenbalances::Module<T>>::free_token(&(father.clone(), symbol.clone())),
None=>Zero::zero(),
};
let total_token=free_token+father_free_token;
let father_free_token: <T as tokenbalances::Trait>::TokenBalance =
match <associations::Module<T>>::exchange_relationship(account) {
Some(father) => <tokenbalances::Module<T>>::free_token(&(
father.clone(),
symbol.clone(),
)),
None => Zero::zero(),
};
let total_token = free_token + father_free_token;
//将精度考虑进去
let after_discount: T::Amount = if total_token > As::sa(0) {
if total_token <= As::sa(10_u128.pow(token.precision().as_()) * 10000) {
As::sa((amount.as_() * 7_u128) / 10_u128)
} else if total_token <= As::sa(10_u128.pow(token.precision().as_()) * 100000) {
As::sa((amount.as_() * 6_u128) / 10_u128)
} else if total_token <= As::sa(10_u128.pow(token.precision().as_()) * 1000000) {
} else if total_token <= As::sa(10_u128.pow(token.precision().as_()) * 1000000)
{
As::sa((amount.as_() * 5_u128) / 10_u128)
} else if total_token <= As::sa(10_u128.pow(token.precision().as_()) * 10000000)
{
As::sa((amount.as_() * 3_u128) / 10_u128)
} else if total_token <= As::sa(10_u128.pow(token.precision().as_()) * 100000000)
} else if total_token
<= As::sa(10_u128.pow(token.precision().as_()) * 100000000)
{
As::sa((amount.as_() * 2_u128) / 10_u128)
} else {
Expand Down Expand Up @@ -925,35 +955,17 @@ impl Default for OrderStatus {
}
}

#[derive(PartialEq, Eq, Clone, Encode, Decode)]
#[derive(PartialEq, Eq, Clone, Encode, Decode, Default)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct OrderPair {
first: Symbol,
second: Symbol,
precision: u32, //价格精度
pub first: Symbol,
pub second: Symbol,
}

impl OrderPair {
pub fn new(first: Symbol, second: Symbol, precision: u32) -> Self {
return OrderPair {
first: first,
second: second,
precision: precision,
};
}
pub fn precision(&self) -> u32 {
self.precision
}
}

impl Default for OrderPair {
fn default() -> Self {
OrderPair {
first: Default::default(),
second: Default::default(),
precision: 0,
}
}
#[derive(PartialEq, Eq, Clone, Encode, Decode, Default)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct OrderPairDetail {
pub precision: u32, //价格精度
}

/// 成交的历史,包含了双方的挂单index
Expand Down
17 changes: 8 additions & 9 deletions cxrml/exchange/pendingorders/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,6 @@ impl Trait for Test {
type Event = ();
type Amount = u128;
type Price = u128;
const FEE_BUY_ACCOUNT: <Self as system::Trait>::AccountId = 1;
const FEE_DESTROY_ACCOUNT: <Self as system::Trait>::AccountId = 0;
}

type PendingOrders = Module<Test>;
Expand All @@ -121,12 +119,10 @@ fn test_pair() {
let p1 = OrderPair {
first: b"x-btc".to_vec(),
second: b"x-eth".to_vec(),
precision: 0,
};
let p2 = OrderPair {
first: b"x-eos".to_vec(),
second: b"x-eth".to_vec(),
precision: 0,
};
let mut p_list = Vec::new();
p_list.push(p1.clone());
Expand Down Expand Up @@ -162,7 +158,6 @@ fn test_order() {
let p1 = OrderPair {
first: t_sym_eos.clone(),
second: t_sym_eth.clone(),
precision: 0,
};

let mut p_list = Vec::new();
Expand Down Expand Up @@ -330,7 +325,6 @@ fn test_fill_no_fee() {
let p1 = OrderPair {
first: t_sym_eos.clone(),
second: t_sym_eth.clone(),
precision: 0,
};

// 增加交易对
Expand Down Expand Up @@ -452,7 +446,6 @@ fn test_fill_fee() {
let p1 = OrderPair {
first: t_sym_eos.clone(),
second: t_sym_eth.clone(),
precision: 0,
};

// 增加交易对
Expand Down Expand Up @@ -531,11 +524,17 @@ fn test_fill_fee() {
);

assert_eq!(
TokenBalances::free_token(&(Test::FEE_BUY_ACCOUNT, t_sym_eth.clone())),
TokenBalances::free_token(&(
cxsystem::Module::<Test>::fee_buy_account(),
t_sym_eth.clone()
)),
25
);
assert_eq!(
TokenBalances::free_token(&(Test::FEE_BUY_ACCOUNT, t_sym_eos.clone())),
TokenBalances::free_token(&(
cxsystem::Module::<Test>::fee_buy_account(),
t_sym_eos.clone()
)),
5
);
PendingOrders::clear_command_and_put_fee_buy_order();
Expand Down
2 changes: 1 addition & 1 deletion cxrml/tokenbalances/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ mod mock;
mod tests;

use codec::Codec;
use primitives::traits::{As, CheckedAdd, CheckedSub, Zero,Member, OnFinalise, SimpleArithmetic};
use primitives::traits::{As, CheckedAdd, CheckedSub, Member, OnFinalise, SimpleArithmetic, Zero};
use rstd::prelude::*;
pub use rstd::result::Result as StdResult;
use rstd::slice::Iter;
Expand Down
15 changes: 10 additions & 5 deletions cxrml/tokenbalances/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,12 +365,17 @@ fn test_transfer_not_init() {
let new_id: u64 = 100;
let btc_symbol = b"x-btc".to_vec();
TokenBalances::issue(&a, &btc_symbol.clone(), 50).unwrap();
assert_ok!(TokenBalances::transfer(Some(a).into(), new_id.into(), btc_symbol.clone(), 25));
assert_eq!(Balances::lookup_index(3), Some(new_id));
assert_err!(associations::Module::<Test>::init_account(
assert_ok!(TokenBalances::transfer(
Some(a).into(),
new_id.into(),
), "this account is existing");
btc_symbol.clone(),
25
));
assert_eq!(Balances::lookup_index(3), Some(new_id));
assert_err!(
associations::Module::<Test>::init_account(Some(a).into(), new_id.into(),),
"this account is existing"
);
assert_ok!(TokenBalances::transfer(
Some(a).into(),
new_id.into(),
Expand All @@ -386,7 +391,7 @@ fn test_transfer_not_init() {

assert_eq!(
TokenBalances::free_token(&(a, Test::CHAINX_SYMBOL.to_vec())),
1000 -10 - 10 - 25 - 10
1000 - 10 - 10 - 25 - 10
);
assert_eq!(
TokenBalances::free_token(&(new_id, Test::CHAINX_SYMBOL.to_vec())),
Expand Down
Loading

0 comments on commit 9c6bdc1

Please sign in to comment.