Skip to content

Commit

Permalink
Use BoundedBTreeMap in neo-swaps Pool struct
Browse files Browse the repository at this point in the history
  • Loading branch information
maltekliemann committed Feb 7, 2024
1 parent 761cc59 commit c91f48e
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 43 deletions.
10 changes: 5 additions & 5 deletions zrml/neo-swaps/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ pub use pallet::*;
#[frame_support::pallet]
mod pallet {
use crate::{
consts::{LN_NUMERICAL_LIMIT, MAX_ASSETS},
consts::LN_NUMERICAL_LIMIT,
liquidity_tree::types::{BenchmarkInfo, LiquidityTree, LiquidityTreeError},
math::{Math, MathOps},
traits::{pool_operations::PoolOperations, LiquiditySharesManager},
types::{FeeDistribution, Pool},
types::{FeeDistribution, MaxAssets, Pool},
weights::*,
};
use alloc::{collections::BTreeMap, vec, vec::Vec};
Expand Down Expand Up @@ -99,7 +99,7 @@ mod pallet {
pub(crate) type MarketIdOf<T> =
<<T as Config>::MarketCommons as MarketCommonsPalletApi>::MarketId;
pub(crate) type LiquidityTreeOf<T> = LiquidityTree<T, <T as Config>::MaxLiquidityTreeDepth>;
pub(crate) type PoolOf<T> = Pool<T, LiquidityTreeOf<T>>;
pub(crate) type PoolOf<T> = Pool<T, LiquidityTreeOf<T>, MaxAssets>;

#[pallet::config]
pub trait Config: frame_system::Config {
Expand Down Expand Up @@ -833,7 +833,7 @@ mod pallet {
ensure!(market.scoring_rule == ScoringRule::Lmsr, Error::<T>::InvalidTradingMechanism);
let asset_count = spot_prices.len();
ensure!(asset_count as u16 == market.outcomes(), Error::<T>::IncorrectVecLen);
ensure!(market.outcomes() <= MAX_ASSETS, Error::<T>::AssetCountAboveMax);
ensure!(market.outcomes() as u32 <= MaxAssets::get(), Error::<T>::AssetCountAboveMax);
ensure!(swap_fee >= MIN_SWAP_FEE.saturated_into(), Error::<T>::SwapFeeBelowMin);
ensure!(swap_fee <= T::MaxSwapFee::get(), Error::<T>::SwapFeeAboveMax);
ensure!(
Expand Down Expand Up @@ -869,7 +869,7 @@ mod pallet {
let collateral = market.base_asset;
let pool = Pool {
account_id: pool_account_id.clone(),
reserves: reserves.clone(),
reserves: reserves.clone().try_into().map_err(|_| Error::<T>::Unexpected)?,
collateral,
liquidity_parameter,
liquidity_shares_manager: LiquidityTree::new(who.clone(), amount)?,
Expand Down
4 changes: 2 additions & 2 deletions zrml/neo-swaps/src/tests/sell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ fn sell_fails_if_price_is_too_low() {
// speaking this leaves the pool in an inconsistent state (reserve recorded in the `Pool`
// struct is smaller than actual reserve), but this doesn't matter in this test.
NeoSwaps::try_mutate_pool(&market_id, |pool| {
pool.reserves.insert(asset_in, 11 * pool.liquidity_parameter);
pool.reserves.try_insert(asset_in, 11 * pool.liquidity_parameter).unwrap();
Ok(())
})
.unwrap();
Expand Down Expand Up @@ -306,7 +306,7 @@ fn sell_fails_if_price_is_pushed_below_threshold() {
NeoSwaps::try_mutate_pool(&market_id, |pool| {
// The price is right at the brink here. Any further shift and sells won't be accepted
// anymore.
pool.reserves.insert(asset_in, 10 * pool.liquidity_parameter);
pool.reserves.try_insert(asset_in, 10 * pool.liquidity_parameter).unwrap();
Ok(())
})
.unwrap();
Expand Down
26 changes: 26 additions & 0 deletions zrml/neo-swaps/src/types/max_assets.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright 2023-2024 Forecasting Technologies LTD.
//
// This file is part of Zeitgeist.
//
// Zeitgeist is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at
// your option) any later version.
//
// Zeitgeist is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Zeitgeist. If not, see <https://www.gnu.org/licenses/>.

use sp_runtime::traits::Get;

pub(crate) struct MaxAssets;

impl Get<u32> for MaxAssets {
fn get() -> u32 {
128
}
}
2 changes: 2 additions & 0 deletions zrml/neo-swaps/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
// along with Zeitgeist. If not, see <https://www.gnu.org/licenses/>.

mod fee_distribution;
mod max_assets;
mod pool;

pub(crate) use fee_distribution::*;
pub(crate) use max_assets::*;
pub(crate) use pool::*;
51 changes: 15 additions & 36 deletions zrml/neo-swaps/src/types/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,37 +16,43 @@
// along with Zeitgeist. If not, see <https://www.gnu.org/licenses/>.

use crate::{
consts::{EXP_NUMERICAL_LIMIT, MAX_ASSETS},
consts::EXP_NUMERICAL_LIMIT,
math::{Math, MathOps},
pallet::{AssetOf, BalanceOf, Config},
traits::{LiquiditySharesManager, PoolOperations},
Error,
};
use alloc::{collections::BTreeMap, vec::Vec};
use alloc::vec::Vec;
use frame_support::{storage::bounded_btree_map::BoundedBTreeMap, CloneNoBound};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{CheckedAdd, CheckedSub},
traits::{CheckedAdd, CheckedSub, Get},
DispatchError, DispatchResult, RuntimeDebug, SaturatedConversion, Saturating,
};

#[derive(Clone, Decode, Encode, Eq, PartialEq, RuntimeDebug, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct Pool<T: Config, LSM>
#[derive(CloneNoBound, Decode, Encode, Eq, MaxEncodedLen, PartialEq, RuntimeDebug, TypeInfo)]
#[scale_info(skip_type_params(S, T))]
pub struct Pool<T, LSM, S>
where
LSM: LiquiditySharesManager<T>,
T: Config,
LSM: Clone + LiquiditySharesManager<T>,
S: Get<u32>,
{
pub account_id: T::AccountId,
pub reserves: BTreeMap<AssetOf<T>, BalanceOf<T>>,
pub reserves: BoundedBTreeMap<AssetOf<T>, BalanceOf<T>, S>,
pub collateral: AssetOf<T>,
pub liquidity_parameter: BalanceOf<T>,
pub liquidity_shares_manager: LSM,
pub swap_fee: BalanceOf<T>,
}

impl<T: Config, LSM: LiquiditySharesManager<T> + TypeInfo> PoolOperations<T> for Pool<T, LSM>
impl<T, LSM, S> PoolOperations<T> for Pool<T, LSM, S>
where
T: Config,
BalanceOf<T>: SaturatedConversion,
LSM: Clone + LiquiditySharesManager<T> + TypeInfo,
S: Get<u32>,
{
fn assets(&self) -> Vec<AssetOf<T>> {
self.reserves.keys().cloned().collect()
Expand Down Expand Up @@ -117,30 +123,3 @@ where
Math::<T>::calculate_buy_ln_argument(reserve, amount_in, self.liquidity_parameter)
}
}

// TODO(#1214): Replace BTreeMap with BoundedBTreeMap and remove the unnecessary `MaxEncodedLen`
// implementation.
impl<T: Config, LSM: LiquiditySharesManager<T>> MaxEncodedLen for Pool<T, LSM>
where
T::AccountId: MaxEncodedLen,
AssetOf<T>: MaxEncodedLen,
BalanceOf<T>: MaxEncodedLen,
LSM: MaxEncodedLen,
{
fn max_encoded_len() -> usize {
let len_account_id = T::AccountId::max_encoded_len();
let len_reserves = 1usize.saturating_add((MAX_ASSETS as usize).saturating_mul(
<AssetOf<T>>::max_encoded_len().saturating_add(BalanceOf::<T>::max_encoded_len()),
));
let len_collateral = AssetOf::<T>::max_encoded_len();
let len_liquidity_parameter = BalanceOf::<T>::max_encoded_len();
let len_liquidity_shares_manager = LSM::max_encoded_len();
let len_swap_fee = BalanceOf::<T>::max_encoded_len();
len_account_id
.saturating_add(len_reserves)
.saturating_add(len_collateral)
.saturating_add(len_liquidity_parameter)
.saturating_add(len_liquidity_shares_manager)
.saturating_add(len_swap_fee)
}
}

0 comments on commit c91f48e

Please sign in to comment.