Skip to content

Commit

Permalink
update trade event info
Browse files Browse the repository at this point in the history
  • Loading branch information
Chralt98 committed Mar 27, 2024
1 parent abe868a commit 2e58bed
Show file tree
Hide file tree
Showing 5 changed files with 124 additions and 74 deletions.
9 changes: 6 additions & 3 deletions primitives/src/hybrid_router_api_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,24 @@
// You should have received a copy of the GNU General Public License
// along with Zeitgeist. If not, see <https://www.gnu.org/licenses/>.

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
use frame_support::pallet_prelude::*;
use scale_info::TypeInfo;

#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, Debug, TypeInfo)]
pub struct AmmTrade<Balance> {
pub amount_in: Balance,
pub amount_out: Balance,
pub swap_fee_amount: Balance,
pub external_fee_amount: Balance,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, Debug, TypeInfo)]
pub struct ExternalFee<AccountId, Balance> {
pub account: AccountId,
pub amount: Balance,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, Debug, TypeInfo)]
pub struct OrderbookTrade<AccountId, Balance> {
pub filled_maker_amount: Balance,
pub filled_taker_amount: Balance,
Expand Down
109 changes: 43 additions & 66 deletions zrml/hybrid-router/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub use pallet::*;
#[frame_support::pallet]
mod pallet {
use crate::{
types::{Strategy, TxType},
types::{Strategy, Trade, TradeEventInfo, TxType},
weights::WeightInfoZeitgeist,
};
use alloc::{vec, vec::Vec};
Expand All @@ -44,7 +44,7 @@ mod pallet {
pallet_prelude::{Decode, DispatchError, Encode, TypeInfo},
require_transactional,
traits::{IsType, StorageVersion},
BoundedVec, RuntimeDebug, PalletId,
BoundedVec, PalletId, RuntimeDebug,
};
use frame_system::{
ensure_signed,
Expand Down Expand Up @@ -167,12 +167,13 @@ mod pallet {
asset_in: AssetOf<T>,
/// The amount of the `asset_in` provided by the trader.
/// It includes swap and external fees.
/// It is an amount before fees are deducted.
amount_in: BalanceOf<T>,
/// The asset received by the trader.
asset_out: AssetOf<T>,
/// The aggregated amount of the `asset_out` already received
/// by the trader from AMM and orderbook.
/// It is the amount going out after all fees were paid.
/// It is an amount after fees are deducted.
amount_out: BalanceOf<T>,
/// The external fee amount paid in the base asset.
external_fee_amount: BalanceOf<T>,
Expand Down Expand Up @@ -322,9 +323,9 @@ mod pallet {
{
/// Returns a vector of assets corresponding to the given market ID and market type.
/// For scalar outcomes, the returned vector is [LONG, SHORT].
/// For categorical outcomes,
/// For categorical outcomes,
/// the vector starts with the lowest and ends with the highest categorical outcome.
///
///
/// # Arguments
///
/// * `market_id` - The ID of the market.
Expand Down Expand Up @@ -643,65 +644,41 @@ mod pallet {
)?;
}

enum Trade<T: Config> {
Orderbook(OrderTradeOf<T>),
Amm(AmmTradeOf<T>),
}

struct TradeEventInfo<T: Config> {
amount_out: BalanceOf<T>,
external_fee_amount: BalanceOf<T>,
swap_fee_amount: BalanceOf<T>,
}

let TradeEventInfo { amount_out, external_fee_amount, swap_fee_amount } =
orderbook_trades
.iter()
.map(Trade::Orderbook)
.chain(amm_trades.iter().map(Trade::Amm))
.fold(
Ok(TradeEventInfo {
amount_out: BalanceOf::<T>::zero(),
external_fee_amount: BalanceOf::<T>::zero(),
swap_fee_amount: BalanceOf::<T>::zero(),
}),
|event_info, trade| match trade {
Trade::Orderbook(orderbook_trade) => {
let amount_out = event_info
.amount_out
.checked_add_res(orderbook_trade.filled_maker_amount)?;
let external_fee_amount =
if orderbook_trade.external_fee.account == &who {
event_info
.external_fee_amount
.checked_add_res(orderbook_trade.external_fee.amount)
} else {
event_info.external_fee_amount
};
Ok(TradeEventInfo {
amount_out,
external_fee_amount,
swap_fee_amount: event_info.swap_fee_amount,
})
}
Trade::Amm(amm_trade) => {
// TODO For Sell the AMM says on the SellExecuted event that amount_out is with fees not yet deducted. We need to be sure what amount_out is (with regards to order book too. Is the fee included in amount_out there?)
let amount_out =
event_info.amount_out.checked_add_res(amm_trade.amount_out)?;
let external_fee_amount = event_info
.external_fee_amount
.checked_add_res(amm_trade.external_fee_amount)?;
let swap_fee_amount = event_info
.swap_fee_amount
.checked_add_res(amm_trade.swap_fee_amount)?;
Ok(TradeEventInfo {
amount_out,
external_fee_amount,
swap_fee_amount,
})
let event_info = orderbook_trades
.iter()
.map(|trade| Trade::<T>::Orderbook(trade))
.chain(amm_trades.iter().map(|trade| Trade::Amm(*trade)))
.fold(
Ok(TradeEventInfo::<T>::new()),
|event_info: Result<TradeEventInfo<T>, DispatchError>, trade| match event_info {
Ok(mut event_info) => {
match trade {
Trade::Orderbook(orderbook_trade) => {
let external_fee_amount =
if orderbook_trade.external_fee.account == who {
orderbook_trade.external_fee.amount
} else {
BalanceOf::<T>::zero()
};
event_info.add_amount_out_minus_fees(
orderbook_trade.filled_maker_amount,
external_fee_amount,
BalanceOf::<T>::zero(),
)?;
}
Trade::Amm(amm_trade) => {
event_info.add_amount_out_and_fees(
amm_trade.amount_out,
amm_trade.external_fee_amount,
amm_trade.swap_fee_amount,
)?;
}
}
},
)?;
Ok(event_info)
}
Err(e) => return Err(e),
},
)?;

Self::deposit_event(Event::HybridRouterExecuted {
tx_type,
Expand All @@ -711,9 +688,9 @@ mod pallet {
asset_in,
amount_in,
asset_out,
amount_out,
external_fee_amount,
swap_fee_amount,
amount_out: event_info.amount_out(),
external_fee_amount: event_info.external_fee_amount(),
swap_fee_amount: event_info.swap_fee_amount(),
});

Ok(())
Expand Down
66 changes: 66 additions & 0 deletions zrml/hybrid-router/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@
// You should have received a copy of the GNU General Public License
// along with Zeitgeist. If not, see <https://www.gnu.org/licenses/>.

use crate::{AmmTradeOf, BalanceOf, Config, OrderTradeOf};
use frame_support::pallet_prelude::*;
use scale_info::TypeInfo;
use sp_runtime::traits::Zero;
use zeitgeist_primitives::math::checked_ops_res::{CheckedAddRes, CheckedSubRes};

/// Represents the strategy used when placing an order in a trading environment.
#[derive(
Expand Down Expand Up @@ -45,3 +48,66 @@ pub enum TxType {
Buy,
Sell,
}

#[derive(Clone, Debug, Decode, Encode, PartialEq, TypeInfo)]
pub enum Trade<'a, T: Config> {
Orderbook(&'a OrderTradeOf<T>),
Amm(AmmTradeOf<T>),
}

#[derive(Clone, Copy, Debug, Decode, Encode, PartialEq, TypeInfo)]
pub struct TradeEventInfo<T: Config> {
amount_out: BalanceOf<T>,
external_fee_amount: BalanceOf<T>,
swap_fee_amount: BalanceOf<T>,
}

impl<T: Config> TradeEventInfo<T> {
pub fn new() -> Self {
Self {
amount_out: BalanceOf::<T>::zero(),
external_fee_amount: BalanceOf::<T>::zero(),
swap_fee_amount: BalanceOf::<T>::zero(),
}
}

pub fn add_amount_out_minus_fees(
&mut self,
amount: BalanceOf<T>,
external_fee_amount: BalanceOf<T>,
swap_fee_amount: BalanceOf<T>,
) -> Result<(), DispatchError> {
self.external_fee_amount.checked_add_res(&external_fee_amount)?;
self.swap_fee_amount.checked_add_res(&swap_fee_amount)?;
let fees = external_fee_amount.checked_add_res(&swap_fee_amount)?;
let amount_minus_fees = amount.checked_sub_res(&fees)?;
self.amount_out.checked_add_res(&amount_minus_fees)?;

Ok(())
}

pub fn add_amount_out_and_fees(
&mut self,
amount: BalanceOf<T>,
external_fee_amount: BalanceOf<T>,
swap_fee_amount: BalanceOf<T>,
) -> Result<(), DispatchError> {
self.external_fee_amount.checked_add_res(&external_fee_amount)?;
self.swap_fee_amount.checked_add_res(&swap_fee_amount)?;
self.amount_out.checked_add_res(&amount)?;

Ok(())
}

pub fn amount_out(&self) -> BalanceOf<T> {
self.amount_out
}

pub fn external_fee_amount(&self) -> BalanceOf<T> {
self.external_fee_amount
}

pub fn swap_fee_amount(&self) -> BalanceOf<T> {
self.swap_fee_amount
}
}
12 changes: 8 additions & 4 deletions zrml/neo-swaps/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,7 @@ mod pallet {
external_fee_amount: BalanceOf<T>,
},
/// Informant sold a position. `amount_out` is the amount of collateral received by `who`,
/// with swap and external fees not yet deducted. The actual amount received is
/// `amount_out - swap_fee_amount - external_fee_amount`.
/// with swap and external fees already deducted.
SellExecuted {
who: T::AccountId,
market_id: MarketIdOf<T>,
Expand Down Expand Up @@ -656,11 +655,16 @@ mod pallet {
market_id,
asset_in,
amount_in,
amount_out,
amount_out: amount_out_minus_fees,
swap_fee_amount,
external_fee_amount,
});
Ok(AmmTrade { amount_in, amount_out, swap_fee_amount, external_fee_amount })
Ok(AmmTrade {
amount_in,
amount_out: amount_out_minus_fees,
swap_fee_amount,
external_fee_amount,
})
})
}

Expand Down
2 changes: 1 addition & 1 deletion zrml/orderbook/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ mod pallet {
filled_taker_amount: maker_fill,
unfilled_maker_amount: order_data.maker_amount,
unfilled_taker_amount: order_data.taker_amount,
external_fee,
external_fee: external_fee.clone(),
});

Ok(OrderbookTrade {
Expand Down

0 comments on commit 2e58bed

Please sign in to comment.