Skip to content

Commit

Permalink
Minor Release (#952)
Browse files Browse the repository at this point in the history
## Describe your changes

1. Auto registration during deposit
2. Fixes LMP trading fee bug
3. Fixes TooLowToRedeembug in Rewards pallet
  • Loading branch information
Gauthamastro authored May 6, 2024
2 parents 0ba43f1 + 6a710e4 commit 59461e2
Show file tree
Hide file tree
Showing 26 changed files with 783 additions and 419 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 9 additions & 9 deletions pallets/ocex/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -475,14 +475,14 @@ verify {
assert_eq!(current_fee_distribution.burn_ration, burn_ration);
}

place_bid {
let old_bidder = T::AccountId::decode(&mut &[1; 32][..]).unwrap();
let auction_info: AuctionInfo<T::AccountId, BalanceOf<T>> =
AuctionInfo { fee_info: BTreeMap::new(), highest_bidder: None, highest_bid: Zero::zero() };
<Auction<T>>::put(auction_info);
let bidder = T::AccountId::decode(&mut &[2; 32][..]).unwrap();
let _imbalance = T::NativeCurrency::deposit_creating(&bidder, (100 * UNIT_BALANCE).saturated_into());
}: _(RawOrigin::Signed(bidder), (10 * UNIT_BALANCE).saturated_into())
// place_bid {
// let old_bidder = T::AccountId::decode(&mut &[1; 32][..]).unwrap();
// let auction_info: AuctionInfo<T::AccountId, BalanceOf<T>> =
// AuctionInfo { fee_info: BTreeMap::new(), highest_bidder: None, highest_bid: Zero::zero() };
// <Auction<T>>::put(auction_info);
// let bidder = T::AccountId::decode(&mut &[2; 32][..]).unwrap();
// let _imbalance = T::NativeCurrency::deposit_creating(&bidder, (100 * UNIT_BALANCE).saturated_into());
// }: _(RawOrigin::Signed(bidder), (10 * UNIT_BALANCE).saturated_into())

on_initialize {
let block_no: BlockNumberFor<T> = 200u32.into();
Expand Down Expand Up @@ -604,7 +604,7 @@ use frame_benchmarking::impl_benchmark_test_suite;
use frame_support::traits::fungibles::Create;
use orderbook_primitives::lmp::LMPMarketConfigWrapper;
use orderbook_primitives::ocex::TradingPairConfig;
use polkadex_primitives::auction::AuctionInfo;
// use polkadex_primitives::auction::AuctionInfo;

#[cfg(test)]
impl_benchmark_test_suite!(Ocex, crate::mock::new_test_ext(), crate::mock::Test);
68 changes: 36 additions & 32 deletions pallets/ocex/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1023,28 +1023,28 @@ pub mod pallet {
Ok(())
}

/// Place Bid
#[pallet::call_index(22)]
#[pallet::weight(< T as Config >::WeightInfo::place_bid())]
pub fn place_bid(origin: OriginFor<T>, bid_amount: BalanceOf<T>) -> DispatchResult {
let bidder = ensure_signed(origin)?;
let mut auction_info = <Auction<T>>::get().ok_or(Error::<T>::AuctionNotFound)?;
ensure!(bid_amount > Zero::zero(), Error::<T>::InvalidBidAmount);
ensure!(bid_amount > auction_info.highest_bid, Error::<T>::InvalidBidAmount);
ensure!(
T::NativeCurrency::can_reserve(&bidder, bid_amount),
Error::<T>::InsufficientBalance
);
T::NativeCurrency::reserve(&bidder, bid_amount)?;
if let Some(old_bidder) = auction_info.highest_bidder {
// Un-reserve the old bidder
T::NativeCurrency::unreserve(&old_bidder, auction_info.highest_bid);
}
auction_info.highest_bid = bid_amount;
auction_info.highest_bidder = Some(bidder);
<Auction<T>>::put(auction_info);
Ok(())
}
// /// Place Bid TODO: Enable it after frontend is ready.
// #[pallet::call_index(22)]
// #[pallet::weight(< T as Config >::WeightInfo::place_bid())]
// pub fn place_bid(origin: OriginFor<T>, bid_amount: BalanceOf<T>) -> DispatchResult {
// let bidder = ensure_signed(origin)?;
// let mut auction_info = <Auction<T>>::get().ok_or(Error::<T>::AuctionNotFound)?;
// ensure!(bid_amount > Zero::zero(), Error::<T>::InvalidBidAmount);
// ensure!(bid_amount > auction_info.highest_bid, Error::<T>::InvalidBidAmount);
// ensure!(
// T::NativeCurrency::can_reserve(&bidder, bid_amount),
// Error::<T>::InsufficientBalance
// );
// T::NativeCurrency::reserve(&bidder, bid_amount)?;
// if let Some(old_bidder) = auction_info.highest_bidder {
// // Un-reserve the old bidder
// T::NativeCurrency::unreserve(&old_bidder, auction_info.highest_bid);
// }
// auction_info.highest_bid = bid_amount;
// auction_info.highest_bidder = Some(bidder);
// <Auction<T>>::put(auction_info);
// Ok(())
// }

/// Starts a new liquidity mining epoch
#[pallet::call_index(23)]
Expand Down Expand Up @@ -1706,12 +1706,16 @@ pub mod pallet {
) -> DispatchResult {
ensure!(Self::orderbook_operational_state(), Error::<T>::ExchangeNotOperational);
ensure!(<AllowlistedToken<T>>::get().contains(&asset), Error::<T>::TokenNotAllowlisted);
// Check if account is registered
ensure!(<Accounts<T>>::contains_key(&user), Error::<T>::AccountNotRegistered);
ensure!(amount.saturated_into::<u128>() <= DEPOSIT_MAX, Error::<T>::AmountOverflow);
let converted_amount = Decimal::from(amount.saturated_into::<u128>())
.checked_div(Decimal::from(UNIT_BALANCE))
.ok_or(Error::<T>::FailedToConvertDecimaltoBalance)?;

// if a new user is depositing, then register the user with main account as proxy
if !<Accounts<T>>::contains_key(&user) {
Self::register_user(user.clone(), user.clone())?;
}

Self::transfer_asset(&user, &Self::get_pallet_account(), amount, asset)?;
// Get Storage Map Value
if let Some(expected_total_amount) =
Expand Down Expand Up @@ -2363,21 +2367,21 @@ impl<T: Config> sp_application_crypto::BoundToRuntimeAppPublic for Pallet<T> {
impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
type Key = T::AuthorityId;

fn on_genesis_session<'a, I: 'a>(authorities: I)
where
I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{
fn on_genesis_session<'a, I: 'a + Iterator<Item = (&'a T::AccountId, Self::Key)>>(
authorities: I,
) {
let authorities = authorities.map(|(_, k)| k).collect::<Vec<_>>();
<Authorities<T>>::insert(
GENESIS_AUTHORITY_SET_ID,
ValidatorSet::new(authorities, GENESIS_AUTHORITY_SET_ID),
);
}

fn on_new_session<'a, I: 'a>(_changed: bool, authorities: I, queued_authorities: I)
where
I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{
fn on_new_session<'a, I: 'a + Iterator<Item = (&'a T::AccountId, Self::Key)>>(
_changed: bool,
authorities: I,
queued_authorities: I,
) {
let next_authorities = authorities.map(|(_, k)| k).collect::<Vec<_>>();
let next_queued_authorities = queued_authorities.map(|(_, k)| k).collect::<Vec<_>>();

Expand Down
2 changes: 1 addition & 1 deletion pallets/ocex/src/lmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ impl<T: Config> Pallet<T> {
)?;

// Taker fees is in quote because they put bid order.
let fees = taker_fees.saturating_mul(trade.price);
let fees = taker_fees;
store_fees_paid_by_main_account_in_quote(
state,
epoch,
Expand Down
18 changes: 9 additions & 9 deletions pallets/ocex/src/settlement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ use orderbook_primitives::types::Order;
use orderbook_primitives::{constants::FEE_POT_PALLET_ID, types::Trade};
use parity_scale_codec::{alloc::string::ToString, Decode, Encode};
use polkadex_primitives::{fees::FeeConfig, AccountId, AssetId};
use rust_decimal::RoundingStrategy::ToZero;
use rust_decimal::{prelude::ToPrimitive, Decimal};
use sp_core::crypto::{ByteArray, Ss58AddressFormat, Ss58Codec};
use sp_runtime::traits::AccountIdConversion;
Expand Down Expand Up @@ -104,6 +103,7 @@ pub fn sub_balance(
account: &AccountId,
asset: AssetId,
mut balance: Decimal,
is_withdrawal: bool,
) -> Result<Decimal, &'static str> {
log::info!(target:"ocex", "subtracting {:?} asset {:?} from account {:?}", balance.to_f64().unwrap(), asset.to_string(), account);
let mut balances: BTreeMap<AssetId, Decimal> = match state.get(&account.to_raw_vec())? {
Expand All @@ -115,14 +115,14 @@ pub fn sub_balance(
let account_balance = balances.get_mut(&asset).ok_or("NotEnoughBalance: zero balance")?;

if *account_balance < balance {
// If the deviation is smaller that system limit, then we can allow what's stored in the offchain balance
let deviation = balance.sub(&*account_balance);
if !deviation.round_dp_with_strategy(8, ToZero).is_zero() {
if is_withdrawal {
// If the deviation is smaller that system limit, then we can allow what's stored in the offchain balance
let deviation = balance.sub(&*account_balance);
log::warn!(target:"ocex","[withdrawal] balance deviation of {:?} for asset: {:?}, of account: {:?}: Withdrawing available balance",deviation,asset.to_string(), account.to_ss58check_with_version(Ss58AddressFormat::from(POLKADEX_MAINNET_SS58)));
balance = *account_balance;
} else {
log::error!(target:"ocex","Asset found but balance low for asset: {:?}, of account: {:?}",asset, account);
return Err("NotEnoughBalance");
} else {
log::warn!(target:"ocex","Asset found but minor balance deviation of {:?} for asset: {:?}, of account: {:?}",deviation,asset.to_string(), account.to_ss58check_with_version(Ss58AddressFormat::from(POLKADEX_MAINNET_SS58)));
balance = *account_balance;
}
}
*account_balance = Order::rounding_off(account_balance.saturating_sub(balance));
Expand Down Expand Up @@ -170,7 +170,7 @@ impl<T: Config> Pallet<T> {
add_balance(state, &pot_account, maker_asset.asset, maker_fees)?;

let (maker_asset, maker_debit) = trade.debit(true);
sub_balance(state, &maker_asset.main, maker_asset.asset, maker_debit)?;
sub_balance(state, &maker_asset.main, maker_asset.asset, maker_debit, false)?;
maker_fees
};
let taker_fees = {
Expand All @@ -182,7 +182,7 @@ impl<T: Config> Pallet<T> {
add_balance(state, &pot_account, taker_asset.asset, taker_fees)?;

let (taker_asset, taker_debit) = trade.debit(false);
sub_balance(state, &taker_asset.main, taker_asset.asset, taker_debit)?;
sub_balance(state, &taker_asset.main, taker_asset.asset, taker_debit, false)?;
taker_fees
};

Expand Down
Loading

0 comments on commit 59461e2

Please sign in to comment.