From 8d7a959b2ed9ceb35c513fc01d95233c653a6329 Mon Sep 17 00:00:00 2001 From: Gautham Date: Wed, 24 Jan 2024 17:56:10 +0530 Subject: [PATCH] test runtime build --- Cargo.lock | 7 +- pallets/liquidity-mining/src/callback.rs | 3 +- pallets/liquidity-mining/src/lib.rs | 20 +- pallets/liquidity-mining/src/mock.rs | 221 +++--- pallets/liquidity-mining/src/tests.rs | 935 ++++++++++++++--------- pallets/liquidity-mining/src/types.rs | 1 - pallets/ocex/rpc/runtime-api/src/lib.rs | 4 +- pallets/ocex/src/lib.rs | 5 +- pallets/ocex/src/lmp.rs | 3 +- pallets/ocex/src/tests.rs | 155 ++-- pallets/ocex/src/validator.rs | 2 +- primitives/orderbook/src/lib.rs | 6 +- primitives/orderbook/src/lmp.rs | 3 +- primitives/orderbook/src/types.rs | 36 +- primitives/polkadex/src/assets.rs | 16 +- primitives/polkadex/src/ingress.rs | 15 +- primitives/polkadex/src/ocex.rs | 15 +- runtimes/mainnet/Cargo.toml | 2 - runtimes/mainnet/src/lib.rs | 23 +- 19 files changed, 873 insertions(+), 599 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2cece8eed..22c5617f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5117,7 +5117,6 @@ dependencies = [ "sp-staking", "sp-statement-store", "sp-std", - "sp-storage", "sp-transaction-pool", "sp-version", "static_assertions", @@ -5767,10 +5766,15 @@ dependencies = [ "frame-system", "log", "orderbook-primitives", + "pallet-assets", + "pallet-balances", + "pallet-ocex-lmp", + "pallet-timestamp", "parity-scale-codec", "polkadex-primitives", "rust_decimal", "scale-info", + "sp-application-crypto", "sp-io", "sp-runtime", "sp-std", @@ -5822,6 +5826,7 @@ dependencies = [ "orderbook-primitives", "pallet-assets", "pallet-balances", + "pallet-lmp", "pallet-timestamp", "parity-scale-codec", "polkadex-primitives", diff --git a/pallets/liquidity-mining/src/callback.rs b/pallets/liquidity-mining/src/callback.rs index 5b3c47cd6..cfab641a3 100644 --- a/pallets/liquidity-mining/src/callback.rs +++ b/pallets/liquidity-mining/src/callback.rs @@ -150,7 +150,8 @@ impl LiquidityMiningCrowdSourcePallet for Pallet { base_freed: Decimal, quote_freed: Decimal, ) -> DispatchResult { - let mut pool_config = >::get(market, market_maker).ok_or(Error::::UnknownPool)?; + let mut pool_config = + >::get(market, market_maker).ok_or(Error::::UnknownPool)?; pool_config.force_closed = true; >::insert(market, market_maker, pool_config); let base_freed = base_freed diff --git a/pallets/liquidity-mining/src/lib.rs b/pallets/liquidity-mining/src/lib.rs index c074e9b82..33b796c8b 100644 --- a/pallets/liquidity-mining/src/lib.rs +++ b/pallets/liquidity-mining/src/lib.rs @@ -15,8 +15,6 @@ // // You should have received a copy of the GNU General Public License // along with this program. If not, see . -#![cfg_attr(not(feature = "std"), no_std)] - // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] @@ -37,6 +35,7 @@ mod tests; pub mod pallet { use super::*; use crate::types::MarketMakerConfig; + use core::ops::{Div, DivAssign, MulAssign}; use frame_support::{ pallet_prelude::*, sp_runtime::{traits::AccountIdConversion, SaturatedConversion}, @@ -60,15 +59,18 @@ pub mod pallet { Saturating, }; use sp_std::collections::btree_map::BTreeMap; - use core::ops::{Div, DivAssign, MulAssign}; type BalanceOf = <::NativeCurrency as Currency< ::AccountId, >>::Balance; - type SumOfScores = BalanceOf; - type MMScore = BalanceOf; + type SumOfScores = BalanceOf; + type MMScore = BalanceOf; type MMClaimFlag = bool; - type MMInfo = (BTreeMap, MMClaimFlag)>, SumOfScores, MMClaimFlag); + type MMInfo = ( + BTreeMap<::AccountId, (MMScore, MMClaimFlag)>, + SumOfScores, + MMClaimFlag, + ); #[pallet::config] pub trait Config: frame_system::Config + SendTransactionTypes> { @@ -384,7 +386,9 @@ pub mod pallet { market.quote.asset_id().ok_or(Error::::ConversionError)?, &market_maker, &pool, - T::OtherAssets::minimum_balance(market.quote.asset_id().ok_or(Error::::ConversionError)?), + T::OtherAssets::minimum_balance( + market.quote.asset_id().ok_or(Error::::ConversionError)?, + ), Preservation::Preserve, )?; // Register on OCEX pallet @@ -396,7 +400,7 @@ pub mod pallet { exit_fee, public_funds_allowed, name, - share_id: share_id, + share_id, force_closed: false, }; >::insert(market, market_maker, config); diff --git a/pallets/liquidity-mining/src/mock.rs b/pallets/liquidity-mining/src/mock.rs index bf73e43f1..9159cefe2 100644 --- a/pallets/liquidity-mining/src/mock.rs +++ b/pallets/liquidity-mining/src/mock.rs @@ -20,22 +20,22 @@ use crate::*; use frame_support::{ - parameter_types, - traits::{AsEnsureOriginWithArg, ConstU128, ConstU64, OnTimestampSet}, - PalletId, + pallet_prelude::Weight, + parameter_types, + traits::{AsEnsureOriginWithArg, ConstU128, ConstU64, OnTimestampSet}, + PalletId, }; use frame_system::{EnsureRoot, EnsureSigned}; use polkadex_primitives::{Moment, Signature}; use sp_application_crypto::sp_core::H256; use sp_std::cell::RefCell; -use frame_support::pallet_prelude::Weight; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. +use pallet_ocex_lmp as ocex; use sp_runtime::{ - traits::{BlakeTwo256, IdentityLookup}, - BuildStorage, + traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, }; -use pallet_ocex_lmp as ocex; // Reexport crate as its pallet name for construct_runtime. type Block = frame_system::mocking::MockBlock; @@ -47,8 +47,8 @@ frame_support::construct_runtime!( Balances: pallet_balances, Assets: pallet_assets, Timestamp: pallet_timestamp, - LiqudityMining: crate::pallet, - OCEX: ocex, + LiqudityMining: crate::pallet, + OCEX: ocex, } ); @@ -57,45 +57,45 @@ parameter_types! { frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1024, 64)); } impl frame_system::Config for Test { - type BaseCallFilter = frame_support::traits::Everything; - type BlockWeights = (); - type BlockLength = (); - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = sp_runtime::AccountId32; - type Lookup = IdentityLookup; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = ConstU64<250>; - type DbWeight = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; - type Nonce = u64; - type Block = Block; + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = (); + type BlockLength = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = sp_runtime::AccountId32; + type Lookup = IdentityLookup; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = ConstU64<250>; + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; + type Nonce = u64; + type Block = Block; } impl pallet_balances::Config for Test { - type RuntimeEvent = RuntimeEvent; - type WeightInfo = (); - type Balance = u128; - type DustRemoval = (); - type ExistentialDeposit = ConstU128<1>; - type AccountStore = System; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = (); - type FreezeIdentifier = (); - type MaxLocks = (); - type MaxReserves = (); - type MaxHolds = (); - type MaxFreezes = (); + type RuntimeEvent = RuntimeEvent; + type WeightInfo = (); + type Balance = u128; + type DustRemoval = (); + type ExistentialDeposit = ConstU128<1>; + type AccountStore = System; + type ReserveIdentifier = [u8; 8]; + type RuntimeHoldReason = (); + type FreezeIdentifier = (); + type MaxLocks = (); + type MaxReserves = (); + type MaxHolds = (); + type MaxFreezes = (); } thread_local! { @@ -104,49 +104,48 @@ thread_local! { pub struct MockOnTimestampSet; impl OnTimestampSet for MockOnTimestampSet { - fn on_timestamp_set(moment: Moment) { - CAPTURED_MOMENT.with(|x| *x.borrow_mut() = Some(moment)); - } + fn on_timestamp_set(moment: Moment) { + CAPTURED_MOMENT.with(|x| *x.borrow_mut() = Some(moment)); + } } impl pallet_timestamp::Config for Test { - type Moment = Moment; - type OnTimestampSet = MockOnTimestampSet; - type MinimumPeriod = ConstU64<5>; - type WeightInfo = (); + type Moment = Moment; + type OnTimestampSet = MockOnTimestampSet; + type MinimumPeriod = ConstU64<5>; + type WeightInfo = (); } parameter_types! { pub const ProxyLimit: u32 = 2; pub const OcexPalletId: PalletId = PalletId(*b"OCEX_LMP"); - pub const TresuryPalletId: PalletId = PalletId(*b"OCEX_TRE"); - pub const LMPRewardsPalletId: PalletId = PalletId(*b"OCEX_TMP"); + pub const TresuryPalletId: PalletId = PalletId(*b"OCEX_TRE"); + pub const LMPRewardsPalletId: PalletId = PalletId(*b"OCEX_TMP"); pub const MsPerDay: u64 = 86_400_000; } impl crate::pallet::Config for Test { - type RuntimeEvent = RuntimeEvent; - type OCEX = OCEX; - type PalletId = LMPRewardsPalletId; - type NativeCurrency = Balances; - type OtherAssets = Assets; + type RuntimeEvent = RuntimeEvent; + type OCEX = OCEX; + type PalletId = LMPRewardsPalletId; + type NativeCurrency = Balances; + type OtherAssets = Assets; } impl ocex::Config for Test { - type RuntimeEvent = RuntimeEvent; - type PalletId = OcexPalletId; - type TreasuryPalletId = TresuryPalletId; - type LMPRewardsPalletId = LMPRewardsPalletId; - type NativeCurrency = Balances; - type OtherAssets = Assets; - type EnclaveOrigin = EnsureRoot; - type AuthorityId = ocex::sr25519::AuthorityId; - type GovernanceOrigin = EnsureRoot; - type CrowdSourceLiqudityMining = LiqudityMining; - type WeightInfo = ocex::weights::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type PalletId = OcexPalletId; + type TreasuryPalletId = TresuryPalletId; + type LMPRewardsPalletId = LMPRewardsPalletId; + type NativeCurrency = Balances; + type OtherAssets = Assets; + type EnclaveOrigin = EnsureRoot; + type AuthorityId = ocex::sr25519::AuthorityId; + type GovernanceOrigin = EnsureRoot; + type CrowdSourceLiqudityMining = LiqudityMining; + type WeightInfo = ocex::weights::WeightInfo; } - parameter_types! { pub const AssetDeposit: u128 = 100; pub const ApprovalDeposit: u128 = 1; @@ -156,64 +155,64 @@ parameter_types! { } impl pallet_assets::Config for Test { - type RuntimeEvent = RuntimeEvent; - type Balance = u128; - type RemoveItemsLimit = (); - type AssetId = u128; - type AssetIdParameter = parity_scale_codec::Compact; - type Currency = Balances; - type CreateOrigin = AsEnsureOriginWithArg>; - type ForceOrigin = EnsureRoot; - type AssetDeposit = AssetDeposit; - type AssetAccountDeposit = AssetDeposit; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type ApprovalDeposit = ApprovalDeposit; - type StringLimit = StringLimit; - type Freezer = (); - type Extra = (); - type CallbackHandle = (); - type WeightInfo = (); + type RuntimeEvent = RuntimeEvent; + type Balance = u128; + type RemoveItemsLimit = (); + type AssetId = u128; + type AssetIdParameter = parity_scale_codec::Compact; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = EnsureRoot; + type AssetDeposit = AssetDeposit; + type AssetAccountDeposit = AssetDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = StringLimit; + type Freezer = (); + type Extra = (); + type CallbackHandle = (); + type WeightInfo = (); } pub fn new_test_ext() -> sp_io::TestExternalities { - let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext } use sp_runtime::{ - testing::TestXt, - traits::{Extrinsic as ExtrinsicT, IdentifyAccount, Verify}, + testing::TestXt, + traits::{Extrinsic as ExtrinsicT, IdentifyAccount, Verify}, }; type Extrinsic = TestXt; type AccountId = <::Signer as IdentifyAccount>::AccountId; impl frame_system::offchain::SigningTypes for Test { - type Public = ::Signer; - type Signature = Signature; + type Public = ::Signer; + type Signature = Signature; } impl frame_system::offchain::SendTransactionTypes for Test - where - RuntimeCall: From, +where + RuntimeCall: From, { - type Extrinsic = Extrinsic; - type OverarchingCall = RuntimeCall; + type Extrinsic = Extrinsic; + type OverarchingCall = RuntimeCall; } impl frame_system::offchain::CreateSignedTransaction for Test - where - RuntimeCall: From, +where + RuntimeCall: From, { - fn create_transaction>( - call: RuntimeCall, - _public: ::Signer, - _account: AccountId, - nonce: u64, - ) -> Option<(RuntimeCall, ::SignaturePayload)> { - Some((call, (nonce, ()))) - } + fn create_transaction>( + call: RuntimeCall, + _public: ::Signer, + _account: AccountId, + nonce: u64, + ) -> Option<(RuntimeCall, ::SignaturePayload)> { + Some((call, (nonce, ()))) + } } diff --git a/pallets/liquidity-mining/src/tests.rs b/pallets/liquidity-mining/src/tests.rs index c1e2813f6..cc817045d 100644 --- a/pallets/liquidity-mining/src/tests.rs +++ b/pallets/liquidity-mining/src/tests.rs @@ -18,459 +18,664 @@ //! Tests for pallet-lmp. -use std::collections::BTreeMap; -use std::ops::DivAssign; -use std::process::exit; -use frame_support::{assert_noop, assert_ok}; use crate::mock::*; -use frame_support::testing_prelude::bounded_vec; +use frame_support::{assert_noop, assert_ok, testing_prelude::bounded_vec}; use frame_system::EventRecord; -use sp_core::crypto::AccountId32; -use orderbook_primitives::constants::UNIT_BALANCE; -use orderbook_primitives::types::TradingPair; +use orderbook_primitives::{constants::UNIT_BALANCE, types::TradingPair}; use polkadex_primitives::AssetId; - +use sp_core::crypto::AccountId32; +use std::{collections::BTreeMap, ops::DivAssign, process::exit}; #[test] fn test_register_pool_happy_path() { - new_test_ext().execute_with(|| { - // Register market OCEX - let name = [1;10]; - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let commission = UNIT_BALANCE * 1; - let exit_fee = UNIT_BALANCE * 1; - let public_fund_allowed = true; - let trading_account = AccountId32::new([1;32]); - let market_maker = AccountId32::new([2;32]); - register_test_trading_pair(); - mint_base_quote_asset_for_user(market_maker.clone()); - assert_ok!(LiqudityMining::register_pool(RuntimeOrigin::signed(market_maker.clone()), name, trading_pair, commission, exit_fee, public_fund_allowed, trading_account.clone())); - // Verification - assert!(LiqudityMining::lmp_pool(trading_pair, market_maker.clone()).is_some()); - assert_noop!(LiqudityMining::register_pool(RuntimeOrigin::signed(market_maker.clone()), name, trading_pair, commission, exit_fee, public_fund_allowed, trading_account), crate::pallet::Error::::PoolExists); - }) + new_test_ext().execute_with(|| { + // Register market OCEX + let name = [1; 10]; + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let commission = UNIT_BALANCE * 1; + let exit_fee = UNIT_BALANCE * 1; + let public_fund_allowed = true; + let trading_account = AccountId32::new([1; 32]); + let market_maker = AccountId32::new([2; 32]); + register_test_trading_pair(); + mint_base_quote_asset_for_user(market_maker.clone()); + assert_ok!(LiqudityMining::register_pool( + RuntimeOrigin::signed(market_maker.clone()), + name, + trading_pair, + commission, + exit_fee, + public_fund_allowed, + trading_account.clone() + )); + // Verification + assert!(LiqudityMining::lmp_pool(trading_pair, market_maker.clone()).is_some()); + assert_noop!( + LiqudityMining::register_pool( + RuntimeOrigin::signed(market_maker.clone()), + name, + trading_pair, + commission, + exit_fee, + public_fund_allowed, + trading_account + ), + crate::pallet::Error::::PoolExists + ); + }) } #[test] fn test_register_pool_error_unknown_pool() { - new_test_ext().execute_with(|| { - let name = [1;10]; - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let commission = UNIT_BALANCE * 1; - let exit_fee = UNIT_BALANCE * 1; - let public_fund_allowed = true; - let trading_account = AccountId32::new([1;32]); - let market_maker = AccountId32::new([2;32]); - mint_base_quote_asset_for_user(market_maker.clone()); - assert_noop!(LiqudityMining::register_pool(RuntimeOrigin::signed(market_maker.clone()), name, trading_pair, commission, exit_fee, public_fund_allowed, trading_account.clone()), crate::pallet::Error::::UnknownMarket); - }) + new_test_ext().execute_with(|| { + let name = [1; 10]; + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let commission = UNIT_BALANCE * 1; + let exit_fee = UNIT_BALANCE * 1; + let public_fund_allowed = true; + let trading_account = AccountId32::new([1; 32]); + let market_maker = AccountId32::new([2; 32]); + mint_base_quote_asset_for_user(market_maker.clone()); + assert_noop!( + LiqudityMining::register_pool( + RuntimeOrigin::signed(market_maker.clone()), + name, + trading_pair, + commission, + exit_fee, + public_fund_allowed, + trading_account.clone() + ), + crate::pallet::Error::::UnknownMarket + ); + }) } -use frame_support::traits::fungibles::Inspect; -use rust_decimal::Decimal; -use rust_decimal::prelude::{FromPrimitive}; use crate::pallet::{Pools, SnapshotFlag}; +use frame_support::traits::fungibles::Inspect; +use rust_decimal::{prelude::FromPrimitive, Decimal}; #[test] fn test_register_pool_error_register_pool_fails() { - new_test_ext().execute_with(|| { - let main_account = AccountId32::new([1;32]); - let trading_account = AccountId32::new([2;32]); - assert_ok!(OCEX::set_exchange_state(RuntimeOrigin::root(), true)); - assert_ok!(OCEX::register_user(main_account, trading_account)); - let name = [1;10]; - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let commission = UNIT_BALANCE * 1; - let exit_fee = UNIT_BALANCE * 1; - let public_fund_allowed = true; - let trading_account = AccountId32::new([2;32]); - let market_maker = AccountId32::new([1;32]); - register_test_trading_pair(); - mint_base_quote_asset_for_user(market_maker.clone()); - assert_noop!(LiqudityMining::register_pool(RuntimeOrigin::signed(market_maker.clone()), name, trading_pair, commission, exit_fee, public_fund_allowed, trading_account.clone()), pallet_ocex_lmp::pallet::Error::::ProxyAlreadyRegistered); - let (pool, share_id) = LiqudityMining::create_pool_account(&market_maker, trading_pair); - // Check if Asset is registered or not - assert!(!Assets::asset_exists(share_id)); //Verify this with @gautham - }) + new_test_ext().execute_with(|| { + let main_account = AccountId32::new([1; 32]); + let trading_account = AccountId32::new([2; 32]); + assert_ok!(OCEX::set_exchange_state(RuntimeOrigin::root(), true)); + assert_ok!(OCEX::register_user(main_account, trading_account)); + let name = [1; 10]; + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let commission = UNIT_BALANCE * 1; + let exit_fee = UNIT_BALANCE * 1; + let public_fund_allowed = true; + let trading_account = AccountId32::new([2; 32]); + let market_maker = AccountId32::new([1; 32]); + register_test_trading_pair(); + mint_base_quote_asset_for_user(market_maker.clone()); + assert_noop!( + LiqudityMining::register_pool( + RuntimeOrigin::signed(market_maker.clone()), + name, + trading_pair, + commission, + exit_fee, + public_fund_allowed, + trading_account.clone() + ), + pallet_ocex_lmp::pallet::Error::::ProxyAlreadyRegistered + ); + let (pool, share_id) = LiqudityMining::create_pool_account(&market_maker, trading_pair); + // Check if Asset is registered or not + assert!(!Assets::asset_exists(share_id)); //Verify this with @gautham + }) } -use pallet_ocex_lmp::pallet::PriceOracle; -use frame_support::traits::fungibles::{Create, Mutate as MutateNonNative}; -use frame_support::traits::fungible::Mutate; +use frame_support::traits::{ + fungible::Mutate, + fungibles::{Create, Mutate as MutateNonNative}, +}; use log::log; -use sp_runtime::ArithmeticError::Underflow; -use sp_runtime::traits::One; +use pallet_ocex_lmp::pallet::PriceOracle; +use sp_runtime::{traits::One, ArithmeticError::Underflow}; #[test] fn test_add_liquidity_happy_path() { - new_test_ext().execute_with(|| { - register_test_pool(true); - // Set snapshot flag - //>::put(None); - // Allowlist Token - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), base_asset)); - assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), quote_asset)); - // Put average price in OCEX Pallet - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let mut price = Decimal::from_u128(UNIT_BALANCE * 5).unwrap(); - price.div_assign(Decimal::from(UNIT_BALANCE)); - let tick = Decimal::from_u128(UNIT_BALANCE * 1).unwrap(); - let trading_account = AccountId32::new([1;32]); - let market_maker = AccountId32::new([2;32]); - let user_who_wants_to_add_liq = AccountId32::new([3;32]); - let mut map = BTreeMap::new(); - map.insert((base_asset, quote_asset), (price, tick)); - >::set(map); - // Cretae Base and Quote Asset; - mint_base_quote_asset_for_user(user_who_wants_to_add_liq.clone()); - assert_ok!(LiqudityMining::add_liquidity(RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), trading_pair, market_maker, UNIT_BALANCE * 6, UNIT_BALANCE * 40)); - // * Check user balance - assert_eq!(Balances::free_balance(&user_who_wants_to_add_liq), UNIT_BALANCE * 94); - // TODO: Check pool balance and pallet account balance - }) + new_test_ext().execute_with(|| { + register_test_pool(true); + // Set snapshot flag + //>::put(None); + // Allowlist Token + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), base_asset)); + assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), quote_asset)); + // Put average price in OCEX Pallet + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let mut price = Decimal::from_u128(UNIT_BALANCE * 5).unwrap(); + price.div_assign(Decimal::from(UNIT_BALANCE)); + let tick = Decimal::from_u128(UNIT_BALANCE * 1).unwrap(); + let trading_account = AccountId32::new([1; 32]); + let market_maker = AccountId32::new([2; 32]); + let user_who_wants_to_add_liq = AccountId32::new([3; 32]); + let mut map = BTreeMap::new(); + map.insert((base_asset, quote_asset), (price, tick)); + >::set(map); + // Cretae Base and Quote Asset; + mint_base_quote_asset_for_user(user_who_wants_to_add_liq.clone()); + assert_ok!(LiqudityMining::add_liquidity( + RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), + trading_pair, + market_maker, + UNIT_BALANCE * 6, + UNIT_BALANCE * 40 + )); + // * Check user balance + assert_eq!(Balances::free_balance(&user_who_wants_to_add_liq), UNIT_BALANCE * 94); + // TODO: Check pool balance and pallet account balance + }) } #[test] fn test_add_liquidity_error_public_fund_not_allowed() { - new_test_ext().execute_with(|| { - register_test_pool(false); - let market_maker = AccountId32::new([2;32]); - let user_who_wants_to_add_liq = AccountId32::new([3;32]); - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - assert_noop!(LiqudityMining::add_liquidity(RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), trading_pair, market_maker, UNIT_BALANCE * 6, UNIT_BALANCE * 40), crate::pallet::Error::::PublicDepositsNotAllowed); - }) + new_test_ext().execute_with(|| { + register_test_pool(false); + let market_maker = AccountId32::new([2; 32]); + let user_who_wants_to_add_liq = AccountId32::new([3; 32]); + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + assert_noop!( + LiqudityMining::add_liquidity( + RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), + trading_pair, + market_maker, + UNIT_BALANCE * 6, + UNIT_BALANCE * 40 + ), + crate::pallet::Error::::PublicDepositsNotAllowed + ); + }) } #[test] fn test_add_liquidity_error_price_not_found() { - new_test_ext().execute_with(|| { - register_test_pool(true); - let market_maker = AccountId32::new([2;32]); - let user_who_wants_to_add_liq = AccountId32::new([3;32]); - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - assert_noop!(LiqudityMining::add_liquidity(RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), trading_pair, market_maker, UNIT_BALANCE * 6, UNIT_BALANCE * 40), crate::pallet::Error::::PriceNotAvailable); - }) + new_test_ext().execute_with(|| { + register_test_pool(true); + let market_maker = AccountId32::new([2; 32]); + let user_who_wants_to_add_liq = AccountId32::new([3; 32]); + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + assert_noop!( + LiqudityMining::add_liquidity( + RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), + trading_pair, + market_maker, + UNIT_BALANCE * 6, + UNIT_BALANCE * 40 + ), + crate::pallet::Error::::PriceNotAvailable + ); + }) } #[test] fn test_add_liquidity_error_not_enough_quote_amount() { - new_test_ext().execute_with(|| { - register_test_pool(true); - // Set snapshot flag - //>::put(None); - // Allowlist Token - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), base_asset)); - assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), quote_asset)); - // Put average price in OCEX Pallet - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let mut price = Decimal::from_u128(UNIT_BALANCE * 5).unwrap(); - price.div_assign(Decimal::from(UNIT_BALANCE)); - let tick = Decimal::from_u128(UNIT_BALANCE * 1).unwrap(); - let market_maker = AccountId32::new([2;32]); - let user_who_wants_to_add_liq = AccountId32::new([3;32]); - let mut map = BTreeMap::new(); - map.insert((base_asset, quote_asset), (price, tick)); - >::set(map); - // Cretae Base and Quote Asset; - mint_base_quote_asset_for_user(user_who_wants_to_add_liq.clone()); - assert_noop!(LiqudityMining::add_liquidity(RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), trading_pair, market_maker, UNIT_BALANCE * 6, UNIT_BALANCE * 10), crate::pallet::Error::::NotEnoughQuoteAmount); - }) + new_test_ext().execute_with(|| { + register_test_pool(true); + // Set snapshot flag + //>::put(None); + // Allowlist Token + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), base_asset)); + assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), quote_asset)); + // Put average price in OCEX Pallet + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let mut price = Decimal::from_u128(UNIT_BALANCE * 5).unwrap(); + price.div_assign(Decimal::from(UNIT_BALANCE)); + let tick = Decimal::from_u128(UNIT_BALANCE * 1).unwrap(); + let market_maker = AccountId32::new([2; 32]); + let user_who_wants_to_add_liq = AccountId32::new([3; 32]); + let mut map = BTreeMap::new(); + map.insert((base_asset, quote_asset), (price, tick)); + >::set(map); + // Cretae Base and Quote Asset; + mint_base_quote_asset_for_user(user_who_wants_to_add_liq.clone()); + assert_noop!( + LiqudityMining::add_liquidity( + RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), + trading_pair, + market_maker, + UNIT_BALANCE * 6, + UNIT_BALANCE * 10 + ), + crate::pallet::Error::::NotEnoughQuoteAmount + ); + }) } #[test] fn test_add_liquidity_not_enough_token_to_trasnfer() { - new_test_ext().execute_with(|| { - register_test_pool(true); - // Set snapshot flag - //>::put(None); - // Allowlist Token - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), base_asset)); - assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), quote_asset)); - // Put average price in OCEX Pallet - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let mut price = Decimal::from_u128(UNIT_BALANCE * 5).unwrap(); - price.div_assign(Decimal::from(UNIT_BALANCE)); - let tick = Decimal::from_u128(UNIT_BALANCE * 1).unwrap(); - let market_maker = AccountId32::new([2;32]); - let user_who_wants_to_add_liq = AccountId32::new([3;32]); - let mut map = BTreeMap::new(); - map.insert((base_asset, quote_asset), (price, tick)); - >::set(map); - // Cretae Base and Quote Asset; - mint_base_quote_asset_for_user(user_who_wants_to_add_liq.clone()); - assert_noop!(LiqudityMining::add_liquidity(RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), trading_pair, market_maker, UNIT_BALANCE * 10000, UNIT_BALANCE * 40000000), Underflow); - }) + new_test_ext().execute_with(|| { + register_test_pool(true); + // Set snapshot flag + //>::put(None); + // Allowlist Token + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), base_asset)); + assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), quote_asset)); + // Put average price in OCEX Pallet + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let mut price = Decimal::from_u128(UNIT_BALANCE * 5).unwrap(); + price.div_assign(Decimal::from(UNIT_BALANCE)); + let tick = Decimal::from_u128(UNIT_BALANCE * 1).unwrap(); + let market_maker = AccountId32::new([2; 32]); + let user_who_wants_to_add_liq = AccountId32::new([3; 32]); + let mut map = BTreeMap::new(); + map.insert((base_asset, quote_asset), (price, tick)); + >::set(map); + // Cretae Base and Quote Asset; + mint_base_quote_asset_for_user(user_who_wants_to_add_liq.clone()); + assert_noop!( + LiqudityMining::add_liquidity( + RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), + trading_pair, + market_maker, + UNIT_BALANCE * 10000, + UNIT_BALANCE * 40000000 + ), + Underflow + ); + }) } #[test] fn test_remove_liquidity_happy_path_and_error() { - new_test_ext().execute_with(|| { - add_liquidity(); - let market_maker = AccountId32::new([2;32]); - let user_who_wants_to_add_liq = AccountId32::new([3;32]); - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - assert_ok!(LiqudityMining::remove_liquidity(RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), trading_pair, market_maker.clone(), UNIT_BALANCE * 6)); - let (pool, share_id) = LiqudityMining::create_pool_account(&market_maker, trading_pair); - // * Check shares of user - assert_eq!(Assets::balance(share_id, &user_who_wants_to_add_liq), 0); - assert_noop!(LiqudityMining::remove_liquidity(RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), trading_pair, market_maker.clone(), UNIT_BALANCE * 6), crate::pallet::Error::::TotalShareIssuanceIsZero); - }) + new_test_ext().execute_with(|| { + add_liquidity(); + let market_maker = AccountId32::new([2; 32]); + let user_who_wants_to_add_liq = AccountId32::new([3; 32]); + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + assert_ok!(LiqudityMining::remove_liquidity( + RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), + trading_pair, + market_maker.clone(), + UNIT_BALANCE * 6 + )); + let (pool, share_id) = LiqudityMining::create_pool_account(&market_maker, trading_pair); + // * Check shares of user + assert_eq!(Assets::balance(share_id, &user_who_wants_to_add_liq), 0); + assert_noop!( + LiqudityMining::remove_liquidity( + RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), + trading_pair, + market_maker.clone(), + UNIT_BALANCE * 6 + ), + crate::pallet::Error::::TotalShareIssuanceIsZero + ); + }) } #[test] fn test_force_close_pool_happy_path_and_error() { - new_test_ext().execute_with(|| { - register_test_pool(true); - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let market_maker = AccountId32::new([2;32]); - let base_freed = Decimal::from(2); - let quote_freed = Decimal::from(3); - assert_ok!(LiqudityMining::pool_force_close_success(trading_pair, &market_maker, base_freed, quote_freed)); - assert_ok!(LiqudityMining::force_close_pool(RuntimeOrigin::root(), trading_pair, market_maker.clone())); - let config = >::get(trading_pair, market_maker.clone()).unwrap(); - assert_eq!(config.force_closed, true); - }) + new_test_ext().execute_with(|| { + register_test_pool(true); + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let market_maker = AccountId32::new([2; 32]); + let base_freed = Decimal::from(2); + let quote_freed = Decimal::from(3); + assert_ok!(LiqudityMining::pool_force_close_success( + trading_pair, + &market_maker, + base_freed, + quote_freed + )); + assert_ok!(LiqudityMining::force_close_pool( + RuntimeOrigin::root(), + trading_pair, + market_maker.clone() + )); + let config = >::get(trading_pair, market_maker.clone()).unwrap(); + assert_eq!(config.force_closed, true); + }) } #[test] fn test_add_liquidity_success_happy_path() { - new_test_ext().execute_with(|| { - // Create Pool - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let market_maker = AccountId32::new([2;32]); - let lp = AccountId32::new([3;32]); - let share_issued: Decimal = Decimal::from(100); - let price: Decimal = Decimal::from(5); - let total_inventory_in_quote: Decimal = Decimal::from(40); - register_test_pool(true); - // Start new epoch - LiqudityMining::new_epoch(1); - assert_ok!(LiqudityMining::add_liquidity_success(trading_pair, &market_maker, &lp, share_issued, price, total_inventory_in_quote)); - }) + new_test_ext().execute_with(|| { + // Create Pool + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let market_maker = AccountId32::new([2; 32]); + let lp = AccountId32::new([3; 32]); + let share_issued: Decimal = Decimal::from(100); + let price: Decimal = Decimal::from(5); + let total_inventory_in_quote: Decimal = Decimal::from(40); + register_test_pool(true); + // Start new epoch + LiqudityMining::new_epoch(1); + assert_ok!(LiqudityMining::add_liquidity_success( + trading_pair, + &market_maker, + &lp, + share_issued, + price, + total_inventory_in_quote + )); + }) } #[test] fn test_submit_scores_of_lps_happy_path() { - new_test_ext().execute_with(|| { - let market_maker = AccountId32::new([2;32]); - let mut score_map: BTreeMap = BTreeMap::new(); - score_map.insert(market_maker.clone(), (100 * UNIT_BALANCE, true)); - let total_score = 100 * UNIT_BALANCE; - let mut results: BTreeMap< - (TradingPair, AccountId32, u16), - (BTreeMap, u128)> = BTreeMap::new(); - results.insert((TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, market_maker.clone(), 1), (score_map, total_score)); - register_test_pool(true); - assert_ok!(LiqudityMining::submit_scores_of_lps(RuntimeOrigin::none(), results)); - }) + new_test_ext().execute_with(|| { + let market_maker = AccountId32::new([2; 32]); + let mut score_map: BTreeMap = BTreeMap::new(); + score_map.insert(market_maker.clone(), (100 * UNIT_BALANCE, true)); + let total_score = 100 * UNIT_BALANCE; + let mut results: BTreeMap< + (TradingPair, AccountId32, u16), + (BTreeMap, u128), + > = BTreeMap::new(); + results.insert( + ( + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + market_maker.clone(), + 1, + ), + (score_map, total_score), + ); + register_test_pool(true); + assert_ok!(LiqudityMining::submit_scores_of_lps(RuntimeOrigin::none(), results)); + }) } -use orderbook_primitives::{TradingPairMetricsMap, TradingPairMetrics, TraderMetricsMap}; +use orderbook_primitives::{TraderMetricsMap, TradingPairMetrics, TradingPairMetricsMap}; use sp_runtime::traits::AccountIdConversion; #[test] fn test_claim_rewards_by_lp_happy_path_and_error() { - new_test_ext().execute_with(|| { - register_test_pool(true); - add_lmp_config(); - update_lmp_score(); - let reward_account = ::LMPRewardsPalletId::get().into_account_truncating(); - Balances::mint_into(&reward_account, 300 * UNIT_BALANCE); - let market_maker = AccountId32::new([2;32]); - let trader = AccountId32::new([1;32]); - let mut score_map: BTreeMap = BTreeMap::new(); - score_map.insert(trader.clone(), (100 * UNIT_BALANCE, false)); - let total_score = 100 * UNIT_BALANCE; - let mut results: BTreeMap< - (TradingPair, AccountId32, u16), - (BTreeMap, u128)> = BTreeMap::new(); - results.insert((TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, market_maker.clone(), 1), (score_map, total_score)); - assert_ok!(LiqudityMining::submit_scores_of_lps(RuntimeOrigin::none(), results)); - assert_ok!(LiqudityMining::claim_rewards_by_lp(RuntimeOrigin::signed(trader.clone()), TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, market_maker.clone(), 1 )); - assert_noop!(LiqudityMining::claim_rewards_by_lp(RuntimeOrigin::signed(trader.clone()), TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, market_maker.clone(), 1 ), crate::pallet::Error::::AlreadyClaimed); - }) + new_test_ext().execute_with(|| { + register_test_pool(true); + add_lmp_config(); + update_lmp_score(); + let reward_account = + ::LMPRewardsPalletId::get() + .into_account_truncating(); + Balances::mint_into(&reward_account, 300 * UNIT_BALANCE); + let market_maker = AccountId32::new([2; 32]); + let trader = AccountId32::new([1; 32]); + let mut score_map: BTreeMap = BTreeMap::new(); + score_map.insert(trader.clone(), (100 * UNIT_BALANCE, false)); + let total_score = 100 * UNIT_BALANCE; + let mut results: BTreeMap< + (TradingPair, AccountId32, u16), + (BTreeMap, u128), + > = BTreeMap::new(); + results.insert( + ( + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + market_maker.clone(), + 1, + ), + (score_map, total_score), + ); + assert_ok!(LiqudityMining::submit_scores_of_lps(RuntimeOrigin::none(), results)); + assert_ok!(LiqudityMining::claim_rewards_by_lp( + RuntimeOrigin::signed(trader.clone()), + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + market_maker.clone(), + 1 + )); + assert_noop!( + LiqudityMining::claim_rewards_by_lp( + RuntimeOrigin::signed(trader.clone()), + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + market_maker.clone(), + 1 + ), + crate::pallet::Error::::AlreadyClaimed + ); + }) } #[test] fn test_claim_rewards_by_mm_happy_path_and_error() { - new_test_ext().execute_with(|| { - register_test_pool(true); - add_lmp_config(); - update_lmp_score(); - let reward_account = ::LMPRewardsPalletId::get().into_account_truncating(); - Balances::mint_into(&reward_account, 300 * UNIT_BALANCE); - let market_maker = AccountId32::new([2;32]); - let trader = AccountId32::new([1;32]); - let mut score_map: BTreeMap = BTreeMap::new(); - score_map.insert(trader.clone(), (100 * UNIT_BALANCE, false)); - let total_score = 100 * UNIT_BALANCE; - let mut results: BTreeMap< - (TradingPair, AccountId32, u16), - (BTreeMap, u128)> = BTreeMap::new(); - results.insert((TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, market_maker.clone(), 1), (score_map, total_score)); - assert_ok!(LiqudityMining::submit_scores_of_lps(RuntimeOrigin::none(), results)); - assert_ok!(LiqudityMining::claim_rewards_by_mm(RuntimeOrigin::signed(market_maker.clone()), TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, 1 )); - assert_noop!(LiqudityMining::claim_rewards_by_mm(RuntimeOrigin::signed(market_maker.clone()), TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, 1 ), crate::pallet::Error::::AlreadyClaimed); - }) + new_test_ext().execute_with(|| { + register_test_pool(true); + add_lmp_config(); + update_lmp_score(); + let reward_account = + ::LMPRewardsPalletId::get() + .into_account_truncating(); + Balances::mint_into(&reward_account, 300 * UNIT_BALANCE); + let market_maker = AccountId32::new([2; 32]); + let trader = AccountId32::new([1; 32]); + let mut score_map: BTreeMap = BTreeMap::new(); + score_map.insert(trader.clone(), (100 * UNIT_BALANCE, false)); + let total_score = 100 * UNIT_BALANCE; + let mut results: BTreeMap< + (TradingPair, AccountId32, u16), + (BTreeMap, u128), + > = BTreeMap::new(); + results.insert( + ( + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + market_maker.clone(), + 1, + ), + (score_map, total_score), + ); + assert_ok!(LiqudityMining::submit_scores_of_lps(RuntimeOrigin::none(), results)); + assert_ok!(LiqudityMining::claim_rewards_by_mm( + RuntimeOrigin::signed(market_maker.clone()), + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + 1 + )); + assert_noop!( + LiqudityMining::claim_rewards_by_mm( + RuntimeOrigin::signed(market_maker.clone()), + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + 1 + ), + crate::pallet::Error::::AlreadyClaimed + ); + }) } use crate::pallet::WithdrawalRequests; #[test] fn test_initiate_withdrawal() { - new_test_ext().execute_with(|| { - // Register pool - register_test_pool(true); - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let epoch = 1; - let num_of_request = 1; - let market_maker = AccountId32::new([2;32]); - let (pool, share_id) = LiqudityMining::create_pool_account(&market_maker, trading_pair); - let trader = AccountId32::new([1;32]); - let asset1 = 10 * UNIT_BALANCE; - let asset2 = 10 * UNIT_BALANCE; - let mut value = Vec::new(); - value.push((trader, asset1, asset2)); - >::insert(epoch, pool, value); - // Remove liquidity - assert_ok!(LiqudityMining::initiate_withdrawal(RuntimeOrigin::signed(market_maker), trading_pair, epoch, num_of_request)); - }) + new_test_ext().execute_with(|| { + // Register pool + register_test_pool(true); + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let epoch = 1; + let num_of_request = 1; + let market_maker = AccountId32::new([2; 32]); + let (pool, share_id) = LiqudityMining::create_pool_account(&market_maker, trading_pair); + let trader = AccountId32::new([1; 32]); + let asset1 = 10 * UNIT_BALANCE; + let asset2 = 10 * UNIT_BALANCE; + let mut value = Vec::new(); + value.push((trader, asset1, asset2)); + >::insert(epoch, pool, value); + // Remove liquidity + assert_ok!(LiqudityMining::initiate_withdrawal( + RuntimeOrigin::signed(market_maker), + trading_pair, + epoch, + num_of_request + )); + }) } -#[test] -fn test_ - pub fn update_lmp_score() { - let total_score = Decimal::from(1000); - let total_fee_paid = Decimal::from(1000); - let trading_pair_metrics:TradingPairMetrics = (total_score, total_fee_paid); - let trader = AccountId32::new([1;32]); - let trader_score = Decimal::from(100); - let trader_fee_paid = Decimal::from(100); - let mut trader_metrics: TraderMetricsMap = BTreeMap::new(); - trader_metrics.insert(trader.clone(), (trader_score, trader_fee_paid)); - let mut trading_pair_metrics_map: TradingPairMetricsMap = BTreeMap::new(); - trading_pair_metrics_map.insert(TradingPair{ base: AssetId::Polkadex, quote: AssetId::Asset(1) }, (trader_metrics, trading_pair_metrics)); - assert_ok!(OCEX::update_lmp_scores(&trading_pair_metrics_map)); + let total_score = Decimal::from(1000); + let total_fee_paid = Decimal::from(1000); + let trading_pair_metrics: TradingPairMetrics = (total_score, total_fee_paid); + let trader = AccountId32::new([1; 32]); + let trader_score = Decimal::from(100); + let trader_fee_paid = Decimal::from(100); + let mut trader_metrics: TraderMetricsMap = BTreeMap::new(); + trader_metrics.insert(trader.clone(), (trader_score, trader_fee_paid)); + let mut trading_pair_metrics_map: TradingPairMetricsMap = BTreeMap::new(); + trading_pair_metrics_map.insert( + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + (trader_metrics, trading_pair_metrics), + ); + assert_ok!(OCEX::update_lmp_scores(&trading_pair_metrics_map)); } pub fn add_lmp_config() { - let total_liquidity_mining_rewards: Option = Some(1000 * UNIT_BALANCE); - let total_trading_rewards: Option = Some(1000 * UNIT_BALANCE); - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair{ base: base_asset, quote: quote_asset }; - // Register trading pair - let mut market_weightage = BTreeMap::new(); - market_weightage.insert(trading_pair.clone(), UNIT_BALANCE); - let market_weightage: Option> = Some(market_weightage); - let mut min_fees_paid = BTreeMap::new(); - min_fees_paid.insert(trading_pair.clone(), UNIT_BALANCE); - let min_fees_paid: Option> = Some(min_fees_paid); - let mut min_maker_volume = BTreeMap::new(); - min_maker_volume.insert(trading_pair, UNIT_BALANCE); - let min_maker_volume: Option> = Some(min_maker_volume); - let max_accounts_rewarded: Option = Some(10); - let claim_safety_period: Option = Some(0); - assert_ok!(OCEX::set_lmp_epoch_config( - RuntimeOrigin::root(), - total_liquidity_mining_rewards, - total_trading_rewards, - market_weightage, - min_fees_paid, - min_maker_volume, - max_accounts_rewarded, - claim_safety_period - )); - OCEX::start_new_epoch(); - OCEX::start_new_epoch(); + let total_liquidity_mining_rewards: Option = Some(1000 * UNIT_BALANCE); + let total_trading_rewards: Option = Some(1000 * UNIT_BALANCE); + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + // Register trading pair + let mut market_weightage = BTreeMap::new(); + market_weightage.insert(trading_pair.clone(), UNIT_BALANCE); + let market_weightage: Option> = Some(market_weightage); + let mut min_fees_paid = BTreeMap::new(); + min_fees_paid.insert(trading_pair.clone(), UNIT_BALANCE); + let min_fees_paid: Option> = Some(min_fees_paid); + let mut min_maker_volume = BTreeMap::new(); + min_maker_volume.insert(trading_pair, UNIT_BALANCE); + let min_maker_volume: Option> = Some(min_maker_volume); + let max_accounts_rewarded: Option = Some(10); + let claim_safety_period: Option = Some(0); + assert_ok!(OCEX::set_lmp_epoch_config( + RuntimeOrigin::root(), + total_liquidity_mining_rewards, + total_trading_rewards, + market_weightage, + min_fees_paid, + min_maker_volume, + max_accounts_rewarded, + claim_safety_period + )); + OCEX::start_new_epoch(); + OCEX::start_new_epoch(); } use orderbook_primitives::traits::LiquidityMiningCrowdSourcePallet; fn add_liquidity() { - register_test_pool(true); - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), base_asset)); - assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), quote_asset)); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let mut price = Decimal::from_u128(UNIT_BALANCE * 5).unwrap(); - price.div_assign(Decimal::from(UNIT_BALANCE)); - let tick = Decimal::from_u128(UNIT_BALANCE * 1).unwrap(); - let trading_account = AccountId32::new([1;32]); - let market_maker = AccountId32::new([2;32]); - let user_who_wants_to_add_liq = AccountId32::new([3;32]); - let mut map = BTreeMap::new(); - map.insert((base_asset, quote_asset), (price, tick)); - >::set(map); - // Cretae Base and Quote Asset; - mint_base_quote_asset_for_user(user_who_wants_to_add_liq.clone()); - assert_ok!(LiqudityMining::add_liquidity(RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), trading_pair, market_maker.clone(), UNIT_BALANCE * 6, UNIT_BALANCE * 40)); - let (pool, share_id) = LiqudityMining::create_pool_account(&market_maker, trading_pair); - let share_issued = Decimal::from(6); - let price = Decimal::from(5); - let total_inventory_in_quote = Decimal::from(40); - assert_ok!(LiqudityMining::add_liquidity_success(trading_pair, &market_maker, &user_who_wants_to_add_liq, share_issued, price, total_inventory_in_quote)); + register_test_pool(true); + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), base_asset)); + assert_ok!(OCEX::allowlist_token(RuntimeOrigin::root(), quote_asset)); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let mut price = Decimal::from_u128(UNIT_BALANCE * 5).unwrap(); + price.div_assign(Decimal::from(UNIT_BALANCE)); + let tick = Decimal::from_u128(UNIT_BALANCE * 1).unwrap(); + let trading_account = AccountId32::new([1; 32]); + let market_maker = AccountId32::new([2; 32]); + let user_who_wants_to_add_liq = AccountId32::new([3; 32]); + let mut map = BTreeMap::new(); + map.insert((base_asset, quote_asset), (price, tick)); + >::set(map); + // Cretae Base and Quote Asset; + mint_base_quote_asset_for_user(user_who_wants_to_add_liq.clone()); + assert_ok!(LiqudityMining::add_liquidity( + RuntimeOrigin::signed(user_who_wants_to_add_liq.clone()), + trading_pair, + market_maker.clone(), + UNIT_BALANCE * 6, + UNIT_BALANCE * 40 + )); + let (pool, share_id) = LiqudityMining::create_pool_account(&market_maker, trading_pair); + let share_issued = Decimal::from(6); + let price = Decimal::from(5); + let total_inventory_in_quote = Decimal::from(40); + assert_ok!(LiqudityMining::add_liquidity_success( + trading_pair, + &market_maker, + &user_who_wants_to_add_liq, + share_issued, + price, + total_inventory_in_quote + )); } fn mint_base_quote_asset_for_user(user: AccountId32) { - let quote_asset = AssetId::Asset(1); - Balances::mint_into(&user, UNIT_BALANCE * 100); - Assets::create(RuntimeOrigin::signed(user.clone()), parity_scale_codec::Compact(quote_asset.asset_id().unwrap()), AccountId32::new([1;32]), One::one()); - assert_ok!(Assets::mint_into(quote_asset.asset_id().unwrap(), &user, UNIT_BALANCE * 100)); + let quote_asset = AssetId::Asset(1); + Balances::mint_into(&user, UNIT_BALANCE * 100); + Assets::create( + RuntimeOrigin::signed(user.clone()), + parity_scale_codec::Compact(quote_asset.asset_id().unwrap()), + AccountId32::new([1; 32]), + One::one(), + ); + assert_ok!(Assets::mint_into(quote_asset.asset_id().unwrap(), &user, UNIT_BALANCE * 100)); } fn crete_base_and_quote_asset() { - let quote_asset = AssetId::Asset(1); - Balances::mint_into(&AccountId32::new([1;32]), UNIT_BALANCE); - assert_ok!(Assets::create(RuntimeOrigin::signed(AccountId32::new([1;32])), parity_scale_codec::Compact(quote_asset.asset_id().unwrap()), AccountId32::new([1;32]), One::one())); + let quote_asset = AssetId::Asset(1); + Balances::mint_into(&AccountId32::new([1; 32]), UNIT_BALANCE); + assert_ok!(Assets::create( + RuntimeOrigin::signed(AccountId32::new([1; 32])), + parity_scale_codec::Compact(quote_asset.asset_id().unwrap()), + AccountId32::new([1; 32]), + One::one() + )); } fn register_test_pool(public_fund_allowed: bool) { - let name = [1;10]; - let base_asset = AssetId::Polkadex; - let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; - let commission = UNIT_BALANCE * 1; - let exit_fee = UNIT_BALANCE * 1; - let trading_account = AccountId32::new([1;32]); - let market_maker = AccountId32::new([2;32]); - register_test_trading_pair(); - mint_base_quote_asset_for_user(market_maker.clone()); - assert_ok!(LiqudityMining::register_pool(RuntimeOrigin::signed(market_maker.clone()), name, trading_pair, commission, exit_fee, public_fund_allowed, trading_account.clone())); + let name = [1; 10]; + let base_asset = AssetId::Polkadex; + let quote_asset = AssetId::Asset(1); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let commission = UNIT_BALANCE * 1; + let exit_fee = UNIT_BALANCE * 1; + let trading_account = AccountId32::new([1; 32]); + let market_maker = AccountId32::new([2; 32]); + register_test_trading_pair(); + mint_base_quote_asset_for_user(market_maker.clone()); + assert_ok!(LiqudityMining::register_pool( + RuntimeOrigin::signed(market_maker.clone()), + name, + trading_pair, + commission, + exit_fee, + public_fund_allowed, + trading_account.clone() + )); } fn register_test_trading_pair() { - let base = AssetId::Polkadex; - let quote = AssetId::Asset(1); - let min_order_price: u128 = UNIT_BALANCE * 2; - let max_order_price: u128 = UNIT_BALANCE * 10; - let min_order_qty: u128 = UNIT_BALANCE * 2; - let max_order_qty: u128 = UNIT_BALANCE * 10; - let price_tick_size: u128 = UNIT_BALANCE; - let qty_step_size: u128 = UNIT_BALANCE; - assert_ok!(OCEX::set_exchange_state(RuntimeOrigin::root(), true)); - assert_ok!(OCEX::register_trading_pair(RuntimeOrigin::root(), base, quote, min_order_price, max_order_price, min_order_qty, max_order_qty, price_tick_size, qty_step_size)); + let base = AssetId::Polkadex; + let quote = AssetId::Asset(1); + let min_order_price: u128 = UNIT_BALANCE * 2; + let max_order_price: u128 = UNIT_BALANCE * 10; + let min_order_qty: u128 = UNIT_BALANCE * 2; + let max_order_qty: u128 = UNIT_BALANCE * 10; + let price_tick_size: u128 = UNIT_BALANCE; + let qty_step_size: u128 = UNIT_BALANCE; + assert_ok!(OCEX::set_exchange_state(RuntimeOrigin::root(), true)); + assert_ok!(OCEX::register_trading_pair( + RuntimeOrigin::root(), + base, + quote, + min_order_price, + max_order_price, + min_order_qty, + max_order_qty, + price_tick_size, + qty_step_size + )); } diff --git a/pallets/liquidity-mining/src/types.rs b/pallets/liquidity-mining/src/types.rs index 878b9fb77..f2482f4e8 100644 --- a/pallets/liquidity-mining/src/types.rs +++ b/pallets/liquidity-mining/src/types.rs @@ -1,5 +1,4 @@ use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use polkadex_primitives::AssetId; use rust_decimal::Decimal; use scale_info::TypeInfo; diff --git a/pallets/ocex/rpc/runtime-api/src/lib.rs b/pallets/ocex/rpc/runtime-api/src/lib.rs index 790549c91..610d4b465 100644 --- a/pallets/ocex/rpc/runtime-api/src/lib.rs +++ b/pallets/ocex/rpc/runtime-api/src/lib.rs @@ -34,8 +34,8 @@ sp_api::decl_runtime_apis! { // Returns the asset inventory deviation in the offchain State fn calculate_inventory_deviation() -> Result, sp_runtime::DispatchError>; // Retrieve a sorted vector of accounts for a given epoch and market based on descending order of scores - fn top_lmp_accounts(epoch: u32, market: TradingPair, sorted_by_mm_score: bool, limit: u16) -> Vec; + fn top_lmp_accounts(epoch: u16, market: TradingPair, sorted_by_mm_score: bool, limit: u16) -> Vec; // Returns the eligible rewards for given main, epoch and market - fn calculate_lmp_rewards(main: AccountId, epoch: u32, market: TradingPair) -> (Decimal, Decimal, bool); + fn calculate_lmp_rewards(main: AccountId, epoch: u16, market: TradingPair) -> (Decimal, Decimal, bool); } } diff --git a/pallets/ocex/src/lib.rs b/pallets/ocex/src/lib.rs index 0da2978f7..fadcb86c5 100644 --- a/pallets/ocex/src/lib.rs +++ b/pallets/ocex/src/lib.rs @@ -151,7 +151,10 @@ pub mod pallet { transactional, PalletId, }; use frame_system::{offchain::SendTransactionTypes, pallet_prelude::*}; - use orderbook_primitives::{constants::FEE_POT_PALLET_ID, lmp::LMPEpochConfig, Fees, ObCheckpointRaw, SnapshotSummary, TradingPairMetricsMap}; + use orderbook_primitives::{ + constants::FEE_POT_PALLET_ID, lmp::LMPEpochConfig, Fees, ObCheckpointRaw, SnapshotSummary, + TradingPairMetricsMap, + }; use polkadex_primitives::{ assets::AssetId, ingress::EgressMessages, diff --git a/pallets/ocex/src/lmp.rs b/pallets/ocex/src/lmp.rs index c28dd0995..cc470e94b 100644 --- a/pallets/ocex/src/lmp.rs +++ b/pallets/ocex/src/lmp.rs @@ -8,7 +8,6 @@ use orderbook_primitives::{ types::{OrderSide, Trade, TradingPair}, LiquidityMining, }; -use sp_std::vec::Vec; use parity_scale_codec::{Decode, Encode}; use polkadex_primitives::{ocex::TradingPairConfig, AccountId, UNIT_BALANCE}; use rust_decimal::{ @@ -16,7 +15,7 @@ use rust_decimal::{ Decimal, }; use sp_runtime::{traits::BlockNumberProvider, DispatchError, SaturatedConversion}; -use sp_std::collections::btree_map::BTreeMap; +use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; pub fn update_trade_volume_by_main_account( state: &mut OffchainState, diff --git a/pallets/ocex/src/tests.rs b/pallets/ocex/src/tests.rs index 6b77aa0d1..f46f966e9 100644 --- a/pallets/ocex/src/tests.rs +++ b/pallets/ocex/src/tests.rs @@ -27,7 +27,7 @@ use std::str::FromStr; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use crate::mock::*; -use frame_support::testing_prelude::bounded_vec; +use frame_support::{testing_prelude::bounded_vec, BoundedVec}; use frame_system::EventRecord; use parity_scale_codec::Decode; use polkadex_primitives::{ingress::IngressMessages, AccountId, AssetsLimit}; @@ -40,7 +40,6 @@ use sp_core::{ use sp_keystore::{testing::MemoryKeystore, Keystore}; use sp_runtime::{AccountId32, DispatchError::BadOrigin, SaturatedConversion, TokenError}; use sp_std::default::Default; -use frame_support::BoundedVec; pub fn register_offchain_ext(ext: &mut sp_io::TestExternalities) { let (offchain, _offchain_state) = TestOffchainExt::with_offchain_db(ext.offchain_db()); @@ -2319,7 +2318,11 @@ fn test_withdrawal() { }); } -use orderbook_primitives::{recovery::ObRecoveryState, types::{Order, OrderPayload, OrderSide, OrderStatus, OrderType, Trade}, Fees, TradingPairMetrics, TradingPairMetricsMap, TraderMetricsMap}; +use orderbook_primitives::{ + recovery::ObRecoveryState, + types::{Order, OrderPayload, OrderSide, OrderStatus, OrderType, Trade}, + Fees, TraderMetricsMap, TradingPairMetrics, TradingPairMetricsMap, +}; use sp_runtime::traits::{BlockNumberProvider, One}; use orderbook_primitives::types::{UserActionBatch, UserActions}; @@ -2601,7 +2604,7 @@ fn test_set_lmp_epoch_config_happy_path() { let total_trading_rewards: Option = Some(1000 * UNIT_BALANCE); let base_asset = AssetId::Polkadex; let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair{ base: base_asset, quote: quote_asset }; + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; // Register trading pair crete_base_and_quote_asset(); register_trading_pair(); @@ -2636,7 +2639,7 @@ fn test_set_lmp_epoch_config_invalid_market_weightage() { let total_trading_rewards: Option = Some(1000 * UNIT_BALANCE); let base_asset = AssetId::Polkadex; let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair{ base: base_asset, quote: quote_asset }; + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; // Register trading pair crete_base_and_quote_asset(); register_trading_pair(); @@ -2651,16 +2654,19 @@ fn test_set_lmp_epoch_config_invalid_market_weightage() { let min_maker_volume: Option> = Some(min_maker_volume); let max_accounts_rewarded: Option = Some(10); let claim_safety_period: Option = Some(10); - assert_noop!(OCEX::set_lmp_epoch_config( - RuntimeOrigin::root(), - total_liquidity_mining_rewards, - total_trading_rewards, - market_weightage, - min_fees_paid, - min_maker_volume, - max_accounts_rewarded, - claim_safety_period - ), crate::pallet::Error::::InvalidMarketWeightage); + assert_noop!( + OCEX::set_lmp_epoch_config( + RuntimeOrigin::root(), + total_liquidity_mining_rewards, + total_trading_rewards, + market_weightage, + min_fees_paid, + min_maker_volume, + max_accounts_rewarded, + claim_safety_period + ), + crate::pallet::Error::::InvalidMarketWeightage + ); }) } @@ -2671,7 +2677,7 @@ fn test_set_lmp_epoch_config_invalid_invalid_LMPConfig() { let total_trading_rewards: Option = Some(1000 * UNIT_BALANCE); let base_asset = AssetId::Polkadex; let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair{ base: base_asset, quote: quote_asset }; + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; // Register trading pair crete_base_and_quote_asset(); register_trading_pair(); @@ -2680,7 +2686,7 @@ fn test_set_lmp_epoch_config_invalid_invalid_LMPConfig() { let market_weightage: Option> = Some(market_weightage); let mut min_fees_paid = BTreeMap::new(); let diff_quote_asset = AssetId::Asset(2); - let trading_pair = TradingPair{ base: base_asset, quote: diff_quote_asset }; + let trading_pair = TradingPair { base: base_asset, quote: diff_quote_asset }; min_fees_paid.insert(trading_pair.clone(), 10 * UNIT_BALANCE); let min_fees_paid: Option> = Some(min_fees_paid); let mut min_maker_volume = BTreeMap::new(); @@ -2688,16 +2694,19 @@ fn test_set_lmp_epoch_config_invalid_invalid_LMPConfig() { let min_maker_volume: Option> = Some(min_maker_volume); let max_accounts_rewarded: Option = Some(10); let claim_safety_period: Option = Some(10); - assert_noop!(OCEX::set_lmp_epoch_config( - RuntimeOrigin::root(), - total_liquidity_mining_rewards, - total_trading_rewards, - market_weightage, - min_fees_paid, - min_maker_volume, - max_accounts_rewarded, - claim_safety_period - ), crate::pallet::Error::::InvalidLMPConfig); + assert_noop!( + OCEX::set_lmp_epoch_config( + RuntimeOrigin::root(), + total_liquidity_mining_rewards, + total_trading_rewards, + market_weightage, + min_fees_paid, + min_maker_volume, + max_accounts_rewarded, + claim_safety_period + ), + crate::pallet::Error::::InvalidLMPConfig + ); }) } @@ -2707,14 +2716,17 @@ fn test_update_lmp_scores_happy_path() { add_lmp_config(); let total_score = Decimal::from(1000); let total_fee_paid = Decimal::from(1000); - let trading_pair_metrics:TradingPairMetrics = (total_score, total_fee_paid); - let trader = AccountId32::new([1;32]); + let trading_pair_metrics: TradingPairMetrics = (total_score, total_fee_paid); + let trader = AccountId32::new([1; 32]); let trader_score = Decimal::from(100); let trader_fee_paid = Decimal::from(100); let mut trader_metrics: TraderMetricsMap = BTreeMap::new(); trader_metrics.insert(trader.clone(), (trader_score, trader_fee_paid)); let mut trading_pair_metrics_map: TradingPairMetricsMap = BTreeMap::new(); - trading_pair_metrics_map.insert(TradingPair{ base: AssetId::Polkadex, quote: AssetId::Asset(1) }, (trader_metrics, trading_pair_metrics)); + trading_pair_metrics_map.insert( + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + (trader_metrics, trading_pair_metrics), + ); assert_ok!(OCEX::update_lmp_scores(&trading_pair_metrics_map)); }) } @@ -2724,16 +2736,21 @@ fn test_update_lmp_scores_no_lmp_config() { new_test_ext().execute_with(|| { let total_score = Decimal::from(1000); let total_fee_paid = Decimal::from(1000); - let trading_pair_metrics:TradingPairMetrics = (total_score, total_fee_paid); - let trader = AccountId32::new([1;32]); + let trading_pair_metrics: TradingPairMetrics = (total_score, total_fee_paid); + let trader = AccountId32::new([1; 32]); let trader_score = Decimal::from(100); let trader_fee_paid = Decimal::from(100); let mut trader_metrics: TraderMetricsMap = BTreeMap::new(); trader_metrics.insert(trader.clone(), (trader_score, trader_fee_paid)); let mut trading_pair_metrics_map: TradingPairMetricsMap = BTreeMap::new(); - trading_pair_metrics_map.insert(TradingPair{ base: AssetId::Polkadex, quote: AssetId::Asset(1) }, (trader_metrics, trading_pair_metrics)); - assert_noop!(OCEX::update_lmp_scores(&trading_pair_metrics_map), crate::pallet::Error::::LMPConfigNotFound); - + trading_pair_metrics_map.insert( + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + (trader_metrics, trading_pair_metrics), + ); + assert_noop!( + OCEX::update_lmp_scores(&trading_pair_metrics_map), + crate::pallet::Error::::LMPConfigNotFound + ); }) } @@ -2742,12 +2759,13 @@ fn test_do_claim_lmp_rewards_happy_path() { new_test_ext().execute_with(|| { add_lmp_config(); update_lmp_score(); - let main_account = AccountId32::new([1;32]); + let main_account = AccountId32::new([1; 32]); let epoch = 0; let base_asset = AssetId::Polkadex; let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair{ base: base_asset, quote: quote_asset }; - let reward_account = ::LMPRewardsPalletId::get().into_account_truncating(); + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; + let reward_account = + ::LMPRewardsPalletId::get().into_account_truncating(); Balances::mint_into(&reward_account, 300 * UNIT_BALANCE); assert_ok!(OCEX::do_claim_lmp_rewards(main_account.clone(), epoch, trading_pair)); assert_eq!(Balances::free_balance(&main_account), 200999999999900u128); @@ -2757,14 +2775,17 @@ fn test_do_claim_lmp_rewards_happy_path() { pub fn update_lmp_score() { let total_score = Decimal::from(1000); let total_fee_paid = Decimal::from(1000); - let trading_pair_metrics:TradingPairMetrics = (total_score, total_fee_paid); - let trader = AccountId32::new([1;32]); + let trading_pair_metrics: TradingPairMetrics = (total_score, total_fee_paid); + let trader = AccountId32::new([1; 32]); let trader_score = Decimal::from(100); let trader_fee_paid = Decimal::from(100); let mut trader_metrics: TraderMetricsMap = BTreeMap::new(); trader_metrics.insert(trader.clone(), (trader_score, trader_fee_paid)); let mut trading_pair_metrics_map: TradingPairMetricsMap = BTreeMap::new(); - trading_pair_metrics_map.insert(TradingPair{ base: AssetId::Polkadex, quote: AssetId::Asset(1) }, (trader_metrics, trading_pair_metrics)); + trading_pair_metrics_map.insert( + TradingPair { base: AssetId::Polkadex, quote: AssetId::Asset(1) }, + (trader_metrics, trading_pair_metrics), + ); assert_ok!(OCEX::update_lmp_scores(&trading_pair_metrics_map)); } @@ -2773,7 +2794,7 @@ pub fn add_lmp_config() { let total_trading_rewards: Option = Some(1000 * UNIT_BALANCE); let base_asset = AssetId::Polkadex; let quote_asset = AssetId::Asset(1); - let trading_pair = TradingPair{ base: base_asset, quote: quote_asset }; + let trading_pair = TradingPair { base: base_asset, quote: quote_asset }; // Register trading pair crete_base_and_quote_asset(); register_trading_pair(); @@ -2789,25 +2810,29 @@ pub fn add_lmp_config() { let max_accounts_rewarded: Option = Some(10); let claim_safety_period: Option = Some(0); assert_ok!(OCEX::set_lmp_epoch_config( - RuntimeOrigin::root(), - total_liquidity_mining_rewards, - total_trading_rewards, - market_weightage, - min_fees_paid, - min_maker_volume, - max_accounts_rewarded, - claim_safety_period - )); + RuntimeOrigin::root(), + total_liquidity_mining_rewards, + total_trading_rewards, + market_weightage, + min_fees_paid, + min_maker_volume, + max_accounts_rewarded, + claim_safety_period + )); OCEX::start_new_epoch(); } -use frame_support::traits::fungible::Mutate; -use frame_support::traits::fungibles::Create; +use frame_support::traits::{fungible::Mutate, fungibles::Create}; fn crete_base_and_quote_asset() { let quote_asset = AssetId::Asset(1); - Balances::mint_into(&AccountId32::new([1;32]), UNIT_BALANCE); - assert_ok!(Assets::create(RuntimeOrigin::signed(AccountId32::new([1;32])), parity_scale_codec::Compact(quote_asset.asset_id().unwrap()), AccountId32::new([1;32]), One::one())); + Balances::mint_into(&AccountId32::new([1; 32]), UNIT_BALANCE); + assert_ok!(Assets::create( + RuntimeOrigin::signed(AccountId32::new([1; 32])), + parity_scale_codec::Compact(quote_asset.asset_id().unwrap()), + AccountId32::new([1; 32]), + One::one() + )); } fn register_trading_pair() { @@ -2815,16 +2840,16 @@ fn register_trading_pair() { let quote_asset = AssetId::Asset(1); assert_ok!(OCEX::set_exchange_state(RuntimeOrigin::root(), true)); assert_ok!(OCEX::register_trading_pair( - RuntimeOrigin::root(), - base_asset, - quote_asset, - 1_0000_0000_u128.into(), - 1_000_000_000_000_000_u128.into(), - 1_000_000_u128.into(), - 1_000_000_000_000_000_u128.into(), - 1_000_000_u128.into(), - 1_0000_0000_u128.into(), - )); + RuntimeOrigin::root(), + base_asset, + quote_asset, + 1_0000_0000_u128.into(), + 1_000_000_000_000_000_u128.into(), + 1_000_000_u128.into(), + 1_000_000_000_000_000_u128.into(), + 1_000_000_u128.into(), + 1_0000_0000_u128.into(), + )); } //FIXME: This test case is not building. Check if it relevant or not diff --git a/pallets/ocex/src/validator.rs b/pallets/ocex/src/validator.rs index 8ff405d9b..fbe173959 100644 --- a/pallets/ocex/src/validator.rs +++ b/pallets/ocex/src/validator.rs @@ -28,6 +28,7 @@ use crate::{ storage::{store_trie_root, OffchainState}, Config, Pallet, SnapshotNonce, Snapshots, }; +use core::ops::Div; use frame_system::pallet_prelude::BlockNumberFor; use num_traits::pow::Pow; use orderbook_primitives::{ @@ -52,7 +53,6 @@ use sp_runtime::{ offchain::storage::StorageValueRef, traits::AccountIdConversion, SaturatedConversion, }; use sp_std::{borrow::ToOwned, boxed::Box, collections::btree_map::BTreeMap, vec::Vec}; -use core::ops::Div; use trie_db::{TrieError, TrieMut}; /// Key of the storage that stores the status of an offchain worker diff --git a/primitives/orderbook/src/lib.rs b/primitives/orderbook/src/lib.rs index 814d1d594..45d650077 100644 --- a/primitives/orderbook/src/lib.rs +++ b/primitives/orderbook/src/lib.rs @@ -111,8 +111,8 @@ pub type FeePaid = Decimal; pub type TraderMetrics = (Score, FeePaid); pub type TraderMetricsMap = BTreeMap; pub type TradingPairMetrics = (TotalScore, TotalFeePaid); -pub type TradingPairMetricsMap = BTreeMap, TradingPairMetrics)>; - +pub type TradingPairMetricsMap = + BTreeMap, TradingPairMetrics)>; /// Defines the structure of snapshot DTO. #[derive(Clone, Encode, Decode, Debug, TypeInfo, PartialEq, Serialize, Deserialize)] @@ -132,7 +132,7 @@ pub struct SnapshotSummary { /// List of Egress messages pub egress_messages: Vec>, /// Trader Metrics - pub trader_metrics: Option> //TODO: @ksr use types + pub trader_metrics: Option>, //TODO: @ksr use types } impl SnapshotSummary { diff --git a/primitives/orderbook/src/lmp.rs b/primitives/orderbook/src/lmp.rs index b1d694114..44b6be314 100644 --- a/primitives/orderbook/src/lmp.rs +++ b/primitives/orderbook/src/lmp.rs @@ -5,8 +5,7 @@ use rust_decimal::{ Decimal, }; use scale_info::TypeInfo; -use sp_std::collections::btree_map::BTreeMap; -use sp_std::vec::Vec; +use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; /// All metrics used for calculating the LMP score of a main account #[derive(Decode, Encode, TypeInfo, Copy, Clone, Debug, Eq, PartialEq)] diff --git a/primitives/orderbook/src/types.rs b/primitives/orderbook/src/types.rs index aa201dcd5..c28e9bdc5 100644 --- a/primitives/orderbook/src/types.rs +++ b/primitives/orderbook/src/types.rs @@ -23,9 +23,9 @@ use parity_scale_codec::{Codec, Decode, Encode, MaxEncodedLen}; use polkadex_primitives::{ ocex::TradingPairConfig, withdrawal::Withdrawal, AccountId, AssetId, Signature, }; +use rust_decimal::Decimal; #[cfg(feature = "std")] -use rust_decimal::{RoundingStrategy, prelude::Zero}; -use rust_decimal::{Decimal}; +use rust_decimal::{prelude::Zero, RoundingStrategy}; use scale_info::TypeInfo; use sp_core::H256; use sp_runtime::traits::Verify; @@ -52,7 +52,9 @@ pub struct AccountInfo { } /// Defines account to asset map DTO to be used in the "Orderbook" client. -#[derive(Clone, Debug, Encode, Decode, Ord, PartialOrd, PartialEq, Eq, TypeInfo, Serialize, Deserialize)] +#[derive( + Clone, Debug, Encode, Decode, Ord, PartialOrd, PartialEq, Eq, TypeInfo, Serialize, Deserialize, +)] pub struct AccountAsset { /// Main account identifier. pub main: AccountId, @@ -73,7 +75,7 @@ impl AccountAsset { } /// Defines trade related structure DTO. -#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo , Serialize, Deserialize)] +#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo, Serialize, Deserialize)] pub struct Trade { /// Market order. pub maker: Order, @@ -312,7 +314,21 @@ pub struct WithdrawPayloadCallByUser { } /// Defines possible order sides variants. -#[derive(Encode, Decode, Copy, Clone, Hash, Ord, PartialOrd, Debug, Eq, PartialEq, TypeInfo, Serialize, Deserialize)] +#[derive( + Encode, + Decode, + Copy, + Clone, + Hash, + Ord, + PartialOrd, + Debug, + Eq, + PartialEq, + TypeInfo, + Serialize, + Deserialize, +)] pub enum OrderSide { /// Asking order side. Ask, @@ -344,7 +360,9 @@ impl TryFrom for OrderSide { } /// Defines possible order types variants. -#[derive(Encode, Decode, Copy, Clone, Hash, Debug, Eq, PartialEq, TypeInfo, Serialize, Deserialize)] +#[derive( + Encode, Decode, Copy, Clone, Hash, Debug, Eq, PartialEq, TypeInfo, Serialize, Deserialize, +)] pub enum OrderType { /// Order limit type. LIMIT, @@ -366,7 +384,9 @@ impl TryFrom for OrderType { } /// Defines possible order statuses variants. -#[derive(Encode, Decode, Copy, Clone, Hash, Debug, Eq, PartialEq, TypeInfo, Serialize, Deserialize)] +#[derive( + Encode, Decode, Copy, Clone, Hash, Debug, Eq, PartialEq, TypeInfo, Serialize, Deserialize, +)] pub enum OrderStatus { /// Order open. OPEN, @@ -416,7 +436,7 @@ impl From for String { TypeInfo, MaxEncodedLen, Serialize, - Deserialize + Deserialize, )] pub struct TradingPair { /// Base asset identifier. diff --git a/primitives/polkadex/src/assets.rs b/primitives/polkadex/src/assets.rs index 4ae1b2077..deb1332ca 100644 --- a/primitives/polkadex/src/assets.rs +++ b/primitives/polkadex/src/assets.rs @@ -172,14 +172,14 @@ pub enum AssetId { Polkadex, } - impl AssetId { - pub fn asset_id(&self) -> Option { - match self { - AssetId::Asset(id) => Some(*id), - AssetId::Polkadex => None, - } - } - } +impl AssetId { + pub fn asset_id(&self) -> Option { + match self { + AssetId::Asset(id) => Some(*id), + AssetId::Polkadex => None, + } + } +} use sp_runtime::traits::Zero; impl From for AssetId { diff --git a/primitives/polkadex/src/ingress.rs b/primitives/polkadex/src/ingress.rs index 4ef26b74a..76b5662fa 100644 --- a/primitives/polkadex/src/ingress.rs +++ b/primitives/polkadex/src/ingress.rs @@ -28,7 +28,20 @@ use rust_decimal::Decimal; use scale_info::TypeInfo; /// Definition of available ingress messages variants. -#[derive(Clone, Encode, Decode, MaxEncodedLen, TypeInfo, Debug, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] +#[derive( + Clone, + Encode, + Decode, + MaxEncodedLen, + TypeInfo, + Debug, + Eq, + PartialEq, + PartialOrd, + Ord, + Serialize, + Deserialize, +)] pub enum IngressMessages { /// Open Trading Pair. OpenTradingPair(TradingPairConfig), diff --git a/primitives/polkadex/src/ocex.rs b/primitives/polkadex/src/ocex.rs index 581b0bd76..3b1f4ac8b 100644 --- a/primitives/polkadex/src/ocex.rs +++ b/primitives/polkadex/src/ocex.rs @@ -88,8 +88,19 @@ impl> AccountInfo /// Trading pair configuration structure definition. #[derive( - Clone, Encode, Decode, MaxEncodedLen, TypeInfo, Debug, Eq, PartialEq, Copy, Ord, PartialOrd, -Serialize, Deserialize + Clone, + Encode, + Decode, + MaxEncodedLen, + TypeInfo, + Debug, + Eq, + PartialEq, + Copy, + Ord, + PartialOrd, + Serialize, + Deserialize, )] pub struct TradingPairConfig { /// Base asset identifier. diff --git a/runtimes/mainnet/Cargo.toml b/runtimes/mainnet/Cargo.toml index 503d50d1b..1c4de1dd0 100644 --- a/runtimes/mainnet/Cargo.toml +++ b/runtimes/mainnet/Cargo.toml @@ -71,7 +71,6 @@ sp-transaction-pool = { default-features = false, workspace = true } sp-version = { default-features = false, workspace = true } sp-io = { workspace = true, default-features = false } sp-statement-store = { workspace = true, default-features = false } -sp-storage = { workspace = true, default-features = false } #added sp-authority-discovery = { default-features = false, workspace = true } @@ -199,7 +198,6 @@ std = [ "pallet-asset-tx-payment/std", "pallet-statement/std", "sp-statement-store/std", - "sp-storage/std", ] runtime-benchmarks = [ #theirs diff --git a/runtimes/mainnet/src/lib.rs b/runtimes/mainnet/src/lib.rs index 991c4e15c..c9623d403 100644 --- a/runtimes/mainnet/src/lib.rs +++ b/runtimes/mainnet/src/lib.rs @@ -32,9 +32,9 @@ use frame_support::{ pallet_prelude::{ConstU32, RuntimeDebug}, parameter_types, traits::{ - AsEnsureOriginWithArg, Currency, EitherOfDiverse, EnsureOrigin, EqualPrivilegeOnly, - Everything, Get, Imbalance, InstanceFilter, KeyOwnerProofSystem, LockIdentifier, - OnUnbalanced, + fungible::Inspect, AsEnsureOriginWithArg, Currency, EitherOfDiverse, EnsureOrigin, + EqualPrivilegeOnly, Everything, Get, Imbalance, InstanceFilter, KeyOwnerProofSystem, + LockIdentifier, OnUnbalanced, }, weights::{ constants::{ @@ -51,6 +51,7 @@ use frame_system::{ EnsureRoot, EnsureSigned, RawOrigin, }; +use orderbook_primitives::types::TradingPair; #[cfg(any(feature = "std", test))] pub use pallet_balances::Call as BalancesCall; use pallet_grandpa::{ @@ -90,7 +91,6 @@ use sp_std::{prelude::*, vec}; use sp_version::NativeVersion; use sp_version::RuntimeVersion; use static_assertions::const_assert; -use orderbook_primitives::types::TradingPair; /// Implementations of some helper traits passed into runtime modules as associated types. pub mod impls; @@ -842,11 +842,6 @@ type EnsureRootOrHalfCouncil = EitherOfDiverse< pallet_collective::EnsureProportionMoreThan, >; -type EnsureRootOrHalfOrderbookCouncil = EitherOfDiverse< - EnsureRoot, - pallet_collective::EnsureProportionMoreThan, ->; - impl pallet_membership::Config for Runtime { type RuntimeEvent = RuntimeEvent; type AddOrigin = EnsureRootOrHalfCouncil; @@ -1603,9 +1598,7 @@ pub type Executive = frame_executive::Executive< AllPalletsWithSystem, >; -use crate::{ - impls::CreditToBlockAuthor, -}; +use crate::impls::CreditToBlockAuthor; use orderbook_primitives::ObCheckpointRaw; impl_runtime_apis! { impl sp_api::Core for Runtime { @@ -1704,12 +1697,12 @@ impl_runtime_apis! { DispatchError> { OCEX::calculate_inventory_deviation() } - fn top_lmp_accounts(epoch: u32, market: TradingPair, sorted_by_mm_score: bool, limit: u16) -> Vec { + fn top_lmp_accounts(epoch: u16, market: TradingPair, sorted_by_mm_score: bool, limit: u16) -> Vec { OCEX::top_lmp_accounts(epoch, market, sorted_by_mm_score, limit as usize) } - fn calculate_lmp_rewards(main: AccountId, epoch: u32, market: TradingPair) -> (Decimal, Decimal, bool) { - OCEX::get_lmp_rewards(main, epoch, market) + fn calculate_lmp_rewards(main: AccountId, epoch: u16, market: TradingPair) -> (Decimal, Decimal, bool) { + OCEX::get_lmp_rewards(&main, epoch, market) } }