From 04d71d9a50cd46c36d8bfa4a0c6fe1e313a1870c Mon Sep 17 00:00:00 2001 From: dmoka Date: Mon, 25 Nov 2024 13:52:01 +0100 Subject: [PATCH 01/36] add combined add liquidity stableswap omnipool and join farms wrapper extrinsic --- Cargo.lock | 1 + integration-tests/src/dca.rs | 2 +- .../src/omnipool_liquidity_mining.rs | 213 +++++++- integration-tests/src/router.rs | 2 +- pallets/omnipool-liquidity-mining/src/lib.rs | 27 +- ...dity_stableswap_omnipool_and_join_farms.rs | 479 ++++++++++++++++++ .../src/tests/mock.rs | 26 +- .../src/tests/mod.rs | 1 + pallets/stableswap/src/lib.rs | 36 +- pallets/stableswap/src/tests/add_liquidity.rs | 3 +- .../src/tests/calculate_spot_price.rs | 3 +- pallets/stableswap/src/tests/hooks.rs | 3 +- pallets/stableswap/src/tests/invariants.rs | 3 +- pallets/stableswap/src/tests/mock.rs | 3 +- pallets/stableswap/src/tests/price.rs | 3 +- .../stableswap/src/tests/remove_liquidity.rs | 3 +- pallets/stableswap/src/tests/trades.rs | 3 +- pallets/stableswap/src/trade_execution.rs | 2 +- pallets/stableswap/src/types.rs | 22 - runtime-mock/Cargo.toml | 1 + runtime-mock/src/stableswap.rs | 2 +- runtime/hydradx/src/assets.rs | 1 + traits/src/lib.rs | 2 + traits/src/stableswap.rs | 36 ++ 24 files changed, 819 insertions(+), 58 deletions(-) create mode 100644 pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs create mode 100644 traits/src/stableswap.rs diff --git a/Cargo.lock b/Cargo.lock index 78eda0cf1..91ba37521 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12328,6 +12328,7 @@ dependencies = [ "frame-support", "frame-system", "hydradx-runtime", + "hydradx-traits", "orml-tokens", "pallet-asset-registry", "pallet-omnipool", diff --git a/integration-tests/src/dca.rs b/integration-tests/src/dca.rs index 8ed62338b..e079caa04 100644 --- a/integration-tests/src/dca.rs +++ b/integration-tests/src/dca.rs @@ -22,7 +22,7 @@ use orml_traits::MultiCurrency; use orml_traits::MultiReservableCurrency; use pallet_dca::types::{Order, Schedule}; use pallet_omnipool::types::Tradability; -use pallet_stableswap::types::AssetAmount; +use hydradx_traits::stableswap::AssetAmount; use pallet_stableswap::MAX_ASSETS_IN_POOL; use primitives::{AssetId, Balance}; use sp_runtime::traits::ConstU32; diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index d73be77a3..277450935 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -17,25 +17,28 @@ #![cfg(test)] use crate::polkadot_test_net::*; - +use hydradx_traits::Create; use frame_support::assert_ok; use hydradx_traits::liquidity_mining::PriceAdjustment; use warehouse_liquidity_mining::{ DefaultPriceAdjustment, DepositData, GlobalFarmData, GlobalFarmId, Instance1, LoyaltyCurve, YieldFarmData, YieldFarmEntry, }; - +use hydradx_runtime::Omnipool; +use frame_support::storage::with_transaction; +use sp_runtime::TransactionOutcome; +use sp_runtime::DispatchResult; use orml_traits::MultiCurrency; use primitives::{constants::currency::UNITS, AssetId}; -use sp_runtime::{ - traits::{One, Zero}, - FixedPointNumber, FixedU128, Permill, Perquintill, -}; +use sp_runtime::{traits::{One, Zero}, FixedPointNumber, FixedU128, Permill, Perquintill, DispatchError}; use xcm_emulator::TestExt; -use hydradx_runtime::{AssetRegistry, Balance, Bonds, RuntimeEvent, RuntimeOrigin, Treasury, TreasuryAccount}; +use hydradx_runtime::{AssetRegistry, Balance, Bonds, Currencies, Runtime, RuntimeEvent, RuntimeOrigin, Stableswap, Treasury, TreasuryAccount}; use pallet_asset_registry::AssetType; use pretty_assertions::assert_eq; +use hydradx_traits::AssetKind; +use hydradx_traits::stableswap::AssetAmount; +use pallet_stableswap::MAX_ASSETS_IN_POOL; use primitives::constants::time::unix_time::MONTH; #[macro_export] @@ -514,6 +517,150 @@ fn add_liquidity_and_join_farms_should_work_for_multiple_farms() { }); } +#[test] +fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_for_multiple_farms() { + TestNet::reset(); + + Hydra::execute_with(|| { + let _ = with_transaction(|| { + let global_farm_1_id = 1; + let global_farm_2_id = 2; + let global_farm_3_id = 3; + let yield_farm_1_id = 4; + let yield_farm_2_id = 5; + let yield_farm_3_id = 6; + + //Arrange + let (stable_pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + + init_omnipool(); + seed_lm_pot(); + + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + stable_pool_id, + 30_000_000 * UNITS as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + stable_pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); + + //NOTE: necessary to get oracle price. + hydradx_run_to_block(100); + set_relaychain_block_number(100); + create_global_farm(None, None); + create_global_farm(None, None); + create_global_farm(None, None); + + set_relaychain_block_number(200); + create_yield_farm(global_farm_1_id, stable_pool_id); + create_yield_farm(global_farm_2_id, stable_pool_id); + create_yield_farm(global_farm_3_id, stable_pool_id); + + set_relaychain_block_number(300); + + assert_ok!(hydradx_runtime::Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + CHARLIE.into(), + ETH, + 10_000 * UNITS as i128, + )); + + //Add some liquidiity to make sure that it does not interfere with the new liquidty add + assert_ok!(hydradx_runtime::Omnipool::add_liquidity( + RuntimeOrigin::signed(CHARLIE.into()), + ETH, + 100 * UNITS, + )); + + let position_id = hydradx_runtime::Omnipool::next_position_id(); + + set_relaychain_block_number(400); + let deposit_id = 1; + let farms = vec![ + (global_farm_1_id, yield_farm_1_id), + (global_farm_2_id, yield_farm_2_id), + (global_farm_3_id, yield_farm_3_id), + ]; + + //Act + assert_ok!(hydradx_runtime::Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_1, + 100 * UNITS as i128, + )); + assert_ok!(hydradx_runtime::Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_2, + 100 * UNITS as i128, + )); + assert_ok!(hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_stableswap_omnipool_and_join_farms( + RuntimeOrigin::signed(CHARLIE.into()), + stable_pool_id, + vec![AssetAmount::new(stable_asset_1, 10 * UNITS), AssetAmount::new(stable_asset_2, 10 * UNITS)].try_into().unwrap(), + farms.try_into().unwrap() + )); + + //Assert that the ownership of the nft should be transferred to omnipool account + let lm_account = hydradx_runtime::OmnipoolLiquidityMining::account_id(); + assert_nft_owner!(hydradx_runtime::OmnipoolCollectionId::get(), position_id, lm_account); + + set_relaychain_block_number(500); + + let deposit = hydradx_runtime::OmnipoolWarehouseLM::deposit(deposit_id).unwrap(); + let mut expected_deposit = DepositData::new(20044549999405, stable_pool_id); + //1-th deposit entry + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + global_farm_1_id, + yield_farm_1_id, + 10022274999702, + FixedU128::zero(), + 40, + 0, + )) + .unwrap(); + + //2-nd redeposit entry + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + global_farm_2_id, + yield_farm_2_id, + 10022274999702, //NOTE: nothing changed in omnipool so shares are + //valued same as before + FixedU128::zero(), + 40, + 0, + )) + .unwrap(); + + //3-nd redeposit entry + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + global_farm_3_id, + yield_farm_3_id, + 10022274999702, //NOTE: nothing changed in omnipool so shares are + //valued same as before + FixedU128::zero(), + 40, + 0, + )) + .unwrap(); + + assert_eq!(deposit, expected_deposit); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} + #[test] fn withdraw_shares_should_work_when_deposit_exists() { TestNet::reset(); @@ -1430,3 +1577,55 @@ pub fn expect_reward_claimed_events(e: Vec) { pretty_assertions::assert_eq!(reward_claimed_events, e); } + +//TODO: duplicated, remove duplication +pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { + let initial_liquidity = 1_000_000_000_000_000_000_000u128; + + let mut initial: Vec::AssetId>> = vec![]; + let mut asset_ids: Vec<::AssetId> = Vec::new(); + for idx in 0u32..MAX_ASSETS_IN_POOL { + let name: Vec = idx.to_ne_bytes().to_vec(); + let asset_id = AssetRegistry::register_sufficient_asset( + None, + Some(name.try_into().unwrap()), + AssetKind::Token, + 1u128, + Some(b"xDUM".to_vec().try_into().unwrap()), + Some(18u8), + None, + None, + )?; + + asset_ids.push(asset_id); + Currencies::update_balance( + RuntimeOrigin::root(), + AccountId::from(BOB), + asset_id, + initial_liquidity as i128, + )?; + initial.push(AssetAmount::new(asset_id, initial_liquidity)); + } + let pool_id = AssetRegistry::register_sufficient_asset( + None, + Some(b"pool".to_vec().try_into().unwrap()), + AssetKind::Token, + 1u128, + None, + None, + None, + None, + )?; + + let amplification = 100u16; + let fee = Permill::from_percent(1); + + let asset_in: AssetId = *asset_ids.last().unwrap(); + let asset_out: AssetId = *asset_ids.first().unwrap(); + + Stableswap::create_pool(RuntimeOrigin::root(), pool_id, asset_ids, amplification, fee)?; + + Stableswap::add_liquidity(RuntimeOrigin::signed(BOB.into()), pool_id, initial)?; + + Ok((pool_id, asset_in, asset_out)) +} diff --git a/integration-tests/src/router.rs b/integration-tests/src/router.rs index e68797d06..fa0b4b171 100644 --- a/integration-tests/src/router.rs +++ b/integration-tests/src/router.rs @@ -29,7 +29,7 @@ use frame_support::{assert_noop, assert_ok}; use xcm_emulator::TestExt; use frame_support::storage::with_transaction; -use pallet_stableswap::types::AssetAmount; +use hydradx_traits::stableswap::AssetAmount; use pallet_stableswap::MAX_ASSETS_IN_POOL; use sp_runtime::{ traits::{ConstU32, Zero}, diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index 2cb97cab0..2938bb931 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -72,9 +72,10 @@ use primitive_types::U256; use primitives::{Balance, ItemId as DepositId}; use sp_runtime::{ArithmeticError, FixedU128, Perquintill}; use sp_std::vec; - +use hydradx_traits::stableswap::StableswapAddLiquidity; pub use pallet::*; pub use weights::WeightInfo; +use hydradx_traits::stableswap::AssetAmount; type OmnipoolPallet = pallet_omnipool::Pallet; type PeriodOf = BlockNumberFor; @@ -145,6 +146,8 @@ pub mod pallet { Period = PeriodOf, >; + type Stableswap: StableswapAddLiquidity; + /// Identifier of oracle data soruce #[pallet::constant] type OracleSource: Get; @@ -996,6 +999,28 @@ pub mod pallet { Ok(()) } + + /// TODO: ADD DOC + #[pallet::call_index(16)] + #[pallet::weight(::WeightInfo::exit_farms(farm_entries.len() as u32))]//TODO: rebenchmark + pub fn add_liquidity_stableswap_omnipool_and_join_farms( + origin: OriginFor, + stable_pool_id: T::AssetId, + stable_asset_amounts: BoundedVec, T::MaxFarmEntriesPerDeposit>, + farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, + ) -> DispatchResult { + let who = ensure_signed(origin.clone())?; + ensure!(!farm_entries.is_empty(), Error::::NoFarmEntriesSpecified); + + let stablepool_shares = T::Stableswap::add_liquidity(who, stable_pool_id, stable_asset_amounts.to_vec())?; + + let position_id = + OmnipoolPallet::::do_add_liquidity_with_limit(origin.clone(), stable_pool_id, stablepool_shares, Balance::MIN)?; + + Self::join_farms(origin, farm_entries, position_id)?; + + Ok(()) + } } } diff --git a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs new file mode 100644 index 000000000..e28cdb165 --- /dev/null +++ b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs @@ -0,0 +1,479 @@ +// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::*; + +use pallet_liquidity_mining::{DepositData, YieldFarmEntry}; +use pallet_omnipool::types::AssetReserveState; +use pallet_omnipool::types::Tradability; +use pretty_assertions::assert_eq; + +#[test] +fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_with_single_yield_farm() { + let token_amount = 2000 * ONE; + ExtBuilder::default() + .with_endowed_accounts(vec![ + (Omnipool::protocol_account(), DAI, 1000 * ONE), + (Omnipool::protocol_account(), HDX, NATIVE_AMOUNT), + (LP1, STABLESWAP_POOL_ID, 500000 * ONE), + (LP1, KSM, 5000 * ONE), + (LP2, DOT, 2000 * ONE), + (GC, HDX, 100_000_000 * ONE), + (CHARLIE, HDX, 100_000_000 * ONE), + (BOB, HDX, 100_000_000 * ONE), + (ALICE, KSM, 10_000 * ONE), + (BOB, DOT, 10_000 * ONE), + ]) + .with_registered_asset(KSM) + .with_registered_asset(DOT) + .with_registered_asset(STABLESWAP_POOL_ID) + .with_initial_pool(FixedU128::from_float(0.5), FixedU128::from(1)) + .with_token(KSM, FixedU128::from_float(0.65), LP1, token_amount) + .with_token(STABLESWAP_POOL_ID, FixedU128::from_float(0.65), LP1, token_amount) + .with_global_farm( + //id: 1 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + GC, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + CHARLIE, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 3 + 60_000_000 * ONE, + 2_428_000, + 1, + HDX, + BOB, + Perquintill::from_float(0.000_000_14_f64), + 1_000, + FixedU128::one(), + ) + .with_yield_farm(GC, 1, STABLESWAP_POOL_ID, FixedU128::one(), None) //id: 4 + .build() + .execute_with(|| { + let gc_g_farm_id = 1; + let gc_y_farm_id = 4; + let omnipool_position_id = 4; + let deposit_id = 1; + let asset_in_position = STABLESWAP_POOL_ID; + let amount = 20 * ONE; + let yield_farms = vec![(gc_g_farm_id, gc_y_farm_id)]; + + assert_ok!(OmnipoolMining::add_liquidity_stableswap_omnipool_and_join_farms( + RuntimeOrigin::signed(LP1), + STABLESWAP_POOL_ID, + vec![AssetAmount::new(USDT, amount)].try_into().unwrap(), + yield_farms.try_into().unwrap(), + )); + + //Assert that liquidity is added + assert_asset_state!( + asset_in_position, + AssetReserveState { + reserve: token_amount + SHARES_FROM_STABLESWAP, + hub_reserve: 1303250000000000, + shares: token_amount + SHARES_FROM_STABLESWAP, + protocol_shares: 0, + cap: DEFAULT_WEIGHT_CAP, + tradable: Tradability::default(), + } + ); + + //Assert join farms functionality + expect_events(vec![crate::Event::SharesDeposited { + global_farm_id: gc_g_farm_id, + yield_farm_id: gc_y_farm_id, + deposit_id, + asset_id: STABLESWAP_POOL_ID, + who: LP1, + shares_amount: SHARES_FROM_STABLESWAP, + position_id: omnipool_position_id, + } + .into()]); + + assert_eq!( + crate::OmniPositionId::::get(deposit_id).unwrap(), + omnipool_position_id + ); + + let deposit = + pallet_liquidity_mining::Deposit::::get(deposit_id).unwrap(); + let mut expected_deposit = DepositData::new(SHARES_FROM_STABLESWAP, STABLESWAP_POOL_ID); + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + gc_g_farm_id, + gc_y_farm_id, + 3250000000000, + FixedU128::zero(), + 1, + 0, + )) + .unwrap(); + + assert_eq!(deposit, expected_deposit); + + //NFT check: lm account should be owner of the omnipool position. + let lm_account = OmnipoolMining::account_id(); + let owner: AccountId = DummyNFT::owner(&OMNIPOOL_COLLECTION_ID, &omnipool_position_id).unwrap(); + assert_eq!(owner, lm_account); + + //NFT check: lm deposit should be minted for user. + let owner: AccountId = DummyNFT::owner(&LM_COLLECTION_ID, &deposit_id).unwrap(); + assert_eq!(owner, LP1); + }); +} + +#[test] +fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_with_multiple_yield_farm() { + let token_amount = 2000 * ONE; + + ExtBuilder::default() + .with_endowed_accounts(vec![ + (Omnipool::protocol_account(), DAI, 1000 * ONE), + (Omnipool::protocol_account(), HDX, NATIVE_AMOUNT), + (LP1, STABLESWAP_POOL_ID, 500000 * ONE), + (LP1, KSM, 5000 * ONE), + (LP2, DOT, 2000 * ONE), + (GC, HDX, 100_000_000 * ONE), + (CHARLIE, HDX, 100_000_000 * ONE), + (BOB, HDX, 100_000_000 * ONE), + (ALICE, KSM, 10_000 * ONE), + (BOB, DOT, 10_000 * ONE), + ]) + .with_registered_asset(KSM) + .with_registered_asset(DOT) + .with_registered_asset(STABLESWAP_POOL_ID) + .with_initial_pool(FixedU128::from_float(0.5), FixedU128::from(1)) + .with_token(KSM, FixedU128::from_float(0.65), LP1, token_amount) + .with_token(STABLESWAP_POOL_ID, FixedU128::from_float(0.65), LP1, token_amount) + .with_global_farm( + //id: 1 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + GC, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + CHARLIE, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 3 + 60_000_000 * ONE, + 2_428_000, + 1, + HDX, + BOB, + Perquintill::from_float(0.000_000_14_f64), + 1_000, + FixedU128::one(), + ) + .with_yield_farm(GC, 1, STABLESWAP_POOL_ID, FixedU128::one(), None) //id: 4 + .with_yield_farm(CHARLIE, 2, STABLESWAP_POOL_ID, FixedU128::one(), None) //id: 5 + .with_yield_farm(BOB, 3, STABLESWAP_POOL_ID, FixedU128::one(), None) //id: 6 + .build() + .execute_with(|| { + let gc_g_farm_id = 1; + let gc_y_farm_id = 4; + let charlie_g_farm_id = 2; + let charlie_y_farm_id = 5; + let bob_g_farm_id = 3; + let bob_y_farm_id = 6; + let omnipool_position_id = 4; + let deposit_id = 1; + let amount = 10 * ONE; + let yield_farms = vec![ + (gc_g_farm_id, gc_y_farm_id), + (charlie_g_farm_id, charlie_y_farm_id), + (bob_g_farm_id, bob_y_farm_id), + ]; + + assert_ok!(OmnipoolMining::add_liquidity_stableswap_omnipool_and_join_farms( + RuntimeOrigin::signed(LP1), + STABLESWAP_POOL_ID, + vec![AssetAmount::new(USDT, amount)].try_into().unwrap(), + yield_farms.try_into().unwrap(), + )); + + //Assert that liquidity is added + assert_asset_state!( + STABLESWAP_POOL_ID, + AssetReserveState { + reserve: token_amount + SHARES_FROM_STABLESWAP, + hub_reserve: 1303250000000000, + shares: token_amount + SHARES_FROM_STABLESWAP, + protocol_shares: 0, + cap: DEFAULT_WEIGHT_CAP, + tradable: Tradability::default(), + } + ); + + //Assert + expect_events(vec![ + crate::Event::SharesDeposited { + global_farm_id: gc_g_farm_id, + yield_farm_id: gc_y_farm_id, + deposit_id, + asset_id: STABLESWAP_POOL_ID, + who: LP1, + shares_amount: SHARES_FROM_STABLESWAP, + position_id: omnipool_position_id, + } + .into(), + crate::Event::SharesRedeposited { + global_farm_id: charlie_g_farm_id, + yield_farm_id: charlie_y_farm_id, + deposit_id, + asset_id: STABLESWAP_POOL_ID, + who: LP1, + shares_amount: SHARES_FROM_STABLESWAP, + position_id: omnipool_position_id, + } + .into(), + crate::Event::SharesRedeposited { + global_farm_id: bob_g_farm_id, + yield_farm_id: bob_y_farm_id, + deposit_id, + asset_id: STABLESWAP_POOL_ID, + who: LP1, + shares_amount: SHARES_FROM_STABLESWAP, + position_id: omnipool_position_id, + } + .into(), + ]); + + assert_eq!( + crate::OmniPositionId::::get(deposit_id).unwrap(), + omnipool_position_id + ); + + let deposit = + pallet_liquidity_mining::Deposit::::get(deposit_id).unwrap(); + let mut expected_deposit = DepositData::new(SHARES_FROM_STABLESWAP, STABLESWAP_POOL_ID); + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + gc_g_farm_id, + gc_y_farm_id, + 3250000000000, + FixedU128::zero(), + 1, + 0, + )) + .unwrap(); + + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + charlie_g_farm_id, + charlie_y_farm_id, + 3250000000000, + FixedU128::zero(), + 1, + 0, + )) + .unwrap(); + + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + bob_g_farm_id, + bob_y_farm_id, + 3250000000000, + FixedU128::zero(), + 1, + 0, + )) + .unwrap(); + + assert_eq!(deposit, expected_deposit); + + //NFT check: lm account should be owner of the omnipool position. + let lm_account = OmnipoolMining::account_id(); + let owner: AccountId = DummyNFT::owner(&OMNIPOOL_COLLECTION_ID, &omnipool_position_id).unwrap(); + assert_eq!(owner, lm_account); + + //NFT check: lm deposit should be minted for user. + let owner: AccountId = DummyNFT::owner(&LM_COLLECTION_ID, &deposit_id).unwrap(); + assert_eq!(owner, LP1); + }); +} + +#[test] +fn add_liquidity_stableswap_omnipool_and_join_farms_should_fail_when_origin_is_none() { + let token_amount = 2000 * ONE; + ExtBuilder::default() + .with_endowed_accounts(vec![ + (Omnipool::protocol_account(), DAI, 1000 * ONE), + (Omnipool::protocol_account(), HDX, NATIVE_AMOUNT), + (LP1, STABLESWAP_POOL_ID, 500000 * ONE), + (LP1, KSM, 5000 * ONE), + (LP2, DOT, 2000 * ONE), + (GC, HDX, 100_000_000 * ONE), + (CHARLIE, HDX, 100_000_000 * ONE), + (BOB, HDX, 100_000_000 * ONE), + (ALICE, KSM, 10_000 * ONE), + (BOB, DOT, 10_000 * ONE), + ]) + .with_registered_asset(KSM) + .with_registered_asset(DOT) + .with_registered_asset(STABLESWAP_POOL_ID) + .with_initial_pool(FixedU128::from_float(0.5), FixedU128::from(1)) + .with_token(KSM, FixedU128::from_float(0.65), LP1, token_amount) + .with_token(STABLESWAP_POOL_ID, FixedU128::from_float(0.65), LP1, token_amount) + .with_global_farm( + //id: 1 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + GC, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + CHARLIE, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 3 + 60_000_000 * ONE, + 2_428_000, + 1, + HDX, + BOB, + Perquintill::from_float(0.000_000_14_f64), + 1_000, + FixedU128::one(), + ) + .with_yield_farm(GC, 1, STABLESWAP_POOL_ID, FixedU128::one(), None) //id: 4 + .build() + .execute_with(|| { + let gc_g_farm_id = 1; + let gc_y_farm_id = 4; + let amount = 20 * ONE; + let yield_farms = vec![(gc_g_farm_id, gc_y_farm_id)]; + + //Act and assert + assert_noop!(OmnipoolMining::add_liquidity_stableswap_omnipool_and_join_farms( + RuntimeOrigin::none(), + STABLESWAP_POOL_ID, + vec![AssetAmount::new(USDT, amount)].try_into().unwrap(), + yield_farms.try_into().unwrap(), + ), BadOrigin); + }); +} + +#[test] +fn add_liquidity_stableswap_omnipool_and_join_farms_should_fail_when_no_farm_specified() { + let token_amount = 2000 * ONE; + ExtBuilder::default() + .with_endowed_accounts(vec![ + (Omnipool::protocol_account(), DAI, 1000 * ONE), + (Omnipool::protocol_account(), HDX, NATIVE_AMOUNT), + (LP1, STABLESWAP_POOL_ID, 500000 * ONE), + (LP1, KSM, 5000 * ONE), + (LP2, DOT, 2000 * ONE), + (GC, HDX, 100_000_000 * ONE), + (CHARLIE, HDX, 100_000_000 * ONE), + (BOB, HDX, 100_000_000 * ONE), + (ALICE, KSM, 10_000 * ONE), + (BOB, DOT, 10_000 * ONE), + ]) + .with_registered_asset(KSM) + .with_registered_asset(DOT) + .with_registered_asset(STABLESWAP_POOL_ID) + .with_initial_pool(FixedU128::from_float(0.5), FixedU128::from(1)) + .with_token(KSM, FixedU128::from_float(0.65), LP1, token_amount) + .with_token(STABLESWAP_POOL_ID, FixedU128::from_float(0.65), LP1, token_amount) + .with_global_farm( + //id: 1 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + GC, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + CHARLIE, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 3 + 60_000_000 * ONE, + 2_428_000, + 1, + HDX, + BOB, + Perquintill::from_float(0.000_000_14_f64), + 1_000, + FixedU128::one(), + ) + .with_yield_farm(GC, 1, STABLESWAP_POOL_ID, FixedU128::one(), None) //id: 4 + .build() + .execute_with(|| { + let amount = 20 * ONE; + let yield_farms = vec![]; + + //Act and assert + assert_noop!(OmnipoolMining::add_liquidity_stableswap_omnipool_and_join_farms( + RuntimeOrigin::signed(LP1), + STABLESWAP_POOL_ID, + vec![AssetAmount::new(USDT, amount)].try_into().unwrap(), + yield_farms.try_into().unwrap(), + ), Error::::NoFarmEntriesSpecified); + }); +} \ No newline at end of file diff --git a/pallets/omnipool-liquidity-mining/src/tests/mock.rs b/pallets/omnipool-liquidity-mining/src/tests/mock.rs index e806caa88..0d917ad17 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mock.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mock.rs @@ -45,11 +45,7 @@ use sp_runtime::{ use warehouse_liquidity_mining::{GlobalFarmData, Instance1}; -use hydradx_traits::{ - oracle::{OraclePeriod, Source}, - pools::DustRemovalAccountWhitelist, - AssetKind, -}; +use hydradx_traits::{oracle::{OraclePeriod, Source}, pools::DustRemovalAccountWhitelist, AssetKind, stableswap::StableswapAddLiquidity}; type Block = frame_system::mocking::MockBlock; @@ -67,6 +63,7 @@ pub const DAI: AssetId = 2; pub const DOT: AssetId = 1_000; pub const KSM: AssetId = 1_001; pub const ACA: AssetId = 1_002; +pub const USDT: AssetId = 2_000; pub const LP1: AccountId = 1; pub const LP2: AccountId = 2; @@ -177,6 +174,7 @@ impl omnipool_liquidity_mining::Config for Test { type NFTCollectionId = LMCollectionId; type NFTHandler = DummyNFT; type LiquidityMiningHandler = WarehouseLM; + type Stableswap = StableswapAddLiquidityStub; type OracleSource = OracleSource; type OraclePeriod = PeriodOracle; type PriceOracle = DummyOracle; @@ -184,6 +182,16 @@ impl omnipool_liquidity_mining::Config for Test { type WeightInfo = (); } +pub const SHARES_FROM_STABLESWAP: u128 = 5 * ONE; +pub const STABLESWAP_POOL_ID: u32 = 72; +pub struct StableswapAddLiquidityStub; + +impl StableswapAddLiquidity for StableswapAddLiquidityStub { + fn add_liquidity(_who: AccountId, _pool_id: AssetId, _asset_amounts: Vec>) -> Result { + Ok(SHARES_FROM_STABLESWAP) + } +} + parameter_types! { pub const TreasuryPalletId: PalletId = PalletId(*b"aca/trsy"); pub TreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating(); @@ -744,6 +752,7 @@ where } use hydradx_traits::oracle::AggregatedPriceOracle; +use hydradx_traits::stableswap::AssetAmount; use pallet_omnipool::traits::ExternalPriceProvider; pub struct DummyOracle; @@ -772,6 +781,13 @@ impl AggregatedPriceOracle for DummyOracle { }, 0, )), + STABLESWAP_POOL_ID => Ok(( + OraclePrice { + n: 650_000_000_000_000_000, + d: 1_000_000_000_000_000_000, + }, + 0, + )), //Tokens used in benchmarks 1_000_001..=1_000_004 => Ok(( OraclePrice { diff --git a/pallets/omnipool-liquidity-mining/src/tests/mod.rs b/pallets/omnipool-liquidity-mining/src/tests/mod.rs index 78b1e56a9..533f93111 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mod.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mod.rs @@ -45,6 +45,7 @@ pub mod terminate_yield_farm; pub mod update_global_farm; pub mod update_yield_farm; pub mod withdraw_shares; +pub mod add_liquidity_stableswap_omnipool_and_join_farms; pub fn expect_events(e: Vec) { test_utils::expect_events::(e); diff --git a/pallets/stableswap/src/lib.rs b/pallets/stableswap/src/lib.rs index b262929d5..add4966c9 100644 --- a/pallets/stableswap/src/lib.rs +++ b/pallets/stableswap/src/lib.rs @@ -55,8 +55,8 @@ extern crate core; use frame_support::pallet_prelude::{DispatchResult, Get}; use frame_support::{ensure, require_transactional, transactional, PalletId}; -use frame_system::pallet_prelude::BlockNumberFor; -use hydradx_traits::{registry::Inspect, AccountIdFor}; +use frame_system::pallet_prelude::{BlockNumberFor, OriginFor}; +use hydradx_traits::{registry::Inspect, AccountIdFor, AMMAddLiquidity, stableswap::StableswapAddLiquidity}; pub use pallet::*; use sp_runtime::traits::{AccountIdConversion, BlockNumberProvider, Zero}; use sp_runtime::{ArithmeticError, DispatchError, Permill, SaturatedConversion}; @@ -68,7 +68,8 @@ mod trade_execution; pub mod types; pub mod weights; -use crate::types::{AssetAmount, Balance, PoolInfo, PoolState, StableswapHooks, Tradability}; +use crate::types::{Balance, PoolInfo, PoolState, StableswapHooks, Tradability}; +use hydradx_traits::stableswap::AssetAmount; use hydra_dx_math::stableswap::types::AssetReserve; use hydradx_traits::pools::DustRemovalAccountWhitelist; use orml_traits::MultiCurrency; @@ -479,14 +480,7 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; - let shares = Self::do_add_liquidity(&who, pool_id, &assets)?; - - Self::deposit_event(Event::LiquidityAdded { - pool_id, - who, - shares, - assets, - }); + Self::do_add_liquidity(&who, pool_id, &assets)?; Ok(()) } @@ -1188,6 +1182,13 @@ impl Pallet { #[cfg(feature = "try-runtime")] Self::ensure_add_liquidity_invariant(pool_id, &initial_reserves); + Self::deposit_event(Event::LiquidityAdded { + pool_id, + who: who.clone(), + shares: share_amount, + assets: assets.clone().to_vec(), + }); + Ok(share_amount) } @@ -1464,3 +1465,16 @@ impl Pallet { } } } + +impl StableswapAddLiquidity for Pallet { + fn add_liquidity(who: T::AccountId, pool_id: T::AssetId, assets: Vec>) -> Result { + let asset_amounts = assets.iter().map(|asset| { + AssetAmount { + asset_id: asset.asset_id, + amount: asset.amount, + } + }).collect::>(); + + Self::do_add_liquidity(&who, pool_id, &asset_amounts) + } +} \ No newline at end of file diff --git a/pallets/stableswap/src/tests/add_liquidity.rs b/pallets/stableswap/src/tests/add_liquidity.rs index 81fc88e48..21fd28c96 100644 --- a/pallets/stableswap/src/tests/add_liquidity.rs +++ b/pallets/stableswap/src/tests/add_liquidity.rs @@ -1,5 +1,6 @@ use crate::tests::mock::*; -use crate::types::{AssetAmount, PoolInfo}; +use crate::types::{PoolInfo}; +use hydradx_traits::stableswap::AssetAmount; use crate::{assert_balance, to_precision, Error}; use frame_support::{assert_noop, assert_ok}; use sp_runtime::Permill; diff --git a/pallets/stableswap/src/tests/calculate_spot_price.rs b/pallets/stableswap/src/tests/calculate_spot_price.rs index d28553512..1ad4bf35d 100644 --- a/pallets/stableswap/src/tests/calculate_spot_price.rs +++ b/pallets/stableswap/src/tests/calculate_spot_price.rs @@ -2,7 +2,8 @@ use crate::assert_balance; use crate::tests::mock::*; -use crate::types::{AssetAmount, PoolInfo}; +use crate::types::{PoolInfo}; +use hydradx_traits::stableswap::AssetAmount; use frame_support::assert_ok; use hydradx_traits::router::PoolType; use hydradx_traits::router::TradeExecution; diff --git a/pallets/stableswap/src/tests/hooks.rs b/pallets/stableswap/src/tests/hooks.rs index 365cc437b..7885fce13 100644 --- a/pallets/stableswap/src/tests/hooks.rs +++ b/pallets/stableswap/src/tests/hooks.rs @@ -1,5 +1,6 @@ use crate::tests::mock::*; -use crate::types::{AssetAmount, PoolInfo, PoolState}; +use crate::types::{PoolInfo, PoolState}; +use hydradx_traits::stableswap::AssetAmount; use frame_support::assert_ok; use sp_runtime::Permill; use std::num::NonZeroU16; diff --git a/pallets/stableswap/src/tests/invariants.rs b/pallets/stableswap/src/tests/invariants.rs index 04fe399fa..c118fee8d 100644 --- a/pallets/stableswap/src/tests/invariants.rs +++ b/pallets/stableswap/src/tests/invariants.rs @@ -1,5 +1,6 @@ use crate::tests::*; -use crate::types::{AssetAmount, PoolInfo}; +use crate::types::{PoolInfo}; +use hydradx_traits::stableswap::AssetAmount; use frame_support::{assert_ok, BoundedVec}; use sp_runtime::{FixedU128, Permill}; use std::cmp::Ordering; diff --git a/pallets/stableswap/src/tests/mock.rs b/pallets/stableswap/src/tests/mock.rs index 8e71647c7..8a6ce5156 100644 --- a/pallets/stableswap/src/tests/mock.rs +++ b/pallets/stableswap/src/tests/mock.rs @@ -316,7 +316,8 @@ impl ExtBuilder { #[cfg(feature = "runtime-benchmarks")] use crate::types::BenchmarkHelper; -use crate::types::{AssetAmount, PoolInfo, PoolState, StableswapHooks}; +use crate::types::{PoolInfo, PoolState, StableswapHooks}; +use hydradx_traits::stableswap::AssetAmount; use hydradx_traits::pools::DustRemovalAccountWhitelist; use hydradx_traits::{AccountIdFor, Inspect}; use sp_runtime::traits::Zero; diff --git a/pallets/stableswap/src/tests/price.rs b/pallets/stableswap/src/tests/price.rs index ba78a491b..cb4b27870 100644 --- a/pallets/stableswap/src/tests/price.rs +++ b/pallets/stableswap/src/tests/price.rs @@ -1,5 +1,6 @@ use crate::tests::*; -use crate::types::{AssetAmount, PoolInfo}; +use crate::types::{PoolInfo}; +use hydradx_traits::stableswap::AssetAmount; use frame_support::assert_ok; use sp_runtime::{FixedU128, Permill}; use std::num::NonZeroU16; diff --git a/pallets/stableswap/src/tests/remove_liquidity.rs b/pallets/stableswap/src/tests/remove_liquidity.rs index f70b6f8a7..21336f325 100644 --- a/pallets/stableswap/src/tests/remove_liquidity.rs +++ b/pallets/stableswap/src/tests/remove_liquidity.rs @@ -1,6 +1,7 @@ use crate::tests::mock::*; -use crate::types::{AssetAmount, PoolInfo}; +use crate::types::{PoolInfo}; use crate::{assert_balance, Error, Event, Pools}; +use hydradx_traits::stableswap::AssetAmount; use frame_support::traits::Contains; use frame_support::{assert_noop, assert_ok, BoundedVec}; use sp_runtime::Permill; diff --git a/pallets/stableswap/src/tests/trades.rs b/pallets/stableswap/src/tests/trades.rs index d27b7fd44..a1971a604 100644 --- a/pallets/stableswap/src/tests/trades.rs +++ b/pallets/stableswap/src/tests/trades.rs @@ -1,5 +1,6 @@ use crate::tests::mock::*; -use crate::types::{AssetAmount, PoolInfo}; +use crate::types::{PoolInfo}; +use hydradx_traits::stableswap::AssetAmount; use crate::{assert_balance, to_precision, Error}; use std::num::NonZeroU16; diff --git a/pallets/stableswap/src/trade_execution.rs b/pallets/stableswap/src/trade_execution.rs index 53d54e25a..1466785b8 100644 --- a/pallets/stableswap/src/trade_execution.rs +++ b/pallets/stableswap/src/trade_execution.rs @@ -1,4 +1,4 @@ -use crate::types::AssetAmount; +use hydradx_traits::stableswap::AssetAmount; use crate::{Balance, Config, Error, Pallet, Pools, D_ITERATIONS, Y_ITERATIONS}; use hydra_dx_math::stableswap::types::AssetReserve; use hydradx_traits::router::{ExecutorError, PoolType, TradeExecution}; diff --git a/pallets/stableswap/src/types.rs b/pallets/stableswap/src/types.rs index 17a8002d0..c1a10fc19 100644 --- a/pallets/stableswap/src/types.rs +++ b/pallets/stableswap/src/types.rs @@ -74,28 +74,6 @@ where } } -#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo, Default)] -pub struct AssetAmount { - pub asset_id: AssetId, - pub amount: Balance, -} - -impl AssetAmount { - pub fn new(asset_id: AssetId, amount: Balance) -> Self { - Self { asset_id, amount } - } -} - -impl From> for u128 { - fn from(value: AssetAmount) -> Self { - value.amount - } -} -impl From<&AssetAmount> for u128 { - fn from(value: &AssetAmount) -> Self { - value.amount - } -} bitflags::bitflags! { /// Indicates whether asset can be bought or sold to/from Omnipool and/or liquidity added/removed. diff --git a/runtime-mock/Cargo.toml b/runtime-mock/Cargo.toml index 5fb31cac6..e1f2481d0 100644 --- a/runtime-mock/Cargo.toml +++ b/runtime-mock/Cargo.toml @@ -14,6 +14,7 @@ toml = { workspace = true } # local dependencies hydradx-runtime = { workspace = true } +hydradx-traits = { workspace = true } primitives = { workspace = true } # Substrate dependencies diff --git a/runtime-mock/src/stableswap.rs b/runtime-mock/src/stableswap.rs index 2b9d388b0..303695b64 100644 --- a/runtime-mock/src/stableswap.rs +++ b/runtime-mock/src/stableswap.rs @@ -1,6 +1,6 @@ use crate::{AccountId, MockedRuntime}; use hydradx_runtime::RuntimeCall; -use pallet_stableswap::types::AssetAmount; +use hydradx_traits::stableswap::AssetAmount; use serde::Deserialize; use serde::Deserializer; use sp_runtime::{FixedPointNumber, FixedU128, Permill}; diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 8a99084c1..2da446109 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -662,6 +662,7 @@ impl pallet_omnipool_liquidity_mining::Config for Runtime { type NFTCollectionId = OmnipoolLMCollectionId; type NFTHandler = Uniques; type LiquidityMiningHandler = OmnipoolWarehouseLM; + type Stableswap = Stableswap; type OracleSource = OmnipoolLMOracleSource; type OraclePeriod = OmnipoolLMOraclePeriod; type PriceOracle = EmaOracle; diff --git a/traits/src/lib.rs b/traits/src/lib.rs index c21b44ebb..f5f0bb394 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -27,6 +27,7 @@ pub mod pools; pub mod price; pub mod registry; pub mod router; +pub mod stableswap; pub use oracle::*; pub use registry::*; @@ -287,6 +288,7 @@ pub trait AMMAddLiquidity { ) -> Result; } + /// Provides account's fee payment asset pub trait AccountFeeCurrency { type AssetId; diff --git a/traits/src/stableswap.rs b/traits/src/stableswap.rs new file mode 100644 index 000000000..70d8a3cbb --- /dev/null +++ b/traits/src/stableswap.rs @@ -0,0 +1,36 @@ +use codec::{Decode, Encode}; +use frame_support::__private::DispatchError; +use frame_support::pallet_prelude::TypeInfo; +use sp_std::vec::Vec; + +pub trait StableswapAddLiquidity { + fn add_liquidity( + who: AccountId, + pool_id: AssetId, + assets_amounts: Vec> + ) -> Result; +} + + +#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo, Default)] +pub struct AssetAmount { + pub asset_id: AssetId, + pub amount: u128, +} + +impl AssetAmount { + pub fn new(asset_id: AssetId, amount: u128) -> Self { + Self { asset_id, amount } + } +} + +impl From> for u128 { + fn from(value: AssetAmount) -> Self { + value.amount + } +} +impl From<&AssetAmount> for u128 { + fn from(value: &AssetAmount) -> Self { + value.amount + } +} \ No newline at end of file From fe05d998f5f010807fe9349e5b8f23ff1cc604bb Mon Sep 17 00:00:00 2001 From: dmoka Date: Mon, 25 Nov 2024 14:49:06 +0100 Subject: [PATCH 02/36] add add_liquidity_with_limit_and_join_farms --- integration-tests/src/dca.rs | 2 +- .../src/omnipool_liquidity_mining.rs | 260 ++++++-- pallets/omnipool-liquidity-mining/src/lib.rs | 55 +- ...dity_stableswap_omnipool_and_join_farms.rs | 38 +- ...add_liquidity_with_limit_and_join_farms.rs | 558 ++++++++++++++++++ .../src/tests/mock.rs | 13 +- .../src/tests/mod.rs | 3 +- 7 files changed, 868 insertions(+), 61 deletions(-) create mode 100644 pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs diff --git a/integration-tests/src/dca.rs b/integration-tests/src/dca.rs index e079caa04..8698a29f7 100644 --- a/integration-tests/src/dca.rs +++ b/integration-tests/src/dca.rs @@ -18,11 +18,11 @@ use hydradx_traits::registry::{AssetKind, Create}; use hydradx_traits::router::AssetPair; use hydradx_traits::router::PoolType; use hydradx_traits::router::Trade; +use hydradx_traits::stableswap::AssetAmount; use orml_traits::MultiCurrency; use orml_traits::MultiReservableCurrency; use pallet_dca::types::{Order, Schedule}; use pallet_omnipool::types::Tradability; -use hydradx_traits::stableswap::AssetAmount; use pallet_stableswap::MAX_ASSETS_IN_POOL; use primitives::{AssetId, Balance}; use sp_runtime::traits::ConstU32; diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index 277450935..dbec86c56 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -17,28 +17,34 @@ #![cfg(test)] use crate::polkadot_test_net::*; -use hydradx_traits::Create; use frame_support::assert_ok; +use frame_support::storage::with_transaction; +use hydradx_runtime::Omnipool; use hydradx_traits::liquidity_mining::PriceAdjustment; +use hydradx_traits::Create; +use orml_traits::MultiCurrency; +use primitives::{constants::currency::UNITS, AssetId}; +use sp_runtime::DispatchResult; +use sp_runtime::TransactionOutcome; +use sp_runtime::{ + traits::{One, Zero}, + DispatchError, FixedPointNumber, FixedU128, Permill, Perquintill, +}; use warehouse_liquidity_mining::{ DefaultPriceAdjustment, DepositData, GlobalFarmData, GlobalFarmId, Instance1, LoyaltyCurve, YieldFarmData, YieldFarmEntry, }; -use hydradx_runtime::Omnipool; -use frame_support::storage::with_transaction; -use sp_runtime::TransactionOutcome; -use sp_runtime::DispatchResult; -use orml_traits::MultiCurrency; -use primitives::{constants::currency::UNITS, AssetId}; -use sp_runtime::{traits::{One, Zero}, FixedPointNumber, FixedU128, Permill, Perquintill, DispatchError}; use xcm_emulator::TestExt; - -use hydradx_runtime::{AssetRegistry, Balance, Bonds, Currencies, Runtime, RuntimeEvent, RuntimeOrigin, Stableswap, Treasury, TreasuryAccount}; -use pallet_asset_registry::AssetType; -use pretty_assertions::assert_eq; -use hydradx_traits::AssetKind; +use frame_support::assert_noop; +use hydradx_runtime::{ + AssetRegistry, Balance, Bonds, Currencies, Runtime, RuntimeEvent, RuntimeOrigin, Stableswap, Treasury, + TreasuryAccount, +}; use hydradx_traits::stableswap::AssetAmount; +use hydradx_traits::AssetKind; +use pallet_asset_registry::AssetType; use pallet_stableswap::MAX_ASSETS_IN_POOL; +use pretty_assertions::assert_eq; use primitives::constants::time::unix_time::MONTH; #[macro_export] @@ -517,6 +523,185 @@ fn add_liquidity_and_join_farms_should_work_for_multiple_farms() { }); } +#[test] +fn add_liquidity_with_limit_and_join_farms_should_work_for_multiple_farms() { + TestNet::reset(); + + Hydra::execute_with(|| { + let global_farm_1_id = 1; + let global_farm_2_id = 2; + let global_farm_3_id = 3; + let yield_farm_1_id = 4; + let yield_farm_2_id = 5; + let yield_farm_3_id = 6; + + //Arrange + init_omnipool(); + seed_lm_pot(); + + //NOTE: necessary to get oracle price. + hydradx_run_to_block(100); + set_relaychain_block_number(100); + create_global_farm(None, None); + create_global_farm(None, None); + create_global_farm(None, None); + + set_relaychain_block_number(200); + create_yield_farm(global_farm_1_id, ETH); + create_yield_farm(global_farm_2_id, ETH); + create_yield_farm(global_farm_3_id, ETH); + + set_relaychain_block_number(300); + + assert_ok!(hydradx_runtime::Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + CHARLIE.into(), + ETH, + 10_000 * UNITS as i128, + )); + + //Add some liquidiity to make sure that it does not interfere with the new liquidty add + assert_ok!(hydradx_runtime::Omnipool::add_liquidity( + RuntimeOrigin::signed(CHARLIE.into()), + ETH, + 100 * UNITS, + )); + + let position_id = hydradx_runtime::Omnipool::next_position_id(); + + set_relaychain_block_number(400); + let deposit_id = 1; + let farms = vec![ + (global_farm_1_id, yield_farm_1_id), + (global_farm_2_id, yield_farm_2_id), + (global_farm_3_id, yield_farm_3_id), + ]; + assert_ok!( + hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_with_limit_and_join_farms( + RuntimeOrigin::signed(CHARLIE.into()), + farms.try_into().unwrap(), + ETH, + 1_000 * UNITS, + 1_000 * UNITS + ) + ); + + //Assert that the ownership of the nft should be transferred to omnipool account + let lm_account = hydradx_runtime::OmnipoolLiquidityMining::account_id(); + assert_nft_owner!(hydradx_runtime::OmnipoolCollectionId::get(), position_id, lm_account); + + set_relaychain_block_number(500); + + let deposit = hydradx_runtime::OmnipoolWarehouseLM::deposit(deposit_id).unwrap(); + let mut expected_deposit = DepositData::new(1_000_000_000_000_000, ETH); + //1-th deposit entry + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + global_farm_1_id, + yield_farm_1_id, + 71_145_071_145_u128, + FixedU128::zero(), + 40, + 0, + )) + .unwrap(); + + //2-nd redeposit entry + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + global_farm_2_id, + yield_farm_2_id, + 71_145_071_145_u128, //NOTE: nothing changed in omnipool so shares are + //valued same as before + FixedU128::zero(), + 40, + 0, + )) + .unwrap(); + + //3-nd redeposit entry + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + global_farm_3_id, + yield_farm_3_id, + 71_145_071_145_u128, //NOTE: nothing changed in omnipool so shares are + //valued same as before + FixedU128::zero(), + 40, + 0, + )) + .unwrap(); + + assert_eq!(deposit, expected_deposit); + }); +} + +#[test] +fn add_liquidity_with_limit_and_join_farms_should_fail_when_reaches_limit() { + TestNet::reset(); + + Hydra::execute_with(|| { + let global_farm_1_id = 1; + let global_farm_2_id = 2; + let global_farm_3_id = 3; + let yield_farm_1_id = 4; + let yield_farm_2_id = 5; + let yield_farm_3_id = 6; + + //Arrange + init_omnipool(); + seed_lm_pot(); + + //NOTE: necessary to get oracle price. + hydradx_run_to_block(100); + set_relaychain_block_number(100); + create_global_farm(None, None); + create_global_farm(None, None); + create_global_farm(None, None); + + set_relaychain_block_number(200); + create_yield_farm(global_farm_1_id, ETH); + create_yield_farm(global_farm_2_id, ETH); + create_yield_farm(global_farm_3_id, ETH); + + set_relaychain_block_number(300); + + assert_ok!(hydradx_runtime::Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + CHARLIE.into(), + ETH, + 10_000 * UNITS as i128, + )); + + //Add some liquidiity to make sure that it does not interfere with the new liquidty add + assert_ok!(hydradx_runtime::Omnipool::add_liquidity( + RuntimeOrigin::signed(CHARLIE.into()), + ETH, + 100 * UNITS, + )); + + let position_id = hydradx_runtime::Omnipool::next_position_id(); + + set_relaychain_block_number(400); + let deposit_id = 1; + let farms = vec![ + (global_farm_1_id, yield_farm_1_id), + (global_farm_2_id, yield_farm_2_id), + (global_farm_3_id, yield_farm_3_id), + ]; + assert_noop!( + hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_with_limit_and_join_farms( + RuntimeOrigin::signed(CHARLIE.into()), + farms.try_into().unwrap(), + ETH, + 1_000 * UNITS, + 1_000 * UNITS + 1 + ), + pallet_omnipool::Error::::SlippageLimit + ); + }); +} + #[test] fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_for_multiple_farms() { TestNet::reset(); @@ -537,19 +722,19 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_for_multiple_far seed_lm_pot(); assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - stable_pool_id, - 30_000_000 * UNITS as i128, - )); + RuntimeOrigin::root(), + Omnipool::protocol_account(), + stable_pool_id, + 30_000_000 * UNITS as i128, + )); assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - stable_pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); + RuntimeOrigin::root(), + stable_pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); //NOTE: necessary to get oracle price. hydradx_run_to_block(100); @@ -574,10 +759,10 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_for_multiple_far //Add some liquidiity to make sure that it does not interfere with the new liquidty add assert_ok!(hydradx_runtime::Omnipool::add_liquidity( - RuntimeOrigin::signed(CHARLIE.into()), - ETH, - 100 * UNITS, - )); + RuntimeOrigin::signed(CHARLIE.into()), + ETH, + 100 * UNITS, + )); let position_id = hydradx_runtime::Omnipool::next_position_id(); @@ -602,12 +787,19 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_for_multiple_far stable_asset_2, 100 * UNITS as i128, )); - assert_ok!(hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_stableswap_omnipool_and_join_farms( - RuntimeOrigin::signed(CHARLIE.into()), - stable_pool_id, - vec![AssetAmount::new(stable_asset_1, 10 * UNITS), AssetAmount::new(stable_asset_2, 10 * UNITS)].try_into().unwrap(), - farms.try_into().unwrap() - )); + assert_ok!( + hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_stableswap_omnipool_and_join_farms( + RuntimeOrigin::signed(CHARLIE.into()), + stable_pool_id, + vec![ + AssetAmount::new(stable_asset_1, 10 * UNITS), + AssetAmount::new(stable_asset_2, 10 * UNITS) + ] + .try_into() + .unwrap(), + farms.try_into().unwrap() + ) + ); //Assert that the ownership of the nft should be transferred to omnipool account let lm_account = hydradx_runtime::OmnipoolLiquidityMining::account_id(); diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index 2938bb931..ae60a8915 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -60,11 +60,14 @@ use frame_system::{ pallet_prelude::{BlockNumberFor, OriginFor}, }; use hydra_dx_math::ema::EmaPrice as Price; +use hydradx_traits::stableswap::AssetAmount; +use hydradx_traits::stableswap::StableswapAddLiquidity; use hydradx_traits::{ liquidity_mining::{GlobalFarmId, Mutate as LiquidityMiningMutate, YieldFarmId}, oracle::{AggregatedPriceOracle, OraclePeriod, Source}, }; use orml_traits::MultiCurrency; +pub use pallet::*; use pallet_ema_oracle::OracleError; use pallet_liquidity_mining::{FarmMultiplier, LoyaltyCurve}; use pallet_omnipool::{types::Position as OmniPosition, NFTCollectionIdOf}; @@ -72,10 +75,7 @@ use primitive_types::U256; use primitives::{Balance, ItemId as DepositId}; use sp_runtime::{ArithmeticError, FixedU128, Perquintill}; use sp_std::vec; -use hydradx_traits::stableswap::StableswapAddLiquidity; -pub use pallet::*; pub use weights::WeightInfo; -use hydradx_traits::stableswap::AssetAmount; type OmnipoolPallet = pallet_omnipool::Pallet; type PeriodOf = BlockNumberFor; @@ -1000,9 +1000,46 @@ pub mod pallet { Ok(()) } - /// TODO: ADD DOC + /// This function allows user to add liquidity then use that shares to join multiple farms. + /// + /// Limit protection is applied. + /// + /// Parameters: + /// - `origin`: owner of the omnipool position to deposit into the liquidity mining. + /// - `farm_entries`: list of farms to join. + /// - `asset`: id of the asset to be deposited into the liquidity mining. + /// - `amount`: amount of the asset to be deposited into the liquidity mining. + /// - `min_shares_limit`: The min amount of delta share asset the user should receive in the position + /// + /// Emits `SharesDeposited` event for the first farm entry + /// Emits `SharesRedeposited` event for each farm entry after the first one #[pallet::call_index(16)] - #[pallet::weight(::WeightInfo::exit_farms(farm_entries.len() as u32))]//TODO: rebenchmark + #[pallet::weight(::WeightInfo::add_liquidity_and_join_farms(farm_entries.len() as u32))] //TODO: add bench? or not needed + pub fn add_liquidity_with_limit_and_join_farms( + origin: OriginFor, + farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, + asset: T::AssetId, + amount: Balance, + min_shares_limit: Balance, + ) -> DispatchResult { + ensure_signed(origin.clone())?; + ensure!(!farm_entries.is_empty(), Error::::NoFarmEntriesSpecified); + + let position_id = crate::OmnipoolPallet::::do_add_liquidity_with_limit( + origin.clone(), + asset, + amount, + min_shares_limit, + )?; + + Self::join_farms(origin, farm_entries, position_id)?; + + Ok(()) + } + + /// TODO: ADD DOC + #[pallet::call_index(17)] + #[pallet::weight(::WeightInfo::exit_farms(farm_entries.len() as u32))] //TODO: rebenchmark pub fn add_liquidity_stableswap_omnipool_and_join_farms( origin: OriginFor, stable_pool_id: T::AssetId, @@ -1014,8 +1051,12 @@ pub mod pallet { let stablepool_shares = T::Stableswap::add_liquidity(who, stable_pool_id, stable_asset_amounts.to_vec())?; - let position_id = - OmnipoolPallet::::do_add_liquidity_with_limit(origin.clone(), stable_pool_id, stablepool_shares, Balance::MIN)?; + let position_id = OmnipoolPallet::::do_add_liquidity_with_limit( + origin.clone(), + stable_pool_id, + stablepool_shares, + Balance::MIN, + )?; Self::join_farms(origin, farm_entries, position_id)?; diff --git a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs index e28cdb165..775f596a8 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs @@ -257,7 +257,7 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_with_multiple_yi shares_amount: SHARES_FROM_STABLESWAP, position_id: omnipool_position_id, } - .into(), + .into(), crate::Event::SharesRedeposited { global_farm_id: charlie_g_farm_id, yield_farm_id: charlie_y_farm_id, @@ -267,7 +267,7 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_with_multiple_yi shares_amount: SHARES_FROM_STABLESWAP, position_id: omnipool_position_id, } - .into(), + .into(), crate::Event::SharesRedeposited { global_farm_id: bob_g_farm_id, yield_farm_id: bob_y_farm_id, @@ -277,7 +277,7 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_with_multiple_yi shares_amount: SHARES_FROM_STABLESWAP, position_id: omnipool_position_id, } - .into(), + .into(), ]); assert_eq!( @@ -398,12 +398,15 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_fail_when_origin_is_n let yield_farms = vec![(gc_g_farm_id, gc_y_farm_id)]; //Act and assert - assert_noop!(OmnipoolMining::add_liquidity_stableswap_omnipool_and_join_farms( - RuntimeOrigin::none(), - STABLESWAP_POOL_ID, - vec![AssetAmount::new(USDT, amount)].try_into().unwrap(), - yield_farms.try_into().unwrap(), - ), BadOrigin); + assert_noop!( + OmnipoolMining::add_liquidity_stableswap_omnipool_and_join_farms( + RuntimeOrigin::none(), + STABLESWAP_POOL_ID, + vec![AssetAmount::new(USDT, amount)].try_into().unwrap(), + yield_farms.try_into().unwrap(), + ), + BadOrigin + ); }); } @@ -469,11 +472,14 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_fail_when_no_farm_spe let yield_farms = vec![]; //Act and assert - assert_noop!(OmnipoolMining::add_liquidity_stableswap_omnipool_and_join_farms( - RuntimeOrigin::signed(LP1), - STABLESWAP_POOL_ID, - vec![AssetAmount::new(USDT, amount)].try_into().unwrap(), - yield_farms.try_into().unwrap(), - ), Error::::NoFarmEntriesSpecified); + assert_noop!( + OmnipoolMining::add_liquidity_stableswap_omnipool_and_join_farms( + RuntimeOrigin::signed(LP1), + STABLESWAP_POOL_ID, + vec![AssetAmount::new(USDT, amount)].try_into().unwrap(), + yield_farms.try_into().unwrap(), + ), + Error::::NoFarmEntriesSpecified + ); }); -} \ No newline at end of file +} diff --git a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs new file mode 100644 index 000000000..11124237f --- /dev/null +++ b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs @@ -0,0 +1,558 @@ +// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::*; + +use pallet_liquidity_mining::{DepositData, YieldFarmEntry}; +use pallet_omnipool::types::AssetReserveState; +use pallet_omnipool::types::Tradability; +use pretty_assertions::assert_eq; + +#[test] +fn add_liquidity_with_limit_and_join_farms_should_work_with_single_yield_farm() { + let token_amount = 2000 * ONE; + ExtBuilder::default() + .with_endowed_accounts(vec![ + (Omnipool::protocol_account(), DAI, 1000 * ONE), + (Omnipool::protocol_account(), HDX, NATIVE_AMOUNT), + (LP1, KSM, 5000 * ONE), + (LP2, DOT, 2000 * ONE), + (GC, HDX, 100_000_000 * ONE), + (CHARLIE, HDX, 100_000_000 * ONE), + (BOB, HDX, 100_000_000 * ONE), + (ALICE, KSM, 10_000 * ONE), + (BOB, DOT, 10_000 * ONE), + ]) + .with_registered_asset(KSM) + .with_registered_asset(DOT) + .with_initial_pool(FixedU128::from_float(0.5), FixedU128::from(1)) + .with_token(KSM, FixedU128::from_float(0.65), LP1, token_amount) + .with_global_farm( + //id: 1 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + GC, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + CHARLIE, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 3 + 60_000_000 * ONE, + 2_428_000, + 1, + HDX, + BOB, + Perquintill::from_float(0.000_000_14_f64), + 1_000, + FixedU128::one(), + ) + .with_yield_farm(GC, 1, KSM, FixedU128::one(), None) //id: 4 + .build() + .execute_with(|| { + let gc_g_farm_id = 1; + let gc_y_farm_id = 4; + let omnipool_position_id = 3; + let deposit_id = 1; + let asset_in_position = KSM; + let amount = 20 * ONE; + let yield_farms = vec![(gc_g_farm_id, gc_y_farm_id)]; + + assert_ok!(OmnipoolMining::add_liquidity_with_limit_and_join_farms( + RuntimeOrigin::signed(LP1), + yield_farms.try_into().unwrap(), + asset_in_position, + amount, + u128::MIN + )); + + //Assert that liquidity is added + assert_asset_state!( + asset_in_position, + AssetReserveState { + reserve: token_amount + amount, + hub_reserve: 1313 * ONE, + shares: token_amount + amount, + protocol_shares: 0, + cap: DEFAULT_WEIGHT_CAP, + tradable: Tradability::default(), + } + ); + + //Assert join farms functionality + expect_events(vec![crate::Event::SharesDeposited { + global_farm_id: gc_g_farm_id, + yield_farm_id: gc_y_farm_id, + deposit_id, + asset_id: KSM, + who: LP1, + shares_amount: amount, + position_id: omnipool_position_id, + } + .into()]); + + assert_eq!( + crate::OmniPositionId::::get(deposit_id).unwrap(), + omnipool_position_id + ); + + let deposit = + pallet_liquidity_mining::Deposit::::get(deposit_id).unwrap(); + let mut expected_deposit = DepositData::new(amount, KSM); + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + gc_g_farm_id, + gc_y_farm_id, + 13_000_000_000_000, + FixedU128::zero(), + 1, + 0, + )) + .unwrap(); + + assert_eq!(deposit, expected_deposit); + + //NFT check: lm account should be owner of the omnipool position. + let lm_account = OmnipoolMining::account_id(); + let owner: AccountId = DummyNFT::owner(&OMNIPOOL_COLLECTION_ID, &omnipool_position_id).unwrap(); + assert_eq!(owner, lm_account); + + //NFT check: lm deposit should be minted for user. + let owner: AccountId = DummyNFT::owner(&LM_COLLECTION_ID, &deposit_id).unwrap(); + assert_eq!(owner, LP1); + }); +} + +#[test] +fn add_liquidity_join_farms_should_fail_when_doesnt_reach_limit() { + let token_amount = 2000 * ONE; + ExtBuilder::default() + .with_endowed_accounts(vec![ + (Omnipool::protocol_account(), DAI, 1000 * ONE), + (Omnipool::protocol_account(), HDX, NATIVE_AMOUNT), + (LP1, KSM, 5000 * ONE), + (LP2, DOT, 2000 * ONE), + (GC, HDX, 100_000_000 * ONE), + (CHARLIE, HDX, 100_000_000 * ONE), + (BOB, HDX, 100_000_000 * ONE), + (ALICE, KSM, 10_000 * ONE), + (BOB, DOT, 10_000 * ONE), + ]) + .with_registered_asset(KSM) + .with_registered_asset(DOT) + .with_initial_pool(FixedU128::from_float(0.5), FixedU128::from(1)) + .with_token(KSM, FixedU128::from_float(0.65), LP1, token_amount) + .with_global_farm( + //id: 1 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + GC, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + CHARLIE, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 3 + 60_000_000 * ONE, + 2_428_000, + 1, + HDX, + BOB, + Perquintill::from_float(0.000_000_14_f64), + 1_000, + FixedU128::one(), + ) + .with_yield_farm(GC, 1, KSM, FixedU128::one(), None) //id: 4 + .build() + .execute_with(|| { + let gc_g_farm_id = 1; + let gc_y_farm_id = 4; + let omnipool_position_id = 3; + let deposit_id = 1; + let asset_in_position = KSM; + let amount = 20 * ONE; + let yield_farms = vec![(gc_g_farm_id, gc_y_farm_id)]; + + assert_noop!( + OmnipoolMining::add_liquidity_with_limit_and_join_farms( + RuntimeOrigin::signed(LP1), + yield_farms.try_into().unwrap(), + asset_in_position, + amount, + amount + 1 + ), + pallet_omnipool::Error::::SlippageLimit + ); + }); +} + +#[test] +fn join_farms_should_work_with_multiple_yield_farm() { + let token_amount = 2000 * ONE; + + ExtBuilder::default() + .with_endowed_accounts(vec![ + (Omnipool::protocol_account(), DAI, 1000 * ONE), + (Omnipool::protocol_account(), HDX, NATIVE_AMOUNT), + (LP1, KSM, 5000 * ONE), + (LP2, DOT, 2000 * ONE), + (GC, HDX, 100_000_000 * ONE), + (CHARLIE, HDX, 100_000_000 * ONE), + (BOB, HDX, 100_000_000 * ONE), + (ALICE, KSM, 10_000 * ONE), + (BOB, DOT, 10_000 * ONE), + ]) + .with_registered_asset(KSM) + .with_registered_asset(DOT) + .with_initial_pool(FixedU128::from_float(0.5), FixedU128::from(1)) + .with_token(KSM, FixedU128::from_float(0.65), LP1, token_amount) + .with_global_farm( + //id: 1 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + GC, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + CHARLIE, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 3 + 60_000_000 * ONE, + 2_428_000, + 1, + HDX, + BOB, + Perquintill::from_float(0.000_000_14_f64), + 1_000, + FixedU128::one(), + ) + .with_yield_farm(GC, 1, KSM, FixedU128::one(), None) //id: 4 + .with_yield_farm(CHARLIE, 2, KSM, FixedU128::one(), None) //id: 5 + .with_yield_farm(BOB, 3, KSM, FixedU128::one(), None) //id: 6 + .build() + .execute_with(|| { + let gc_g_farm_id = 1; + let gc_y_farm_id = 4; + let charlie_g_farm_id = 2; + let charlie_y_farm_id = 5; + let bob_g_farm_id = 3; + let bob_y_farm_id = 6; + let omnipool_position_id = 3; + let deposit_id = 1; + let asset_in_position = KSM; + let amount = 10 * ONE; + let yield_farms = vec![ + (gc_g_farm_id, gc_y_farm_id), + (charlie_g_farm_id, charlie_y_farm_id), + (bob_g_farm_id, bob_y_farm_id), + ]; + + assert_ok!(OmnipoolMining::add_liquidity_with_limit_and_join_farms( + RuntimeOrigin::signed(LP1), + yield_farms.try_into().unwrap(), + KSM, + amount, + u128::MIN + )); + + //Assert that liquidity is added + assert_asset_state!( + asset_in_position, + AssetReserveState { + reserve: token_amount + amount, + hub_reserve: 1_306_500_000_000_000, + shares: token_amount + amount, + protocol_shares: 0, + cap: DEFAULT_WEIGHT_CAP, + tradable: Tradability::default(), + } + ); + + //Assert + expect_events(vec![ + crate::Event::SharesDeposited { + global_farm_id: gc_g_farm_id, + yield_farm_id: gc_y_farm_id, + deposit_id, + asset_id: KSM, + who: LP1, + shares_amount: amount, + position_id: omnipool_position_id, + } + .into(), + crate::Event::SharesRedeposited { + global_farm_id: charlie_g_farm_id, + yield_farm_id: charlie_y_farm_id, + deposit_id, + asset_id: asset_in_position, + who: LP1, + shares_amount: amount, + position_id: omnipool_position_id, + } + .into(), + crate::Event::SharesRedeposited { + global_farm_id: bob_g_farm_id, + yield_farm_id: bob_y_farm_id, + deposit_id, + asset_id: asset_in_position, + who: LP1, + shares_amount: amount, + position_id: omnipool_position_id, + } + .into(), + ]); + + assert_eq!( + crate::OmniPositionId::::get(deposit_id).unwrap(), + omnipool_position_id + ); + + let deposit = + pallet_liquidity_mining::Deposit::::get(deposit_id).unwrap(); + let mut expected_deposit = DepositData::new(amount, KSM); + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + gc_g_farm_id, + gc_y_farm_id, + 6_500_000_000_000, + FixedU128::zero(), + 1, + 0, + )) + .unwrap(); + + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + charlie_g_farm_id, + charlie_y_farm_id, + 6_500_000_000_000, + FixedU128::zero(), + 1, + 0, + )) + .unwrap(); + + expected_deposit + .add_yield_farm_entry(YieldFarmEntry::new( + bob_g_farm_id, + bob_y_farm_id, + 6_500_000_000_000, + FixedU128::zero(), + 1, + 0, + )) + .unwrap(); + + assert_eq!(deposit, expected_deposit); + + //NFT check: lm account should be owner of the omnipool position. + let lm_account = OmnipoolMining::account_id(); + let owner: AccountId = DummyNFT::owner(&OMNIPOOL_COLLECTION_ID, &omnipool_position_id).unwrap(); + assert_eq!(owner, lm_account); + + //NFT check: lm deposit should be minted for user. + let owner: AccountId = DummyNFT::owner(&LM_COLLECTION_ID, &deposit_id).unwrap(); + assert_eq!(owner, LP1); + }); +} + +#[test] +fn add_liquidity_and_join_farms_should_fail_when_origin_is_none() { + ExtBuilder::default() + .with_endowed_accounts(vec![ + (Omnipool::protocol_account(), DAI, 1000 * ONE), + (Omnipool::protocol_account(), HDX, NATIVE_AMOUNT), + (LP1, KSM, 5000 * ONE), + (LP2, DOT, 2000 * ONE), + (GC, HDX, 100_000_000 * ONE), + (CHARLIE, HDX, 100_000_000 * ONE), + (BOB, HDX, 100_000_000 * ONE), + (ALICE, KSM, 10_000 * ONE), + (BOB, DOT, 10_000 * ONE), + ]) + .with_registered_asset(KSM) + .with_registered_asset(DOT) + .with_initial_pool(FixedU128::from_float(0.5), FixedU128::from(1)) + .with_token(KSM, FixedU128::from_float(0.65), LP1, 2000 * ONE) + .with_global_farm( + //id: 1 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + GC, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + CHARLIE, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 60_000_000 * ONE, + 2_428_000, + 1, + HDX, + BOB, + Perquintill::from_float(0.000_000_14_f64), + 1_000, + FixedU128::one(), + ) + .with_yield_farm(GC, 1, KSM, FixedU128::one(), None) //id: 4 + .with_yield_farm(CHARLIE, 2, KSM, FixedU128::one(), None) //id: 5 + .with_yield_farm(BOB, 3, KSM, FixedU128::one(), None) //id: 6 + .build() + .execute_with(|| { + let gc_g_farm_id = 1; + let gc_y_farm_id = 4; + let charlie_g_farm_id = 2; + let charlie_y_farm_id = 5; + let bob_g_farm_id = 3; + let bob_y_farm_id = 6; + let yield_farms = vec![ + (gc_g_farm_id, gc_y_farm_id), + (charlie_g_farm_id, charlie_y_farm_id), + (bob_g_farm_id, bob_y_farm_id), + ]; + + assert_noop!( + OmnipoolMining::add_liquidity_with_limit_and_join_farms( + RuntimeOrigin::none(), + yield_farms.try_into().unwrap(), + KSM, + 10 * ONE, + u128::MIN + ), + BadOrigin + ); + }); +} + +#[test] +fn join_farms_should_fail_when_no_farms_specified() { + ExtBuilder::default() + .with_endowed_accounts(vec![ + (Omnipool::protocol_account(), DAI, 1000 * ONE), + (Omnipool::protocol_account(), HDX, NATIVE_AMOUNT), + (LP1, KSM, 5000 * ONE), + (LP2, DOT, 2000 * ONE), + (GC, HDX, 100_000_000 * ONE), + (CHARLIE, HDX, 100_000_000 * ONE), + (BOB, HDX, 100_000_000 * ONE), + (ALICE, KSM, 10_000 * ONE), + (BOB, DOT, 10_000 * ONE), + ]) + .with_registered_asset(KSM) + .with_registered_asset(DOT) + .with_initial_pool(FixedU128::from_float(0.5), FixedU128::from(1)) + .with_token(KSM, FixedU128::from_float(0.65), LP1, 2000 * ONE) + .with_global_farm( + //id: 1 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + GC, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 80_000_000 * ONE, + 2_628_000, + 1, + HDX, + CHARLIE, + Perquintill::from_float(0.000_000_15_f64), + 1_000, + FixedU128::one(), + ) + .with_global_farm( + //id: 2 + 60_000_000 * ONE, + 2_428_000, + 1, + HDX, + BOB, + Perquintill::from_float(0.000_000_14_f64), + 1_000, + FixedU128::one(), + ) + .with_yield_farm(GC, 1, KSM, FixedU128::one(), None) //id: 4 + .build() + .execute_with(|| { + let farms = vec![]; + + assert_noop!( + OmnipoolMining::add_liquidity_with_limit_and_join_farms( + RuntimeOrigin::signed(LP1), + farms.try_into().unwrap(), + KSM, + 10 * ONE, + u128::MIN + ), + Error::::NoFarmEntriesSpecified + ); + }); +} diff --git a/pallets/omnipool-liquidity-mining/src/tests/mock.rs b/pallets/omnipool-liquidity-mining/src/tests/mock.rs index 0d917ad17..e326da95f 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mock.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mock.rs @@ -45,7 +45,12 @@ use sp_runtime::{ use warehouse_liquidity_mining::{GlobalFarmData, Instance1}; -use hydradx_traits::{oracle::{OraclePeriod, Source}, pools::DustRemovalAccountWhitelist, AssetKind, stableswap::StableswapAddLiquidity}; +use hydradx_traits::{ + oracle::{OraclePeriod, Source}, + pools::DustRemovalAccountWhitelist, + stableswap::StableswapAddLiquidity, + AssetKind, +}; type Block = frame_system::mocking::MockBlock; @@ -187,7 +192,11 @@ pub const STABLESWAP_POOL_ID: u32 = 72; pub struct StableswapAddLiquidityStub; impl StableswapAddLiquidity for StableswapAddLiquidityStub { - fn add_liquidity(_who: AccountId, _pool_id: AssetId, _asset_amounts: Vec>) -> Result { + fn add_liquidity( + _who: AccountId, + _pool_id: AssetId, + _asset_amounts: Vec>, + ) -> Result { Ok(SHARES_FROM_STABLESWAP) } } diff --git a/pallets/omnipool-liquidity-mining/src/tests/mod.rs b/pallets/omnipool-liquidity-mining/src/tests/mod.rs index 533f93111..416d22ee0 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mod.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mod.rs @@ -30,6 +30,8 @@ pub fn has_event(event: mock::RuntimeEvent) -> bool { } pub mod add_liquidity_and_join_farms; +pub mod add_liquidity_stableswap_omnipool_and_join_farms; +pub mod add_liquidity_with_limit_and_join_farms; pub mod claim_rewards; pub mod create_global_farm; pub mod create_yield_farm; @@ -45,7 +47,6 @@ pub mod terminate_yield_farm; pub mod update_global_farm; pub mod update_yield_farm; pub mod withdraw_shares; -pub mod add_liquidity_stableswap_omnipool_and_join_farms; pub fn expect_events(e: Vec) { test_utils::expect_events::(e); From a7f30cf179623347b2944cd3767b3f38f0d635ae Mon Sep 17 00:00:00 2001 From: dmoka Date: Tue, 26 Nov 2024 15:50:50 +0100 Subject: [PATCH 03/36] add missing doc --- pallets/omnipool-liquidity-mining/src/lib.rs | 113 ++++++++++++++++++- 1 file changed, 110 insertions(+), 3 deletions(-) diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index ae60a8915..eba3b0fdc 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -1000,6 +1000,38 @@ pub mod pallet { Ok(()) } + /// Exit from all specified yield farms then removes the linked liquidity + /// + /// This function will attempt to withdraw shares and claim rewards (if available) from all + /// specified yield farms for a given deposit. + /// + /// Parameters: + /// - `origin`: account owner of deposit(nft). + /// - `deposit_id`: id of the deposit to claim rewards for. + /// - `yield_farm_ids`: id(s) of yield farm(s) to exit from. + /// + /// Emits: + /// * `RewardClaimed` for each successful claim + /// * `SharesWithdrawn` for each successful withdrawal + /// * `DepositDestroyed` if the deposit is fully withdrawn + /// + #[pallet::call_index(16)] + #[pallet::weight(::WeightInfo::exit_farms(yield_farm_ids.len() as u32))] + pub fn exit_farms_and_remove_liquidity( + origin: OriginFor, + deposit_id: DepositId, + yield_farm_ids: BoundedVec, + ) -> DispatchResult { + for yield_farm_id in yield_farm_ids.iter() { + Self::withdraw_shares(origin.clone(), deposit_id, *yield_farm_id)?; + } + + let position_id = OmniPositionId::::get(deposit_id) + .defensive_ok_or::>(InconsistentStateError::MissingLpPosition.into())?; + + Ok(()) + } + /// This function allows user to add liquidity then use that shares to join multiple farms. /// /// Limit protection is applied. @@ -1013,7 +1045,7 @@ pub mod pallet { /// /// Emits `SharesDeposited` event for the first farm entry /// Emits `SharesRedeposited` event for each farm entry after the first one - #[pallet::call_index(16)] + #[pallet::call_index(17)] #[pallet::weight(::WeightInfo::add_liquidity_and_join_farms(farm_entries.len() as u32))] //TODO: add bench? or not needed pub fn add_liquidity_with_limit_and_join_farms( origin: OriginFor, @@ -1037,8 +1069,23 @@ pub mod pallet { Ok(()) } - /// TODO: ADD DOC - #[pallet::call_index(17)] + /// Add documentation similar we have for other extrinsics + /// This function allows user to add liquidity to stableswap pool, + /// then adding the stable shares as liquidity to omnipool + /// then use that omnipool shares to join multiple farms. + /// + /// Parameters: + /// - `origin`: owner of the omnipool position to deposit into the liquidity mining. + /// - `farm_entries`: list of farms to join. + /// - `asset`: id of the asset to be deposited into the liquidity mining. + /// - `amount`: amount of the asset to be deposited into the liquidity mining. + /// - `min_shares_limit`: The min amount of delta share asset the user should receive in the position + /// + /// Emits `LiquidityAdded` events from both pool + /// Emits `SharesDeposited` event for the first farm entry + /// Emits `SharesRedeposited` event for each farm entry after the first one + /// + #[pallet::call_index(18)] #[pallet::weight(::WeightInfo::exit_farms(farm_entries.len() as u32))] //TODO: rebenchmark pub fn add_liquidity_stableswap_omnipool_and_join_farms( origin: OriginFor, @@ -1191,4 +1238,64 @@ impl Pallet { Ok((deposit_id, lp_position)) } + + #[require_transactional] + fn do_withdraw_shares( + origin: OriginFor, + deposit_id: DepositId, + yield_farm_id: YieldFarmId, + ) -> Result { + let owner = Self::ensure_nft_owner(origin, deposit_id)?; + + //NOTE: not tested - this should never fail. + let position_id = OmniPositionId::::get(deposit_id) + .defensive_ok_or::>(InconsistentStateError::MissingLpPosition.into())?; + let lp_position = OmnipoolPallet::::load_position(position_id, Self::account_id())?; + + //NOTE: not tested - this should never fail. + let global_farm_id = T::LiquidityMiningHandler::get_global_farm_id(deposit_id, yield_farm_id) + .defensive_ok_or::>(InconsistentStateError::DepositDataNotFound.into())?; + + let (withdrawn_amount, claim_data, is_destroyed) = T::LiquidityMiningHandler::withdraw_lp_shares( + owner.clone(), + deposit_id, + global_farm_id, + yield_farm_id, + lp_position.asset_id, + )?; + + if let Some((reward_currency, claimed, _)) = claim_data { + if !claimed.is_zero() { + Self::deposit_event(Event::RewardClaimed { + global_farm_id, + yield_farm_id, + who: owner.clone(), + claimed, + reward_currency, + deposit_id, + }); + } + } + + Self::deposit_event(Event::SharesWithdrawn { + global_farm_id, + yield_farm_id, + who: owner.clone(), + amount: withdrawn_amount, + deposit_id, + }); + + if is_destroyed { + Self::unlock_lp_postion(deposit_id, &owner)?; + ::NFTHandler::burn( + &::NFTCollectionId::get(), + &deposit_id, + Some(&owner), + )?; + + Self::deposit_event(Event::DepositDestroyed { who: owner, deposit_id }); + } + + Ok(withdrawn_amount) + } } From 983816033aa8022e318e1db37da72d0c1185b167 Mon Sep 17 00:00:00 2001 From: dmoka Date: Wed, 27 Nov 2024 13:12:30 +0100 Subject: [PATCH 04/36] wip - benchmarking new wrappers --- .../src/benchmarks.rs | 781 --------------- pallets/omnipool-liquidity-mining/src/lib.rs | 7 +- pallets/stableswap/src/benchmarks.rs | 2 +- runtime/hydradx/src/assets.rs | 1 + runtime/hydradx/src/benchmarking/mod.rs | 1 + .../benchmarking/omnipool_liquidity_mining.rs | 890 ++++++++++++++++++ runtime/hydradx/src/lib.rs | 3 +- 7 files changed, 897 insertions(+), 788 deletions(-) delete mode 100644 pallets/omnipool-liquidity-mining/src/benchmarks.rs create mode 100644 runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs diff --git a/pallets/omnipool-liquidity-mining/src/benchmarks.rs b/pallets/omnipool-liquidity-mining/src/benchmarks.rs deleted file mode 100644 index 253dcf47b..000000000 --- a/pallets/omnipool-liquidity-mining/src/benchmarks.rs +++ /dev/null @@ -1,781 +0,0 @@ -// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#![cfg(feature = "runtime-benchmarks")] - -use crate::*; -use frame_benchmarking::{account, benchmarks}; -use frame_support::storage::with_transaction; -use frame_support::traits::{OnFinalize, OnInitialize}; -use frame_system::{Pallet as System, RawOrigin}; -use hydradx_traits::registry::{AssetKind, Create}; -use orml_traits::MultiCurrencyExtended; -use pallet_liquidity_mining::Instance1; -use primitives::AssetId; -use sp_runtime::TransactionOutcome; -use sp_runtime::{traits::One, FixedU128, Permill}; - -const ONE: Balance = 1_000_000_000_000; -const BTC_ONE: Balance = 100_000_000; -const HDX: AssetId = 0; -const LRNA: AssetId = 1; -const DAI: AssetId = 2; -const BSX: AssetId = 1_000_001; -const ETH: AssetId = 1_000_002; -const BTC: AssetId = 1_000_003; -const DOT: AssetId = 1_000_004; - -const G_FARM_TOTAL_REWARDS: Balance = 10_000_000 * ONE; -const REWARD_CURRENCY: AssetId = HDX; - -type CurrencyOf = ::Currency; -type OmnipoolPallet = pallet_omnipool::Pallet; - -fn fund(to: T::AccountId, currency: T::AssetId, amount: Balance) -> DispatchResult { - CurrencyOf::::deposit(currency, &to, amount) -} - -const SEED: u32 = 0; -fn create_funded_account( - name: &'static str, - index: u32, - amount: Balance, - currency: T::AssetId, -) -> T::AccountId -where - ::AssetId: From, -{ - let caller: T::AccountId = account(name, index, SEED); - - fund::(caller.clone(), currency, amount).unwrap(); - - caller -} - -fn initialize_global_farm(owner: T::AccountId) -> DispatchResult -where - ::Currency: MultiCurrencyExtended, - ::AssetId: From, - T: pallet_liquidity_mining::Config, -{ - Pallet::::create_global_farm( - RawOrigin::Root.into(), - G_FARM_TOTAL_REWARDS, - BlockNumberFor::::from(100_000_u32), - BlockNumberFor::::from(1_u32), - REWARD_CURRENCY.into(), - owner, - Perquintill::from_percent(20), - 1_000, - FixedU128::one(), - )?; - - seed_lm_pot::() -} - -fn initialize_yield_farm(owner: T::AccountId, id: GlobalFarmId, asset: T::AssetId) -> DispatchResult -where - ::AssetId: From, -{ - Pallet::::create_yield_farm(RawOrigin::Signed(owner).into(), id, asset, FixedU128::one(), None) -} - -fn initialize_omnipool() -> DispatchResult -where - ::Currency: MultiCurrencyExtended, - T: pallet_ema_oracle::Config, - T::AssetId: From, - ::AssetRegistry: Create, - <::AssetRegistry as hydradx_traits::Inspect>::AssetId: From, -{ - let stable_amount: Balance = 1_000_000_000_000_000u128; - let native_amount: Balance = 1_000_000_000_000_000u128; - let stable_price: FixedU128 = FixedU128::from((1, 2)); - let native_price: FixedU128 = FixedU128::from(1); - - let acc = OmnipoolPallet::::protocol_account(); - - ::Currency::update_balance(DAI.into(), &acc, stable_amount as i128)?; - ::Currency::update_balance(HDX.into(), &acc, native_amount as i128)?; - - fund::(acc.clone(), HDX.into(), 10_000 * ONE)?; - ::Currency::update_balance(DAI.into(), &acc, stable_amount as i128)?; - ::Currency::update_balance(T::HdxAssetId::get(), &acc, native_amount as i128)?; - - OmnipoolPallet::::add_token( - RawOrigin::Root.into(), - HDX.into(), - native_price, - Permill::from_percent(100), - acc.clone(), - )?; - OmnipoolPallet::::add_token( - RawOrigin::Root.into(), - DAI.into(), - stable_price, - Permill::from_percent(100), - acc.clone(), - )?; - - let name = b"BSX".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; - // Register new asset in asset registry - with_transaction(|| { - TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( - None, - Some(name), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )) - })?; - let name = b"ETH".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; - with_transaction(|| { - TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( - None, - Some(name), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )) - })?; - let name = b"BTC".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; - with_transaction(|| { - TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( - None, - Some(name), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )) - })?; - - let name = b"DOT".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; - with_transaction(|| { - TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( - None, - Some(name), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )) - })?; - - // Create account for token provider and set balance - let owner: T::AccountId = account("owner", 0, 1); - - let token_price = FixedU128::from((1, 5)); - let token_amount = 200_000_000_000_000u128; - - ::Currency::update_balance(BSX.into(), &acc, token_amount as i128)?; - ::Currency::update_balance(ETH.into(), &acc, token_amount as i128)?; - ::Currency::update_balance(BTC.into(), &acc, token_amount as i128)?; - ::Currency::update_balance(DOT.into(), &acc, token_amount as i128)?; - - // Add the token to the pool - OmnipoolPallet::::add_token( - RawOrigin::Root.into(), - BSX.into(), - token_price, - Permill::from_percent(100), - owner.clone(), - )?; - - OmnipoolPallet::::add_token( - RawOrigin::Root.into(), - ETH.into(), - token_price, - Permill::from_percent(100), - owner.clone(), - )?; - - OmnipoolPallet::::add_token( - RawOrigin::Root.into(), - BTC.into(), - token_price, - Permill::from_percent(100), - owner.clone(), - )?; - - OmnipoolPallet::::add_token( - RawOrigin::Root.into(), - DOT.into(), - token_price, - Permill::from_percent(100), - owner, - )?; - - //NOTE: This is necessary for oracle to provide price. - set_period::(10); - - do_lrna_hdx_trade::() -} - -//NOTE: This is necessary for oracle to provide price. -fn do_lrna_hdx_trade() -> DispatchResult -where - ::Currency: MultiCurrencyExtended, - T::AssetId: From, -{ - let trader = create_funded_account::("tmp_trader", 0, 100 * ONE, REWARD_CURRENCY.into()); - - fund::(trader.clone(), LRNA.into(), 100 * ONE)?; - - OmnipoolPallet::::sell(RawOrigin::Signed(trader).into(), LRNA.into(), HDX.into(), ONE, 0) -} - -fn seed_lm_pot() -> DispatchResult -where - ::AssetId: From, - T: pallet_liquidity_mining::Config, -{ - let pot = pallet_liquidity_mining::Pallet::::pot_account_id().unwrap(); - - fund::(pot, HDX.into(), 100 * ONE) -} - -fn omnipool_add_liquidity( - lp: T::AccountId, - asset: T::AssetId, - amount: Balance, -) -> Result { - let current_position_id = OmnipoolPallet::::next_position_id(); - - OmnipoolPallet::::add_liquidity(RawOrigin::Signed(lp).into(), asset, amount)?; - - Ok(current_position_id) -} - -fn lm_deposit_shares( - who: T::AccountId, - g_id: GlobalFarmId, - y_id: YieldFarmId, - position_id: T::PositionItemId, -) -> DispatchResult { - crate::Pallet::::deposit_shares(RawOrigin::Signed(who).into(), g_id, y_id, position_id) -} - -fn set_period(to: u32) -where - T: pallet_ema_oracle::Config, -{ - //NOTE: predefined global farm has period size = 1 block. - - while System::::block_number() < to.into() { - let b = System::::block_number(); - - System::::on_finalize(b); - pallet_ema_oracle::Pallet::::on_finalize(b); - - System::::on_initialize(b + 1_u32.into()); - pallet_ema_oracle::Pallet::::on_initialize(b + 1_u32.into()); - - System::::set_block_number(b + 1_u32.into()); - } -} - -benchmarks! { - where_clause { where - ::AssetId: From, - ::Currency: MultiCurrencyExtended, - T: crate::pallet::Config + pallet_ema_oracle::Config + pallet_liquidity_mining::Config, - ::AssetRegistry: Create::AssetId>, - } - - create_global_farm { - let planned_yielding_periods = BlockNumberFor::::from(100_000_u32); - let blocks_per_period = BlockNumberFor::::from(100_u32); - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let yield_per_period = Perquintill::from_percent(20); - let min_deposit = 1_000; - let price_adjustment = FixedU128::from(10_u128); - - }: _(RawOrigin::Root, G_FARM_TOTAL_REWARDS, planned_yielding_periods, blocks_per_period, REWARD_CURRENCY.into(), owner, yield_per_period, min_deposit, FixedU128::one()) - - update_global_farm { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let global_farm_id = 1; - let yield_farm_id = 2; - - initialize_omnipool::()?; - - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner.clone(), global_farm_id, BTC.into())?; - - let planned_yielding_periods = BlockNumberFor::::from(100_000_u32); - let yield_per_period = Perquintill::from_percent(20); - let min_deposit = 1_000; - - }: _(RawOrigin::Root, global_farm_id, planned_yielding_periods, yield_per_period, min_deposit) - - - terminate_global_farm { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let global_farm_id = 1; - let yield_farm_id = 2; - - initialize_omnipool::()?; - - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner.clone(), global_farm_id, BTC.into())?; - - let lp = create_funded_account::("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let position_id = omnipool_add_liquidity::(lp.clone(), BTC.into(), 10 * BTC_ONE)?; - - set_period::(100); - lm_deposit_shares::(lp, global_farm_id, yield_farm_id, position_id)?; - - crate::Pallet::::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, BTC.into())?; - crate::Pallet::::terminate_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, yield_farm_id, BTC.into())?; - - set_period::(200); - }: _(RawOrigin::Signed(owner), global_farm_id) - - - create_yield_farm { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let global_farm_id = 1; - - initialize_omnipool::()?; - - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner.clone(), global_farm_id, BTC.into())?; - - let lp = create_funded_account::("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let position_id = omnipool_add_liquidity::(lp.clone(), BTC.into(), 10 * BTC_ONE)?; - - set_period::(100); - lm_deposit_shares::(lp, global_farm_id, 2, position_id)?; - - set_period::(200); - }: _(RawOrigin::Signed(owner), global_farm_id, ETH.into(), FixedU128::one(), Some(LoyaltyCurve::default())) - - - update_yield_farm { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let global_farm_id = 1; - let yield_farm_id = 2; - - initialize_omnipool::()?; - - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner.clone(), global_farm_id, BTC.into())?; - - let lp = create_funded_account::("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let position_id = omnipool_add_liquidity::(lp.clone(), BTC.into(), 10 * BTC_ONE)?; - - lm_deposit_shares::(lp, global_farm_id, yield_farm_id, position_id)?; - - set_period::(200); - }: _(RawOrigin::Signed(owner), global_farm_id, BTC.into(), FixedU128::from(2_u128)) - - stop_yield_farm { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let global_farm_id = 1; - let yield_farm_id = 2; - - initialize_omnipool::()?; - - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner.clone(), global_farm_id, BTC.into())?; - - let lp = create_funded_account::("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let position_id = omnipool_add_liquidity::(lp.clone(), BTC.into(), 10 * BTC_ONE)?; - - lm_deposit_shares::(lp, global_farm_id, yield_farm_id, position_id)?; - - set_period::(200); - }: _(RawOrigin::Signed(owner), global_farm_id, BTC.into()) - - resume_yield_farm { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let global_farm_id = 1; - let eth_farm_id = 2; - let btc_farm_id = 3; - - initialize_omnipool::()?; - - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner.clone(), global_farm_id, ETH.into())?; - initialize_yield_farm::(owner.clone(), global_farm_id, BTC.into())?; - - let lp = create_funded_account::("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let position_id = omnipool_add_liquidity::(lp.clone(), BTC.into(), 10 * BTC_ONE)?; - - crate::Pallet::::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, ETH.into())?; - - set_period::(200); - - lm_deposit_shares::(lp, global_farm_id, btc_farm_id, position_id)?; - - set_period::(400); - }: _(RawOrigin::Signed(owner), global_farm_id, eth_farm_id, ETH.into(), FixedU128::from(2)) - - terminate_yield_farm { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let global_farm_id = 1; - let yield_farm_id = 2; - - initialize_omnipool::()?; - - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner.clone(), global_farm_id, BTC.into())?; - - let lp = create_funded_account::("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let position_id = omnipool_add_liquidity::(lp.clone(), BTC.into(), 10 * BTC_ONE)?; - - lm_deposit_shares::(lp, global_farm_id, yield_farm_id, position_id)?; - - set_period::(200); - - crate::Pallet::::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, BTC.into())?; - - set_period::(300); - }: _(RawOrigin::Signed(owner), global_farm_id, yield_farm_id, BTC.into()) - - deposit_shares { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let global_farm_id = 1; - let yield_farm_id = 2; - - initialize_omnipool::()?; - - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner, global_farm_id, BTC.into())?; - - let lp1 = create_funded_account::("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity::(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; - - lm_deposit_shares::(lp1, global_farm_id, yield_farm_id, lp1_position_id)?; - - let lp2 = create_funded_account::("lp_2", 1, 10 * BTC_ONE, BTC.into()); - let lp2_position_id = omnipool_add_liquidity::(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; - set_period::(200); - - - }: _(RawOrigin::Signed(lp2), global_farm_id, yield_farm_id, lp2_position_id) - - - redeposit_shares { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account::("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account::("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account::("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account::("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - - let deposit_id = 1; - - initialize_omnipool::()?; - - //gId: 1, yId: 2 - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner, 1, BTC.into())?; - - //gId: 3, yId: 4 - initialize_global_farm::(owner2.clone())?; - initialize_yield_farm::(owner2, 3, BTC.into())?; - - //gId: 5, yId: 6 - initialize_global_farm::(owner3.clone())?; - initialize_yield_farm::(owner3, 5, BTC.into())?; - - //gId: 7, yId: 8 - initialize_global_farm::(owner4.clone())?; - initialize_yield_farm::(owner4, 7, BTC.into())?; - - //gId: 9, yId: 10 - initialize_global_farm::(owner5.clone())?; - initialize_yield_farm::(owner5, 9, BTC.into())?; - - let lp1 = create_funded_account::("lp_1", 5, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity::(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; - - let lp2 = create_funded_account::("lp_2", 6, 1_000 * ONE, BTC.into()); - let lp2_position_id = omnipool_add_liquidity::(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; - - set_period::(200); - - lm_deposit_shares::(lp1.clone(), 1, 2, lp1_position_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 3, 4, deposit_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 5, 6, deposit_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 7, 8, deposit_id)?; - - //Deposit into the global-farm so it will be updated - lm_deposit_shares::(lp2, 9, 10, lp2_position_id)?; - - set_period::(400); - }: _(RawOrigin::Signed(lp1), 9, 10, deposit_id) - - claim_rewards { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account::("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account::("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account::("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account::("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - - let deposit_id = 1; - - initialize_omnipool::()?; - - //gId: 1, yId: 2 - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner, 1, BTC.into())?; - - //gId: 3, yId: 4 - initialize_global_farm::(owner2.clone())?; - initialize_yield_farm::(owner2, 3, BTC.into())?; - - //gId: 5, yId: 6 - initialize_global_farm::(owner3.clone())?; - initialize_yield_farm::(owner3, 5, BTC.into())?; - - //gId: 7, yId: 8 - initialize_global_farm::(owner4.clone())?; - initialize_yield_farm::(owner4, 7, BTC.into())?; - - //gId: 9, yId: 10 - initialize_global_farm::(owner5.clone())?; - initialize_yield_farm::(owner5, 9, BTC.into())?; - - let lp1 = create_funded_account::("lp_1", 5, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity::(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; - - //NOTE: This is necessary because paid rewards are lower than ED. - fund::(lp1.clone(), REWARD_CURRENCY.into(), 100 * ONE)?; - - set_period::(200); - - lm_deposit_shares::(lp1.clone(), 1, 2, lp1_position_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 3, 4, deposit_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 5, 6, deposit_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 7, 8, deposit_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 9, 10, deposit_id)?; - - set_period::(400); - - }: { - //We fire and forget as claim rewards is disabled - let _ = crate::Pallet::::claim_rewards(RawOrigin::Signed(lp1).into(), deposit_id, 10); - } verify { - - } - - withdraw_shares { - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - - let global_farm_id = 1; - let yield_farm_id = 2; - let deposit_id = 1; - - initialize_omnipool::()?; - - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner, global_farm_id, BTC.into())?; - - let lp1 = create_funded_account::("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity::(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; - - //NOTE: This is necessary because paid rewards are lower than ED. - fund::(lp1.clone(), REWARD_CURRENCY.into(), 100 * ONE)?; - - set_period::(200); - - lm_deposit_shares::(lp1.clone(), 1, 2, lp1_position_id)?; - set_period::(400); - }: _(RawOrigin::Signed(lp1), deposit_id, yield_farm_id) - - join_farms { - let c in 1..get_max_entries::(); - - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account::("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account::("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account::("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account::("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - - let deposit_id = 1; - - initialize_omnipool::()?; - - //gId: 1, yId: 2 - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner, 1, BTC.into())?; - let lp1 = create_funded_account::("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity::(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; - lm_deposit_shares::(lp1, 1, 2, lp1_position_id)?; - - //gId: 3, yId: 4 - initialize_global_farm::(owner2.clone())?; - initialize_yield_farm::(owner2, 3, BTC.into())?; - let lp2 = create_funded_account::("lp_2", 1, 10 * BTC_ONE, BTC.into()); - let lp2_position_id = omnipool_add_liquidity::(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; - lm_deposit_shares::(lp2, 3, 4, lp2_position_id)?; - - //gId: 5, yId: 6 - initialize_global_farm::(owner3.clone())?; - initialize_yield_farm::(owner3, 5, BTC.into())?; - let lp3 = create_funded_account::("lp_3", 1, 10 * BTC_ONE, BTC.into()); - let lp3_position_id = omnipool_add_liquidity::(lp3.clone(), BTC.into(), 10 * BTC_ONE)?; - lm_deposit_shares::(lp3, 5, 6, lp3_position_id)?; - - //gId: 7, yId: 8 - initialize_global_farm::(owner4.clone())?; - initialize_yield_farm::(owner4, 7, BTC.into())?; - let lp4 = create_funded_account::("lp_4", 1, 10 * BTC_ONE, BTC.into()); - let lp4_position_id = omnipool_add_liquidity::(lp4.clone(), BTC.into(), 10 * BTC_ONE)?; - lm_deposit_shares::(lp4, 7, 8, lp4_position_id)?; - - //gId: 9, yId: 10 - initialize_global_farm::(owner5.clone())?; - initialize_yield_farm::(owner5, 9, BTC.into())?; - let lp5 = create_funded_account::("lp_5", 1, 10 * BTC_ONE, BTC.into()); - let lp5_position_id = omnipool_add_liquidity::(lp5.clone(), BTC.into(), 10 * BTC_ONE)?; - lm_deposit_shares::(lp5, 9, 10, lp5_position_id)?; - - let lp6 = create_funded_account::("lp_6", 5, 10 * BTC_ONE, BTC.into()); - let lp6_position_id = omnipool_add_liquidity::(lp6.clone(), BTC.into(), 10 * BTC_ONE)?; - - set_period::(200); - let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; - let farms = farms_entries[0..c as usize].to_vec(); - - }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), lp6_position_id) - - add_liquidity_and_join_farms { - let c in 1..get_max_entries::(); - - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account::("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account::("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account::("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account::("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - - let deposit_id = 1; - - initialize_omnipool::()?; - - //gId: 1, yId: 2 - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner, 1, BTC.into())?; - let lp1 = create_funded_account::("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity::(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; - lm_deposit_shares::(lp1, 1, 2, lp1_position_id)?; - - //gId: 3, yId: 4 - initialize_global_farm::(owner2.clone())?; - initialize_yield_farm::(owner2, 3, BTC.into())?; - let lp2 = create_funded_account::("lp_2", 1, 10 * BTC_ONE, BTC.into()); - let lp2_position_id = omnipool_add_liquidity::(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; - lm_deposit_shares::(lp2, 3, 4, lp2_position_id)?; - - //gId: 5, yId: 6 - initialize_global_farm::(owner3.clone())?; - initialize_yield_farm::(owner3, 5, BTC.into())?; - let lp3 = create_funded_account::("lp_3", 1, 10 * BTC_ONE, BTC.into()); - let lp3_position_id = omnipool_add_liquidity::(lp3.clone(), BTC.into(), 10 * BTC_ONE)?; - lm_deposit_shares::(lp3, 5, 6, lp3_position_id)?; - - //gId: 7, yId: 8 - initialize_global_farm::(owner4.clone())?; - initialize_yield_farm::(owner4, 7, BTC.into())?; - let lp4 = create_funded_account::("lp_4", 1, 10 * BTC_ONE, BTC.into()); - let lp4_position_id = omnipool_add_liquidity::(lp4.clone(), BTC.into(), 10 * BTC_ONE)?; - lm_deposit_shares::(lp4, 7, 8, lp4_position_id)?; - - //gId: 9, yId: 10 - initialize_global_farm::(owner5.clone())?; - initialize_yield_farm::(owner5, 9, BTC.into())?; - let lp5 = create_funded_account::("lp_5", 1, 10 * BTC_ONE, BTC.into()); - let lp5_position_id = omnipool_add_liquidity::(lp5.clone(), BTC.into(), 10 * BTC_ONE)?; - lm_deposit_shares::(lp5, 9, 10, lp5_position_id)?; - - let lp6 = create_funded_account::("lp_6", 5, 10 * BTC_ONE, BTC.into()); - - set_period::(200); - let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; - let farms = farms_entries[0..c as usize].to_vec(); - - }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), BTC.into(), 10 * BTC_ONE) - - exit_farms { - let c in 1..get_max_entries::(); - - let owner = create_funded_account::("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account::("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account::("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account::("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account::("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - - let deposit_id = 1; - - initialize_omnipool::()?; - - //gId: 1, yId: 2 - initialize_global_farm::(owner.clone())?; - initialize_yield_farm::(owner, 1, BTC.into())?; - - //gId: 3, yId: 4 - initialize_global_farm::(owner2.clone())?; - initialize_yield_farm::(owner2, 3, BTC.into())?; - - //gId: 5, yId: 6 - initialize_global_farm::(owner3.clone())?; - initialize_yield_farm::(owner3, 5, BTC.into())?; - - //gId: 7, yId: 8 - initialize_global_farm::(owner4.clone())?; - initialize_yield_farm::(owner4, 7, BTC.into())?; - - //gId: 9, yId: 10 - initialize_global_farm::(owner5.clone())?; - initialize_yield_farm::(owner5, 9, BTC.into())?; - - let lp1 = create_funded_account::("lp_1", 5, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity::(lp1.clone(), BTC.into(), BTC_ONE)?; - - set_period::(200); - - lm_deposit_shares::(lp1.clone(), 1, 2, lp1_position_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 3, 4, deposit_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 5, 6, deposit_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 7, 8, deposit_id)?; - crate::Pallet::::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 9, 10, deposit_id)?; - - let deposit_id = 1; - let farm_entries = [2,4,6,8,10]; - let farms = farm_entries[0..c as usize].to_vec(); - - set_period::(250); - }: _(RawOrigin::Signed(lp1),deposit_id, farms.try_into().unwrap()) - - - - impl_benchmark_test_suite!(Pallet, crate::tests::mock::ExtBuilder::default().build(), crate::tests::mock::Test); -} - -fn get_max_entries() -> u32 { - T::MaxFarmEntriesPerDeposit::get() -} diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index eba3b0fdc..6b2fbc759 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -34,9 +34,6 @@ #![cfg_attr(not(feature = "std"), no_std)] -#[cfg(any(feature = "runtime-benchmarks", test))] -mod benchmarks; - #[cfg(test)] mod tests; @@ -1046,7 +1043,7 @@ pub mod pallet { /// Emits `SharesDeposited` event for the first farm entry /// Emits `SharesRedeposited` event for each farm entry after the first one #[pallet::call_index(17)] - #[pallet::weight(::WeightInfo::add_liquidity_and_join_farms(farm_entries.len() as u32))] //TODO: add bench? or not needed + #[pallet::weight(::WeightInfo::add_liquidity_and_join_farms(farm_entries.len() as u32))]//Same benchmark as add_liquidity_and_join_farms since it's the same logic pub fn add_liquidity_with_limit_and_join_farms( origin: OriginFor, farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, @@ -1073,7 +1070,7 @@ pub mod pallet { /// This function allows user to add liquidity to stableswap pool, /// then adding the stable shares as liquidity to omnipool /// then use that omnipool shares to join multiple farms. - /// + /// /// Parameters: /// - `origin`: owner of the omnipool position to deposit into the liquidity mining. /// - `farm_entries`: list of farms to join. diff --git a/pallets/stableswap/src/benchmarks.rs b/pallets/stableswap/src/benchmarks.rs index 8ba3aa8de..c4145c7e3 100644 --- a/pallets/stableswap/src/benchmarks.rs +++ b/pallets/stableswap/src/benchmarks.rs @@ -19,7 +19,7 @@ use super::*; -use crate::types::AssetAmount; +use hydradx_traits::stableswap::AssetAmount; use frame_benchmarking::account; use frame_benchmarking::benchmarks; use frame_support::traits::EnsureOrigin; diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 2da446109..d10ae8c12 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -58,6 +58,7 @@ use frame_support::{ }, BoundedVec, PalletId, }; +use crate::Stableswap; use frame_system::{EnsureRoot, EnsureSigned, RawOrigin}; use hydradx_traits::AMM; use orml_traits::{ diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index 77510776f..a2a90fe86 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -11,6 +11,7 @@ pub mod tokens; pub mod vesting; pub mod xyk; pub mod xyk_liquidity_mining; +pub mod omnipool_liquidity_mining; use crate::{AssetLocation, AssetRegistry, EmaOracle, MultiTransactionPayment, Runtime, System, DOT_ASSET_LOCATION}; use frame_benchmarking::BenchmarkError; diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs new file mode 100644 index 000000000..984ed28b0 --- /dev/null +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -0,0 +1,890 @@ +// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![cfg(feature = "runtime-benchmarks")] + +use crate::*; +use frame_benchmarking::{account, BenchmarkError, benchmarks}; +use frame_support::assert_ok; +use frame_support::storage::with_transaction; +use frame_support::traits::{OnFinalize, OnInitialize}; +use frame_system::{RawOrigin}; +use frame_system::pallet_prelude::BlockNumberFor; +use orml_benchmarking::runtime_benchmarks; +use hydradx_traits::registry::{AssetKind, Create}; +use orml_traits::MultiCurrencyExtended; +use primitives::AssetId; +use sp_runtime::{DispatchError, DispatchResult, Perquintill, TransactionOutcome}; +use sp_runtime::{traits::One, FixedU128, Permill}; +use hydradx_traits::liquidity_mining::{GlobalFarmId, YieldFarmId}; +use hydradx_traits::stableswap::AssetAmount; +use warehouse_liquidity_mining::LoyaltyCurve; +use crate::benchmarking::{register_asset, register_external_asset}; +const ONE: Balance = 1_000_000_000_000; +const BTC_ONE: Balance = 100_000_000; +const HDX: AssetId = 0; +const LRNA: AssetId = 1; +const DAI: AssetId = 2; +const BSX: AssetId = 1_000_001; +const ETH: AssetId = 1_000_002; +const BTC: AssetId = 1_000_003; +const DOT: AssetId = 1_000_004; + +const G_FARM_TOTAL_REWARDS: Balance = 10_000_000 * ONE; +const REWARD_CURRENCY: AssetId = HDX; + +pub const MAX_ASSETS_IN_POOL: u32 = 5; + + +fn fund(to: AccountId, currency: AssetId, amount: Balance) -> DispatchResult { + Currencies::deposit(currency, &to, amount) +} + +const SEED: u32 = 0; +pub const INITIAL_BALANCE: Balance = 10_000_000 * crate::benchmarking::xyk_liquidity_mining::ONE; + +//TODO: this is use in many places, refactor +fn funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> AccountId { + let account: AccountId = account(name, index, 0); + //Necessary to pay ED in insufficient asset + >::update_balance(0, &account, INITIAL_BALANCE as i128).unwrap(); + for asset in assets { + assert_ok!(>::update_balance( + *asset, + &account, + INITIAL_BALANCE.try_into().unwrap(), + )); + } + account +} + +fn initialize_global_farm(owner: AccountId) -> DispatchResult +{ + OmnipoolLiquidityMining::create_global_farm( + RawOrigin::Root.into(), + G_FARM_TOTAL_REWARDS, + BlockNumberFor::::from(100_000_u32), + BlockNumberFor::::from(1_u32), + REWARD_CURRENCY.into(), + owner, + Perquintill::from_percent(20), + 1_000, + FixedU128::one(), + )?; + + seed_lm_pot() +} + +fn initialize_yield_farm(owner: AccountId, id: GlobalFarmId, asset: AssetId) -> DispatchResult +{ + OmnipoolLiquidityMining::create_yield_farm(RawOrigin::Signed(owner).into(), id, asset, FixedU128::one(), None) +} + +fn initialize_omnipool() -> DispatchResult +{ + let stable_amount: Balance = 1_000_000_000_000_000u128; + let native_amount: Balance = 1_000_000_000_000_000u128; + let stable_price: FixedU128 = FixedU128::from((1, 2)); + let native_price: FixedU128 = FixedU128::from(1); + + let acc = Omnipool::protocol_account(); + + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DAI.into(), stable_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), HDX.into(), native_amount as Amount)?; + + fund(acc.clone(), HDX.into(), 10_000 * ONE)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DAI.into(), stable_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), HDX.into(), native_amount as Amount)?; + + Omnipool::add_token( + RawOrigin::Root.into(), + HDX.into(), + native_price, + Permill::from_percent(100), + acc.clone(), + )?; + Omnipool::add_token( + RawOrigin::Root.into(), + DAI.into(), + stable_price, + Permill::from_percent(100), + acc.clone(), + )?; + + let name = b"BSX".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + // Register new asset in asset registry + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + None, + Some(name), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + let name = b"ETH".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + None, + Some(name), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + let name = b"BTC".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + None, + Some(name), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + + let name = b"DOT".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + None, + Some(name), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + + // Create account for token provider and set balance + let owner: AccountId = account("owner", 0, 1); + + let token_price = FixedU128::from((1, 5)); + let token_amount = 200_000_000_000_000u128; + + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), BSX.into(), token_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), ETH.into(), token_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), BTC.into(), token_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DOT.into(), token_amount as Amount)?; + + // Add the token to the pool + Omnipool::add_token( + RawOrigin::Root.into(), + BSX.into(), + token_price, + Permill::from_percent(100), + owner.clone(), + )?; + + Omnipool::add_token( + RawOrigin::Root.into(), + ETH.into(), + token_price, + Permill::from_percent(100), + owner.clone(), + )?; + + Omnipool::add_token( + RawOrigin::Root.into(), + BTC.into(), + token_price, + Permill::from_percent(100), + owner.clone(), + )?; + + Omnipool::add_token( + RawOrigin::Root.into(), + DOT.into(), + token_price, + Permill::from_percent(100), + owner, + )?; + + //NOTE: This is necessary for oracle to provide price. + set_period(10); + + do_lrna_hdx_trade() +} + +//NOTE: This is necessary for oracle to provide price. +fn do_lrna_hdx_trade() -> DispatchResult +{ + let trader = funded_account("tmp_trader", 0, &vec![REWARD_CURRENCY.into()]); + + fund(trader.clone(), LRNA.into(), 100 * ONE)?; + + Omnipool::sell(RawOrigin::Signed(trader).into(), LRNA.into(), HDX.into(), ONE, 0) +} + +fn seed_lm_pot() -> DispatchResult +{ + let pot = XYKWarehouseLM::pot_account_id().unwrap(); + + fund(pot, HDX.into(), 100 * ONE) +} + +fn omnipool_add_liquidity( + lp: AccountId, + asset: AssetId, + amount: Balance, +) -> Result { + let current_position_id = Omnipool::next_position_id(); + + Omnipool::add_liquidity(RawOrigin::Signed(lp).into(), asset, amount)?; + + Ok(current_position_id) +} + +fn lm_deposit_shares( + who: AccountId, + g_id: GlobalFarmId, + y_id: YieldFarmId, + position_id: ItemId, +) -> DispatchResult { + OmnipoolLiquidityMining::deposit_shares(RawOrigin::Signed(who).into(), g_id, y_id, position_id) +} + +fn set_period(to: u32) +{ + //NOTE: predefined global farm has period size = 1 block. + while System::block_number() < to { + let b = System::block_number(); + + as OnFinalize>>::on_finalize(b); + as frame_support::traits::OnFinalize>>::on_finalize(b); + + as OnInitialize>>::on_initialize(b + 1_u32); + as frame_support::traits::OnInitialize>>::on_initialize(b + 1_u32); + + System::set_block_number(b + 1_u32); + } +} + +runtime_benchmarks! { + {Runtime, pallet_omnipool_liquidity_mining } + + create_global_farm { + let planned_yielding_periods = BlockNumberFor::::from(100_000_u32); + let blocks_per_period = BlockNumberFor::::from(100_u32); + let reward_currency = register_asset(b"REW".to_vec(), 10000 * ONE).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let owner = funded_account("owner", 0, &[reward_currency.into()]); + let yield_per_period = Perquintill::from_percent(20); + let min_deposit = 1_000; + let price_adjustment = FixedU128::from(10_u128); + + }: _(RawOrigin::Root, G_FARM_TOTAL_REWARDS, planned_yielding_periods, blocks_per_period, reward_currency.into(), owner, yield_per_period, min_deposit, FixedU128::one()) + + update_global_farm { + let owner = funded_account("owner", 0, &[REWARD_CURRENCY.into()]); + let global_farm_id = 1; + let yield_farm_id = 2; + + initialize_omnipool()?; + + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + + let planned_yielding_periods = BlockNumberFor::::from(100_000_u32); + let yield_per_period = Perquintill::from_percent(20); + let min_deposit = 1_000; + + }: _(RawOrigin::Root, global_farm_id, planned_yielding_periods, yield_per_period, min_deposit) + +/* + terminate_global_farm { + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let global_farm_id = 1; + let yield_farm_id = 2; + + initialize_omnipool()?; + + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + + let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + + set_period(100); + lm_deposit_shares(lp, global_farm_id, yield_farm_id, position_id)?; + + OmnipoolLiquidityMining::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, BTC.into())?; + OmnipoolLiquidityMining::terminate_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, yield_farm_id, BTC.into())?; + + set_period(200); + }: _(RawOrigin::Signed(owner), global_farm_id) + + + create_yield_farm { + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let global_farm_id = 1; + + initialize_omnipool()?; + + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + + let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + + set_period(100); + lm_deposit_shares(lp, global_farm_id, 2, position_id)?; + + set_period(200); + }: _(RawOrigin::Signed(owner), global_farm_id, ETH.into(), FixedU128::one(), Some(LoyaltyCurve::default())) + + + update_yield_farm { + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let global_farm_id = 1; + let yield_farm_id = 2; + + initialize_omnipool()?; + + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + + let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + + lm_deposit_shares(lp, global_farm_id, yield_farm_id, position_id)?; + + set_period(200); + }: _(RawOrigin::Signed(owner), global_farm_id, BTC.into(), FixedU128::from(2_u128)) + + stop_yield_farm { + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let global_farm_id = 1; + let yield_farm_id = 2; + + initialize_omnipool()?; + + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + + let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + + lm_deposit_shares(lp, global_farm_id, yield_farm_id, position_id)?; + + set_period(200); + }: _(RawOrigin::Signed(owner), global_farm_id, BTC.into()) + + resume_yield_farm { + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let global_farm_id = 1; + let eth_farm_id = 2; + let btc_farm_id = 3; + + initialize_omnipool()?; + + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner.clone(), global_farm_id, ETH.into())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + + let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + + OmnipoolLiquidityMining::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, ETH.into())?; + + set_period(200); + + lm_deposit_shares(lp, global_farm_id, btc_farm_id, position_id)?; + + set_period(400); + }: _(RawOrigin::Signed(owner), global_farm_id, eth_farm_id, ETH.into(), FixedU128::from(2)) + + terminate_yield_farm { + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let global_farm_id = 1; + let yield_farm_id = 2; + + initialize_omnipool()?; + + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + + let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + + lm_deposit_shares(lp, global_farm_id, yield_farm_id, position_id)?; + + set_period(200); + + OmnipoolLiquidityMining::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, BTC.into())?; + + set_period(300); + }: _(RawOrigin::Signed(owner), global_farm_id, yield_farm_id, BTC.into()) + + deposit_shares { + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let global_farm_id = 1; + let yield_farm_id = 2; + + initialize_omnipool()?; + + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner, global_farm_id, BTC.into())?; + + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + + lm_deposit_shares(lp1, global_farm_id, yield_farm_id, lp1_position_id)?; + + let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC.into()); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; + set_period(200); + + + }: _(RawOrigin::Signed(lp2), global_farm_id, yield_farm_id, lp2_position_id) + + + redeposit_shares { + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + + let deposit_id = 1; + + initialize_omnipool()?; + + //gId: 1, yId: 2 + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner, 1, BTC.into())?; + + //gId: 3, yId: 4 + initialize_global_farm(owner2.clone())?; + initialize_yield_farm(owner2, 3, BTC.into())?; + + //gId: 5, yId: 6 + initialize_global_farm(owner3.clone())?; + initialize_yield_farm(owner3, 5, BTC.into())?; + + //gId: 7, yId: 8 + initialize_global_farm(owner4.clone())?; + initialize_yield_farm(owner4, 7, BTC.into())?; + + //gId: 9, yId: 10 + initialize_global_farm(owner5.clone())?; + initialize_yield_farm(owner5, 9, BTC.into())?; + + let lp1 = create_funded_account("lp_1", 5, 10 * BTC_ONE, BTC.into()); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + + let lp2 = create_funded_account("lp_2", 6, 1_000 * ONE, BTC.into()); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; + + set_period(200); + + lm_deposit_shares(lp1.clone(), 1, 2, lp1_position_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 3, 4, deposit_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 5, 6, deposit_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 7, 8, deposit_id)?; + + //Deposit into the global-farm so it will be updated + lm_deposit_shares(lp2, 9, 10, lp2_position_id)?; + + set_period(400); + }: _(RawOrigin::Signed(lp1), 9, 10, deposit_id) + + claim_rewards { + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + + let deposit_id = 1; + + initialize_omnipool()?; + + //gId: 1, yId: 2 + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner, 1, BTC.into())?; + + //gId: 3, yId: 4 + initialize_global_farm(owner2.clone())?; + initialize_yield_farm(owner2, 3, BTC.into())?; + + //gId: 5, yId: 6 + initialize_global_farm(owner3.clone())?; + initialize_yield_farm(owner3, 5, BTC.into())?; + + //gId: 7, yId: 8 + initialize_global_farm(owner4.clone())?; + initialize_yield_farm(owner4, 7, BTC.into())?; + + //gId: 9, yId: 10 + initialize_global_farm(owner5.clone())?; + initialize_yield_farm(owner5, 9, BTC.into())?; + + let lp1 = create_funded_account("lp_1", 5, 10 * BTC_ONE, BTC.into()); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + + //NOTE: This is necessary because paid rewards are lower than ED. + fund(lp1.clone(), REWARD_CURRENCY.into(), 100 * ONE)?; + + set_period(200); + + lm_deposit_shares(lp1.clone(), 1, 2, lp1_position_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 3, 4, deposit_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 5, 6, deposit_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 7, 8, deposit_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 9, 10, deposit_id)?; + + set_period(400); + + }: { + //We fire and forget as claim rewards is disabled + let _ = OmnipoolLiquidityMining::claim_rewards(RawOrigin::Signed(lp1).into(), deposit_id, 10); + } verify { + + } + + withdraw_shares { + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + + let global_farm_id = 1; + let yield_farm_id = 2; + let deposit_id = 1; + + initialize_omnipool()?; + + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner, global_farm_id, BTC.into())?; + + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + + //NOTE: This is necessary because paid rewards are lower than ED. + fund(lp1.clone(), REWARD_CURRENCY.into(), 100 * ONE)?; + + set_period(200); + + lm_deposit_shares(lp1.clone(), 1, 2, lp1_position_id)?; + set_period(400); + }: _(RawOrigin::Signed(lp1), deposit_id, yield_farm_id) + + join_farms { + let c in 1..get_max_entries(); + + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + + let deposit_id = 1; + + initialize_omnipool()?; + + //gId: 1, yId: 2 + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner, 1, BTC.into())?; + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + lm_deposit_shares(lp1, 1, 2, lp1_position_id)?; + + //gId: 3, yId: 4 + initialize_global_farm(owner2.clone())?; + initialize_yield_farm(owner2, 3, BTC.into())?; + let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC.into()); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; + lm_deposit_shares(lp2, 3, 4, lp2_position_id)?; + + //gId: 5, yId: 6 + initialize_global_farm(owner3.clone())?; + initialize_yield_farm(owner3, 5, BTC.into())?; + let lp3 = create_funded_account("lp_3", 1, 10 * BTC_ONE, BTC.into()); + let lp3_position_id = omnipool_add_liquidity(lp3.clone(), BTC.into(), 10 * BTC_ONE)?; + lm_deposit_shares(lp3, 5, 6, lp3_position_id)?; + + //gId: 7, yId: 8 + initialize_global_farm(owner4.clone())?; + initialize_yield_farm(owner4, 7, BTC.into())?; + let lp4 = create_funded_account("lp_4", 1, 10 * BTC_ONE, BTC.into()); + let lp4_position_id = omnipool_add_liquidity(lp4.clone(), BTC.into(), 10 * BTC_ONE)?; + lm_deposit_shares(lp4, 7, 8, lp4_position_id)?; + + //gId: 9, yId: 10 + initialize_global_farm(owner5.clone())?; + initialize_yield_farm(owner5, 9, BTC.into())?; + let lp5 = create_funded_account("lp_5", 1, 10 * BTC_ONE, BTC.into()); + let lp5_position_id = omnipool_add_liquidity(lp5.clone(), BTC.into(), 10 * BTC_ONE)?; + lm_deposit_shares(lp5, 9, 10, lp5_position_id)?; + + let lp6 = create_funded_account("lp_6", 5, 10 * BTC_ONE, BTC.into()); + let lp6_position_id = omnipool_add_liquidity(lp6.clone(), BTC.into(), 10 * BTC_ONE)?; + + set_period(200); + let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; + let farms = farms_entries[0..c as usize].to_vec(); + + }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), lp6_position_id) + + add_liquidity_and_join_farms { + let c in 1..get_max_entries(); + + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + + let deposit_id = 1; + + initialize_omnipool()?; + + //gId: 1, yId: 2 + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner, 1, BTC.into())?; + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + lm_deposit_shares(lp1, 1, 2, lp1_position_id)?; + + //gId: 3, yId: 4 + initialize_global_farm(owner2.clone())?; + initialize_yield_farm(owner2, 3, BTC.into())?; + let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC.into()); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; + lm_deposit_shares(lp2, 3, 4, lp2_position_id)?; + + //gId: 5, yId: 6 + initialize_global_farm(owner3.clone())?; + initialize_yield_farm(owner3, 5, BTC.into())?; + let lp3 = create_funded_account("lp_3", 1, 10 * BTC_ONE, BTC.into()); + let lp3_position_id = omnipool_add_liquidity(lp3.clone(), BTC.into(), 10 * BTC_ONE)?; + lm_deposit_shares(lp3, 5, 6, lp3_position_id)?; + + //gId: 7, yId: 8 + initialize_global_farm(owner4.clone())?; + initialize_yield_farm(owner4, 7, BTC.into())?; + let lp4 = create_funded_account("lp_4", 1, 10 * BTC_ONE, BTC.into()); + let lp4_position_id = omnipool_add_liquidity(lp4.clone(), BTC.into(), 10 * BTC_ONE)?; + lm_deposit_shares(lp4, 7, 8, lp4_position_id)?; + + //gId: 9, yId: 10 + initialize_global_farm(owner5.clone())?; + initialize_yield_farm(owner5, 9, BTC.into())?; + let lp5 = create_funded_account("lp_5", 1, 10 * BTC_ONE, BTC.into()); + let lp5_position_id = omnipool_add_liquidity(lp5.clone(), BTC.into(), 10 * BTC_ONE)?; + lm_deposit_shares(lp5, 9, 10, lp5_position_id)?; + + let lp6 = create_funded_account("lp_6", 5, 10 * BTC_ONE, BTC.into()); + + set_period(200); + let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; + let farms = farms_entries[0..c as usize].to_vec(); + + }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), BTC.into(), 10 * BTC_ONE) + + exit_farms { + let c in 1..get_max_entries(); + + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + + let deposit_id = 1; + + initialize_omnipool()?; + + //gId: 1, yId: 2 + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner, 1, BTC.into())?; + + //gId: 3, yId: 4 + initialize_global_farm(owner2.clone())?; + initialize_yield_farm(owner2, 3, BTC.into())?; + + //gId: 5, yId: 6 + initialize_global_farm(owner3.clone())?; + initialize_yield_farm(owner3, 5, BTC.into())?; + + //gId: 7, yId: 8 + initialize_global_farm(owner4.clone())?; + initialize_yield_farm(owner4, 7, BTC.into())?; + + //gId: 9, yId: 10 + initialize_global_farm(owner5.clone())?; + initialize_yield_farm(owner5, 9, BTC.into())?; + + let lp1 = create_funded_account("lp_1", 5, 10 * BTC_ONE, BTC.into()); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), BTC_ONE)?; + + set_period(200); + + lm_deposit_shares(lp1.clone(), 1, 2, lp1_position_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 3, 4, deposit_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 5, 6, deposit_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 7, 8, deposit_id)?; + OmnipoolLiquidityMining::redeposit_shares(RawOrigin::Signed(lp1.clone()).into(), 9, 10, deposit_id)?; + + let deposit_id = 1; + let farm_entries = [2,4,6,8,10]; + let farms = farm_entries[0..c as usize].to_vec(); + + set_period(250); + }: _(RawOrigin::Signed(lp1),deposit_id, farms.try_into().unwrap())*/ + + /*add_liquidity_stableswap_omnipool_and_join_farms { + let caller: T::AccountId = account("caller", 0, 1); + let lp_provider: T::AccountId = account("provider", 0, 1); + let initial_liquidity = 1_000_000_000_000_000u128; + let liquidity_added = 300_000_000_000_000u128; + + let mut initial: Vec> = vec![]; + let mut added_liquidity: Vec> = vec![]; + let mut asset_ids: Vec = Vec::new() ; + for idx in 0..MAX_ASSETS_IN_POOL { + let name: Vec = idx.to_ne_bytes().to_vec(); + let asset_id = T::AssetRegistry::register_sufficient_asset( + None, + Some(name.try_into().unwrap()), + AssetKind::Token, + 1u128, + Some(b"xDUM".to_vec().try_into().unwrap()), + Some(18u8), + None, + None, + )?; + asset_ids.push(asset_id); + T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; + T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; + initial.push(AssetAmount::new(asset_id, initial_liquidity)); + added_liquidity.push(AssetAmount::new(asset_id, liquidity_added)); + } + + /* + let name = b"BSX".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + // Register new asset in asset registry + with_transaction(|| { + TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( + None, + Some(name), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + */ + + let name = b"PO2".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + let pool_id = T::AssetRegistry::register_sufficient_asset( + None, + Some(name.try_into().unwrap()), + AssetKind::Token, + 1u128, + Some(b"xDUM".to_vec().try_into().unwrap()), + Some(18u8), + None, + None, + )?; + + let amplification = 100u16; + let trade_fee = Permill::from_percent(1); + let successful_origin = T::AuthorityOrigin::try_successful_origin().unwrap(); + OmnipoolLiquidityMining::create_pool(successful_origin, + pool_id, + asset_ids, + amplification, + trade_fee, + )?; + + // Worst case is adding additional liquidity and not initial liquidity + OmnipoolLiquidityMining::add_liquidity(RawOrigin::Signed(caller).into(), + pool_id, + initial, + )?; + + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let deposit_id = 1; + + }: _(RawOrigin::Signed(lp1),deposit_id.into(), vec![].try_into().unwrap(), vec![].try_into().unwrap())*/ + +} + +fn get_max_entries() -> u32 { + T::MaxFarmEntriesPerDeposit::get() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::NativeExistentialDeposit; + use orml_benchmarking::impl_benchmark_test_suite; + use sp_runtime::BuildStorage; + + fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default() + .build_storage() + .unwrap(); + + pallet_asset_registry::GenesisConfig:: { + registered_assets: vec![ + ( + Some(1), + Some(b"LRNA".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"DAI".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ], + native_asset_name: b"HDX".to_vec().try_into().unwrap(), + native_existential_deposit: NativeExistentialDeposit::get(), + native_decimals: 12, + native_symbol: b"HDX".to_vec().try_into().unwrap(), + } + .assimilate_storage(&mut t) + .unwrap(); + + as BuildStorage>::assimilate_storage( + &pallet_omnipool_liquidity_mining::GenesisConfig::::default(), + &mut t, + ) + .unwrap(); + + sp_io::TestExternalities::new(t) + } + + impl_benchmark_test_suite!(new_test_ext(),); +} diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index 293336267..2dacb5560 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -282,7 +282,6 @@ mod benches { frame_benchmarking::define_benchmarks!( [pallet_lbp, LBP] [pallet_asset_registry, AssetRegistry] - [pallet_omnipool_liquidity_mining, OmnipoolLiquidityMining] [pallet_transaction_pause, TransactionPause] [pallet_ema_oracle, EmaOracle] [pallet_circuit_breaker, CircuitBreaker] @@ -1011,6 +1010,7 @@ impl_runtime_apis! { orml_list_benchmark!(list, extra, pallet_xyk, benchmarking::xyk); orml_list_benchmark!(list, extra, pallet_dynamic_evm_fee, benchmarking::dynamic_evm_fee); orml_list_benchmark!(list, extra, pallet_xyk_liquidity_mining, benchmarking::xyk_liquidity_mining); + orml_list_benchmark!(list, extra, pallet_omnipool_liquidity_mining, benchmarking::omnipool_liquidity_mining); let storage_info = AllPalletsWithSystem::storage_info(); @@ -1148,6 +1148,7 @@ impl_runtime_apis! { orml_add_benchmark!(params, batches, pallet_xyk, benchmarking::xyk); orml_add_benchmark!(params, batches, pallet_dynamic_evm_fee, benchmarking::dynamic_evm_fee); orml_add_benchmark!(params, batches, pallet_xyk_liquidity_mining, benchmarking::xyk_liquidity_mining); + orml_add_benchmark!(params, batches, pallet_omnipool_liquidity_mining, benchmarking::omnipool_liquidity_mining); if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } Ok(batches) From 01de50f967c356f275661de033971170076a282f Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 29 Nov 2024 08:10:58 +0100 Subject: [PATCH 05/36] wip - reproduce failing bench test in integration test --- .../src/omnipool_liquidity_mining.rs | 311 +++++++++++++++++- .../benchmarking/omnipool_liquidity_mining.rs | 129 +++++--- 2 files changed, 391 insertions(+), 49 deletions(-) diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index dbec86c56..f101b5c99 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -17,12 +17,23 @@ #![cfg(test)] use crate::polkadot_test_net::*; +use frame_support::assert_noop; use frame_support::assert_ok; use frame_support::storage::with_transaction; use hydradx_runtime::Omnipool; +use hydradx_runtime::{ + AssetRegistry, Balance, Bonds, Currencies, Runtime, RuntimeEvent, RuntimeOrigin, Stableswap, Treasury, + TreasuryAccount, +}; use hydradx_traits::liquidity_mining::PriceAdjustment; +use hydradx_traits::stableswap::AssetAmount; +use hydradx_traits::AssetKind; use hydradx_traits::Create; use orml_traits::MultiCurrency; +use pallet_asset_registry::AssetType; +use pallet_stableswap::MAX_ASSETS_IN_POOL; +use pretty_assertions::assert_eq; +use primitives::constants::time::unix_time::MONTH; use primitives::{constants::currency::UNITS, AssetId}; use sp_runtime::DispatchResult; use sp_runtime::TransactionOutcome; @@ -35,17 +46,6 @@ use warehouse_liquidity_mining::{ YieldFarmEntry, }; use xcm_emulator::TestExt; -use frame_support::assert_noop; -use hydradx_runtime::{ - AssetRegistry, Balance, Bonds, Currencies, Runtime, RuntimeEvent, RuntimeOrigin, Stableswap, Treasury, - TreasuryAccount, -}; -use hydradx_traits::stableswap::AssetAmount; -use hydradx_traits::AssetKind; -use pallet_asset_registry::AssetType; -use pallet_stableswap::MAX_ASSETS_IN_POOL; -use pretty_assertions::assert_eq; -use primitives::constants::time::unix_time::MONTH; #[macro_export] macro_rules! assert_nft_owner { @@ -1821,3 +1821,292 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { Ok((pool_id, asset_in, asset_out)) } + +#[test] +pub fn create_yield_farm2() { + TestNet::reset(); + + Hydra::execute_with(|| { + fund_treasury().unwrap(); //To prevent BelowMinimum error + + let owner = ALICE; + >::update_balance(0, &owner.into(), INITIAL_BALANCE as i128).unwrap(); + assert_ok!(>::update_balance( + HDX, + &owner.into(), + G_FARM_TOTAL_REWARDS.try_into().unwrap(), + )); + let global_farm_id = 1; + + initialize_omnipool().unwrap(); + + initialize_global_farm(owner.clone().into()).unwrap(); + initialize_yield_farm(owner.clone().into(), global_farm_id, BTC.into()).unwrap(); + + let lp = BOB; + >::update_balance(0, &lp.into(), INITIAL_BALANCE as i128).unwrap(); + assert_ok!(>::update_balance( + HDX, + &lp.into(), + (10 * BTC_ONE).try_into().unwrap(), + )); + let position_id = omnipool_add_liquidity(lp.clone().into(), BTC.into(), 10 * BTC_ONE); + + set_period(100); + lm_deposit_shares(lp.into(), global_farm_id, 2, position_id).unwrap(); + + set_period(200); + + assert_ok!(hydradx_runtime::OmnipoolLiquidityMining::create_yield_farm( + RuntimeOrigin::signed(owner.clone().into()), + global_farm_id, + ETH.into(), + FixedU128::one(), + Some(LoyaltyCurve::default()) + )); + }); +} +pub const INITIAL_BALANCE: Balance = 10_000_000 * UNITS; +const BTC_ONE: Balance = 100_000_000; + +fn fund_treasury() -> DispatchResult { + let account = Treasury::account_id(); + + >::update_balance(0, &account, INITIAL_BALANCE as i128).unwrap(); + assert_ok!(>::update_balance( + HDX, + &account, + (10000 * UNITS).try_into().unwrap(), + )); + + assert_ok!(>::update_balance( + ETH, + &account, + (10000 * UNITS).try_into().unwrap(), + )); + + assert_ok!(>::update_balance( + HDX, + &account, + (10000 * UNITS).try_into().unwrap(), + )); + + //>::update_balance(HDX, &treasury, 500_000_000_000_000_000_000i128)?; + /*Currencies::update_balance( + RawOrigin::Root.into(), + treasury.clone(), + HDX.into(), + 500_000_000_000_000_000_000i128 as Amount, + )?; + + Currencies::update_balance( + RawOrigin::Root.into(), + treasury.clone(), + ETH.into(), + 500_000_000_000_000_000_000i128 as Amount, + )?; + + Currencies::update_balance( + RawOrigin::Root.into(), + treasury.clone(), + BTC.into(), + 500_000_000_000_000_000_000i128 as Amount, + )?; + + Currencies::update_balance( + RawOrigin::Root.into(), + treasury.clone(), + HDX.into(), + 500_000_000_000_000_000_000i128 as Amount, + )?;*/ + + Ok(()) +} +const G_FARM_TOTAL_REWARDS: Balance = 10_000_000 * UNITS; + +fn initialize_global_farm(owner: AccountId) -> DispatchResult { + OmnipoolLiquidityMining::create_global_farm( + RawOrigin::Root.into(), + G_FARM_TOTAL_REWARDS, + BlockNumberFor::::from(100_000_u32), + BlockNumberFor::::from(1_u32), + HDX.into(), + owner, + Perquintill::from_percent(20), + 1_000, + FixedU128::one(), + )?; + + seed_lm_pot(); + + Ok(()) +} + +use orml_traits::MultiCurrencyExtended; +fn initialize_yield_farm(owner: AccountId, id: GlobalFarmId, asset: AssetId) -> DispatchResult { + OmnipoolLiquidityMining::create_yield_farm(RawOrigin::Signed(owner).into(), id, asset, FixedU128::one(), None) +} + +fn initialize_omnipool() -> DispatchResult { + let stable_amount: Balance = 1_000_000_000_000_000u128; + let native_amount: Balance = 1_000_000_000_000_000u128; + let stable_price: FixedU128 = FixedU128::from((1, 2)); + let native_price: FixedU128 = FixedU128::from(1); + + let acc = Omnipool::protocol_account(); + + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DAI.into(), stable_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), HDX.into(), native_amount as Amount)?; + + fund(ALICE.clone().into(), HDX.into(), 10_000 * UNITS)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DAI.into(), stable_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), HDX.into(), native_amount as Amount)?; + + Omnipool::add_token( + RawOrigin::Root.into(), + HDX.into(), + native_price, + Permill::from_percent(100), + acc.clone(), + )?; + Omnipool::add_token( + RawOrigin::Root.into(), + DAI.into(), + stable_price, + Permill::from_percent(100), + acc.clone(), + )?; + + let name = b"BSX".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + // Register new asset in asset registry + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + None, + Some(name), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + let name = b"ETH".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + None, + Some(name), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + let name = b"BTC".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + None, + Some(name), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + + let name = b"DOT".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + None, + Some(name), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + + // Create account for token provider and set balance + let owner: AccountId = ALICE.into(); + + let token_price = FixedU128::from((1, 5)); + let token_amount = 200_000_000_000_000u128; + + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), ETH.into(), token_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), BTC.into(), token_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DOT.into(), token_amount as Amount)?; + + Omnipool::add_token( + RawOrigin::Root.into(), + ETH.into(), + token_price, + Permill::from_percent(100), + owner.clone(), + )?; + + Omnipool::add_token( + RawOrigin::Root.into(), + BTC.into(), + token_price, + Permill::from_percent(100), + owner.clone(), + )?; + + Omnipool::add_token( + RawOrigin::Root.into(), + DOT.into(), + token_price, + Permill::from_percent(100), + owner, + )?; + + //NOTE: This is necessary for oracle to provide price. + set_period(10); + + do_lrna_hdx_trade(); + + Ok(()) +} + +fn fund(to: AccountId, currency: AssetId, amount: Balance) -> DispatchResult { + Currencies::deposit(currency, &to, amount) +} + +fn lm_deposit_shares(who: AccountId, g_id: GlobalFarmId, y_id: YieldFarmId, position_id: ItemId) -> DispatchResult { + OmnipoolLiquidityMining::deposit_shares(RawOrigin::Signed(who).into(), g_id, y_id, position_id) +} + +use frame_support::traits::OnFinalize; +use frame_support::traits::OnInitialize; +use frame_system::pallet_prelude::BlockNumberFor; +use hydradx_runtime::OmnipoolLiquidityMining; +use hydradx_traits::liquidity_mining::YieldFarmId; +use primitives::Amount; +use primitives::ItemId; + +fn set_period(to: u32) { + //NOTE: predefined global farm has period size = 1 block. + while hydradx_runtime::System::block_number() < to { + let b = hydradx_runtime::System::block_number(); + + as OnFinalize>>::on_finalize(b); + as frame_support::traits::OnFinalize< + BlockNumberFor, + >>::on_finalize(b); + + as OnInitialize>>::on_initialize( + b + 1_u32, + ); + as frame_support::traits::OnInitialize< + BlockNumberFor, + >>::on_initialize(b + 1_u32); + + hydradx_runtime::System::set_block_number(b + 1_u32); + } +} diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index 984ed28b0..fb84c51be 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -15,23 +15,23 @@ #![cfg(feature = "runtime-benchmarks")] +use crate::benchmarking::{register_asset, register_external_asset}; use crate::*; -use frame_benchmarking::{account, BenchmarkError, benchmarks}; +use frame_benchmarking::{account, benchmarks, BenchmarkError}; use frame_support::assert_ok; use frame_support::storage::with_transaction; use frame_support::traits::{OnFinalize, OnInitialize}; -use frame_system::{RawOrigin}; use frame_system::pallet_prelude::BlockNumberFor; -use orml_benchmarking::runtime_benchmarks; +use frame_system::RawOrigin; +use hydradx_traits::liquidity_mining::{GlobalFarmId, YieldFarmId}; use hydradx_traits::registry::{AssetKind, Create}; +use hydradx_traits::stableswap::AssetAmount; +use orml_benchmarking::runtime_benchmarks; use orml_traits::MultiCurrencyExtended; use primitives::AssetId; -use sp_runtime::{DispatchError, DispatchResult, Perquintill, TransactionOutcome}; use sp_runtime::{traits::One, FixedU128, Permill}; -use hydradx_traits::liquidity_mining::{GlobalFarmId, YieldFarmId}; -use hydradx_traits::stableswap::AssetAmount; +use sp_runtime::{DispatchError, DispatchResult, Perquintill, TransactionOutcome}; use warehouse_liquidity_mining::LoyaltyCurve; -use crate::benchmarking::{register_asset, register_external_asset}; const ONE: Balance = 1_000_000_000_000; const BTC_ONE: Balance = 100_000_000; const HDX: AssetId = 0; @@ -47,7 +47,6 @@ const REWARD_CURRENCY: AssetId = HDX; pub const MAX_ASSETS_IN_POOL: u32 = 5; - fn fund(to: AccountId, currency: AssetId, amount: Balance) -> DispatchResult { Currencies::deposit(currency, &to, amount) } @@ -70,8 +69,73 @@ fn funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> Account account } -fn initialize_global_farm(owner: AccountId) -> DispatchResult -{ +fn fund_treasury() -> DispatchResult { + let account = Treasury::account_id(); + + >::update_balance(0, &account, INITIAL_BALANCE as i128).unwrap(); + assert_ok!(>::update_balance( + HDX, + &account, + (10000 * ONE).try_into().unwrap(), + )); + + assert_ok!(>::update_balance( + ETH, + &account, + (10000 * ONE).try_into().unwrap(), + )); + + assert_ok!(>::update_balance( + REWARD_CURRENCY, + &account, + (10000 * ONE).try_into().unwrap(), + )); + + //>::update_balance(HDX, &treasury, 500_000_000_000_000_000_000i128)?; + /*Currencies::update_balance( + RawOrigin::Root.into(), + treasury.clone(), + HDX.into(), + 500_000_000_000_000_000_000i128 as Amount, + )?; + + Currencies::update_balance( + RawOrigin::Root.into(), + treasury.clone(), + ETH.into(), + 500_000_000_000_000_000_000i128 as Amount, + )?; + + Currencies::update_balance( + RawOrigin::Root.into(), + treasury.clone(), + BTC.into(), + 500_000_000_000_000_000_000i128 as Amount, + )?; + + Currencies::update_balance( + RawOrigin::Root.into(), + treasury.clone(), + REWARD_CURRENCY.into(), + 500_000_000_000_000_000_000i128 as Amount, + )?;*/ + + Ok(()) +} + +fn create_funded_account(name: &'static str, index: u32, balance: Balance, asset: AssetId) -> AccountId { + let account: AccountId = account(name, index, 0); + //Necessary to pay ED in insufficient asset + >::update_balance(0, &account, INITIAL_BALANCE as i128).unwrap(); + assert_ok!(>::update_balance( + asset, + &account, + balance.try_into().unwrap(), + )); + account +} + +fn initialize_global_farm(owner: AccountId) -> DispatchResult { OmnipoolLiquidityMining::create_global_farm( RawOrigin::Root.into(), G_FARM_TOTAL_REWARDS, @@ -87,13 +151,11 @@ fn initialize_global_farm(owner: AccountId) -> DispatchResult seed_lm_pot() } -fn initialize_yield_farm(owner: AccountId, id: GlobalFarmId, asset: AssetId) -> DispatchResult -{ +fn initialize_yield_farm(owner: AccountId, id: GlobalFarmId, asset: AssetId) -> DispatchResult { OmnipoolLiquidityMining::create_yield_farm(RawOrigin::Signed(owner).into(), id, asset, FixedU128::one(), None) } -fn initialize_omnipool() -> DispatchResult -{ +fn initialize_omnipool() -> DispatchResult { let stable_amount: Balance = 1_000_000_000_000_000u128; let native_amount: Balance = 1_000_000_000_000_000u128; let stable_price: FixedU128 = FixedU128::from((1, 2)); @@ -229,8 +291,7 @@ fn initialize_omnipool() -> DispatchResult } //NOTE: This is necessary for oracle to provide price. -fn do_lrna_hdx_trade() -> DispatchResult -{ +fn do_lrna_hdx_trade() -> DispatchResult { let trader = funded_account("tmp_trader", 0, &vec![REWARD_CURRENCY.into()]); fund(trader.clone(), LRNA.into(), 100 * ONE)?; @@ -238,18 +299,13 @@ fn do_lrna_hdx_trade() -> DispatchResult Omnipool::sell(RawOrigin::Signed(trader).into(), LRNA.into(), HDX.into(), ONE, 0) } -fn seed_lm_pot() -> DispatchResult -{ +fn seed_lm_pot() -> DispatchResult { let pot = XYKWarehouseLM::pot_account_id().unwrap(); fund(pot, HDX.into(), 100 * ONE) } -fn omnipool_add_liquidity( - lp: AccountId, - asset: AssetId, - amount: Balance, -) -> Result { +fn omnipool_add_liquidity(lp: AccountId, asset: AssetId, amount: Balance) -> Result { let current_position_id = Omnipool::next_position_id(); Omnipool::add_liquidity(RawOrigin::Signed(lp).into(), asset, amount)?; @@ -257,17 +313,11 @@ fn omnipool_add_liquidity( Ok(current_position_id) } -fn lm_deposit_shares( - who: AccountId, - g_id: GlobalFarmId, - y_id: YieldFarmId, - position_id: ItemId, -) -> DispatchResult { +fn lm_deposit_shares(who: AccountId, g_id: GlobalFarmId, y_id: YieldFarmId, position_id: ItemId) -> DispatchResult { OmnipoolLiquidityMining::deposit_shares(RawOrigin::Signed(who).into(), g_id, y_id, position_id) } -fn set_period(to: u32) -{ +fn set_period(to: u32) { //NOTE: predefined global farm has period size = 1 block. while System::block_number() < to { let b = System::block_number(); @@ -312,9 +362,9 @@ runtime_benchmarks! { }: _(RawOrigin::Root, global_farm_id, planned_yielding_periods, yield_per_period, min_deposit) -/* + terminate_global_farm { - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = funded_account("owner", 0, &[REWARD_CURRENCY.into()]); let global_farm_id = 1; let yield_farm_id = 2; @@ -323,7 +373,7 @@ runtime_benchmarks! { initialize_global_farm(owner.clone())?; initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; - let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let lp = funded_account("lp_1", 1, &[BTC.into()]); let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; set_period(100); @@ -337,6 +387,8 @@ runtime_benchmarks! { create_yield_farm { + fund_treasury().unwrap(); //To prevent BelowMinimum error + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); let global_farm_id = 1; @@ -352,9 +404,10 @@ runtime_benchmarks! { lm_deposit_shares(lp, global_farm_id, 2, position_id)?; set_period(200); - }: _(RawOrigin::Signed(owner), global_farm_id, ETH.into(), FixedU128::one(), Some(LoyaltyCurve::default())) + }: _(RawOrigin::Signed(owner), global_farm_id, ETH.into(), FixedU128::one(), Some(LoyaltyCurve::default())) +/* update_yield_farm { let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); let global_farm_id = 1; @@ -874,14 +927,14 @@ mod tests { native_decimals: 12, native_symbol: b"HDX".to_vec().try_into().unwrap(), } - .assimilate_storage(&mut t) - .unwrap(); + .assimilate_storage(&mut t) + .unwrap(); as BuildStorage>::assimilate_storage( &pallet_omnipool_liquidity_mining::GenesisConfig::::default(), &mut t, ) - .unwrap(); + .unwrap(); sp_io::TestExternalities::new(t) } From 3632f319cc5d22138039f3ae55615af7485cbcb7 Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 29 Nov 2024 10:47:55 +0100 Subject: [PATCH 06/36] adjust balance updates --- .../benchmarking/omnipool_liquidity_mining.rs | 33 ++++++------------- 1 file changed, 10 insertions(+), 23 deletions(-) diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index fb84c51be..1c1e63ca9 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -72,25 +72,9 @@ fn funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> Account fn fund_treasury() -> DispatchResult { let account = Treasury::account_id(); - >::update_balance(0, &account, INITIAL_BALANCE as i128).unwrap(); - assert_ok!(>::update_balance( - HDX, - &account, - (10000 * ONE).try_into().unwrap(), - )); - - assert_ok!(>::update_balance( - ETH, - &account, - (10000 * ONE).try_into().unwrap(), - )); - - assert_ok!(>::update_balance( - REWARD_CURRENCY, - &account, - (10000 * ONE).try_into().unwrap(), - )); - + Currencies::update_balance(RawOrigin::Root.into(), account.clone(), HDX, INITIAL_BALANCE as i128).unwrap(); + Currencies::update_balance(RawOrigin::Root.into(), account.clone(), ETH, INITIAL_BALANCE as i128).unwrap(); + Currencies::update_balance(RawOrigin::Root.into(), account.clone(), REWARD_CURRENCY, INITIAL_BALANCE as i128).unwrap(); //>::update_balance(HDX, &treasury, 500_000_000_000_000_000_000i128)?; /*Currencies::update_balance( RawOrigin::Root.into(), @@ -126,13 +110,16 @@ fn fund_treasury() -> DispatchResult { fn create_funded_account(name: &'static str, index: u32, balance: Balance, asset: AssetId) -> AccountId { let account: AccountId = account(name, index, 0); //Necessary to pay ED in insufficient asset - >::update_balance(0, &account, INITIAL_BALANCE as i128).unwrap(); - assert_ok!(>::update_balance( + Currencies::update_balance(RawOrigin::Root.into(), account.clone(),DAI, INITIAL_BALANCE as i128).unwrap(); + Currencies::update_balance(RawOrigin::Root.into(), account.clone(),LRNA, INITIAL_BALANCE as i128).unwrap(); + Currencies::update_balance(RawOrigin::Root.into(), account.clone(),0, INITIAL_BALANCE as i128).unwrap(); + assert_ok!(Currencies::update_balance( + RawOrigin::Root.into(), + account.clone(), asset, - &account, balance.try_into().unwrap(), )); - account + account.clone() } fn initialize_global_farm(owner: AccountId) -> DispatchResult { From 98ad77a33ae0d26f975f8c152f93ae1eb53d1f8c Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 29 Nov 2024 10:49:03 +0100 Subject: [PATCH 07/36] fix test --- .../src/omnipool_liquidity_mining.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index f101b5c99..282a98eb0 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -1846,10 +1846,11 @@ pub fn create_yield_farm2() { let lp = BOB; >::update_balance(0, &lp.into(), INITIAL_BALANCE as i128).unwrap(); assert_ok!(>::update_balance( - HDX, + BTC, &lp.into(), (10 * BTC_ONE).try_into().unwrap(), )); + let position_id = omnipool_add_liquidity(lp.clone().into(), BTC.into(), 10 * BTC_ONE); set_period(100); @@ -1991,7 +1992,7 @@ fn initialize_omnipool() -> DispatchResult { None, )) })?; - let name = b"ETH".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + /*let name = b"ETH".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; with_transaction(|| { TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( None, @@ -2003,8 +2004,8 @@ fn initialize_omnipool() -> DispatchResult { None, None, )) - })?; - let name = b"BTC".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + })?;*/ + /*let name = b"BTC".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; with_transaction(|| { TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( None, @@ -2016,9 +2017,9 @@ fn initialize_omnipool() -> DispatchResult { None, None, )) - })?; + })?;*/ - let name = b"DOT".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + /*let name = b"DOT".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; with_transaction(|| { TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( None, @@ -2030,7 +2031,7 @@ fn initialize_omnipool() -> DispatchResult { None, None, )) - })?; + })?;*/ // Create account for token provider and set balance let owner: AccountId = ALICE.into(); From 8ad27262b09d65c9cb35bfb5981ea954b5c5186b Mon Sep 17 00:00:00 2001 From: dmoka Date: Sun, 1 Dec 2024 18:21:14 +0100 Subject: [PATCH 08/36] add benchmark for new extrinswics --- pallets/omnipool-liquidity-mining/src/lib.rs | 2 +- runtime/hydradx/src/benchmarking/mod.rs | 17 ++ .../benchmarking/omnipool_liquidity_mining.rs | 244 ++++++++++-------- 3 files changed, 148 insertions(+), 115 deletions(-) diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index 6b2fbc759..afb48716d 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -1087,7 +1087,7 @@ pub mod pallet { pub fn add_liquidity_stableswap_omnipool_and_join_farms( origin: OriginFor, stable_pool_id: T::AssetId, - stable_asset_amounts: BoundedVec, T::MaxFarmEntriesPerDeposit>, + stable_asset_amounts: BoundedVec, T::MaxFarmEntriesPerDeposit>, //TODO: This sohuld be max stable asset amounts farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, ) -> DispatchResult { let who = ensure_signed(origin.clone())?; diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index a2a90fe86..f41ac63c8 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -46,6 +46,23 @@ pub fn register_asset(name: Vec, deposit: Balance) -> Result { .map_err(|_| ()) } +pub fn register_asset_with_decimals(name: Vec, deposit: Balance, decimals: u8) -> Result { + let n = name.try_into().map_err(|_| ())?; + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + None, + Some(n), + AssetKind::Token, + deposit, + None, + Some(decimals), + None, + None, + )) + }) + .map_err(|_| ()) +} + pub fn register_external_asset(name: Vec) -> Result { let n = name.try_into().map_err(|_| ())?; with_transaction(|| { diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index 1c1e63ca9..66326fc6e 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -15,7 +15,7 @@ #![cfg(feature = "runtime-benchmarks")] -use crate::benchmarking::{register_asset, register_external_asset}; +use crate::benchmarking::{register_asset, register_asset_with_decimals, register_external_asset}; use crate::*; use frame_benchmarking::{account, benchmarks, BenchmarkError}; use frame_support::assert_ok; @@ -32,6 +32,7 @@ use primitives::AssetId; use sp_runtime::{traits::One, FixedU128, Permill}; use sp_runtime::{DispatchError, DispatchResult, Perquintill, TransactionOutcome}; use warehouse_liquidity_mining::LoyaltyCurve; +use frame_support::traits::EnsureOrigin; const ONE: Balance = 1_000_000_000_000; const BTC_ONE: Balance = 100_000_000; const HDX: AssetId = 0; @@ -58,13 +59,10 @@ pub const INITIAL_BALANCE: Balance = 10_000_000 * crate::benchmarking::xyk_liqui fn funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> AccountId { let account: AccountId = account(name, index, 0); //Necessary to pay ED in insufficient asset - >::update_balance(0, &account, INITIAL_BALANCE as i128).unwrap(); + Currencies::update_balance(RawOrigin::Root.into(), account.clone(), HDX, 500_000_000_000_000_000_000i128).unwrap(); + for asset in assets { - assert_ok!(>::update_balance( - *asset, - &account, - INITIAL_BALANCE.try_into().unwrap(), - )); + Currencies::update_balance(RawOrigin::Root.into(), account.clone(), *asset, 500_000_000_000_000_000_000i128).unwrap(); } account } @@ -72,37 +70,8 @@ fn funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> Account fn fund_treasury() -> DispatchResult { let account = Treasury::account_id(); - Currencies::update_balance(RawOrigin::Root.into(), account.clone(), HDX, INITIAL_BALANCE as i128).unwrap(); - Currencies::update_balance(RawOrigin::Root.into(), account.clone(), ETH, INITIAL_BALANCE as i128).unwrap(); + Currencies::update_balance(RawOrigin::Root.into(), account.clone(), HDX, 500_000_000_000_000_000_000i128).unwrap(); Currencies::update_balance(RawOrigin::Root.into(), account.clone(), REWARD_CURRENCY, INITIAL_BALANCE as i128).unwrap(); - //>::update_balance(HDX, &treasury, 500_000_000_000_000_000_000i128)?; - /*Currencies::update_balance( - RawOrigin::Root.into(), - treasury.clone(), - HDX.into(), - 500_000_000_000_000_000_000i128 as Amount, - )?; - - Currencies::update_balance( - RawOrigin::Root.into(), - treasury.clone(), - ETH.into(), - 500_000_000_000_000_000_000i128 as Amount, - )?; - - Currencies::update_balance( - RawOrigin::Root.into(), - treasury.clone(), - BTC.into(), - 500_000_000_000_000_000_000i128 as Amount, - )?; - - Currencies::update_balance( - RawOrigin::Root.into(), - treasury.clone(), - REWARD_CURRENCY.into(), - 500_000_000_000_000_000_000i128 as Amount, - )?;*/ Ok(()) } @@ -142,7 +111,7 @@ fn initialize_yield_farm(owner: AccountId, id: GlobalFarmId, asset: AssetId) -> OmnipoolLiquidityMining::create_yield_farm(RawOrigin::Signed(owner).into(), id, asset, FixedU128::one(), None) } -fn initialize_omnipool() -> DispatchResult { +fn initialize_omnipool(additional_asset: Option) -> DispatchResult { let stable_amount: Balance = 1_000_000_000_000_000u128; let native_amount: Balance = 1_000_000_000_000_000u128; let stable_price: FixedU128 = FixedU128::from((1, 2)); @@ -153,9 +122,7 @@ fn initialize_omnipool() -> DispatchResult { Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DAI.into(), stable_amount as Amount)?; Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), HDX.into(), native_amount as Amount)?; - fund(acc.clone(), HDX.into(), 10_000 * ONE)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DAI.into(), stable_amount as Amount)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), HDX.into(), native_amount as Amount)?; + fund(acc.clone(), HDX.into(), 10_000_000_000_000_000 * ONE)?; Omnipool::add_token( RawOrigin::Root.into(), @@ -228,7 +195,7 @@ fn initialize_omnipool() -> DispatchResult { })?; // Create account for token provider and set balance - let owner: AccountId = account("owner", 0, 1); + let owner: AccountId = funded_account("owner2", 0, &vec![]); let token_price = FixedU128::from((1, 5)); let token_amount = 200_000_000_000_000u128; @@ -268,9 +235,21 @@ fn initialize_omnipool() -> DispatchResult { DOT.into(), token_price, Permill::from_percent(100), - owner, + owner.clone(), )?; + if let Some(asset_id) = additional_asset { + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), asset_id.into(), (token_amount * 100) as Amount)?; + Omnipool::add_token( + RawOrigin::Root.into(), + asset_id.into(), + token_price, + Permill::from_percent(100), + owner, + )?; + } + + //NOTE: This is necessary for oracle to provide price. set_period(10); @@ -287,7 +266,7 @@ fn do_lrna_hdx_trade() -> DispatchResult { } fn seed_lm_pot() -> DispatchResult { - let pot = XYKWarehouseLM::pot_account_id().unwrap(); + let pot = OmnipoolWarehouseLM::pot_account_id().unwrap(); fund(pot, HDX.into(), 100 * ONE) } @@ -309,9 +288,11 @@ fn set_period(to: u32) { while System::block_number() < to { let b = System::block_number(); + as OnFinalize>>::on_finalize(b); as OnFinalize>>::on_finalize(b); as frame_support::traits::OnFinalize>>::on_finalize(b); + as OnInitialize>>::on_initialize(b + 1_u32); as OnInitialize>>::on_initialize(b + 1_u32); as frame_support::traits::OnInitialize>>::on_initialize(b + 1_u32); @@ -338,7 +319,7 @@ runtime_benchmarks! { let global_farm_id = 1; let yield_farm_id = 2; - initialize_omnipool()?; + initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; @@ -355,7 +336,7 @@ runtime_benchmarks! { let global_farm_id = 1; let yield_farm_id = 2; - initialize_omnipool()?; + initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; @@ -376,31 +357,35 @@ runtime_benchmarks! { create_yield_farm { fund_treasury().unwrap(); //To prevent BelowMinimum error - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = funded_account("owner", 0, &[HDX, REWARD_CURRENCY.into()]); let global_farm_id = 1; - initialize_omnipool()?; + initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; - let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let lp = funded_account("lp_1", 1, &[BTC.into()]); let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; set_period(100); lm_deposit_shares(lp, global_farm_id, 2, position_id)?; - set_period(200); + set_period(1000); + + }: { + OmnipoolLiquidityMining::create_yield_farm(RawOrigin::Signed(owner).into(), global_farm_id, ETH.into(), FixedU128::one(), Some(LoyaltyCurve::default()))?; + + } verify { + } - }: _(RawOrigin::Signed(owner), global_farm_id, ETH.into(), FixedU128::one(), Some(LoyaltyCurve::default())) -/* update_yield_farm { let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); let global_farm_id = 1; let yield_farm_id = 2; - initialize_omnipool()?; + initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; @@ -418,7 +403,7 @@ runtime_benchmarks! { let global_farm_id = 1; let yield_farm_id = 2; - initialize_omnipool()?; + initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; @@ -437,7 +422,7 @@ runtime_benchmarks! { let eth_farm_id = 2; let btc_farm_id = 3; - initialize_omnipool()?; + initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; initialize_yield_farm(owner.clone(), global_farm_id, ETH.into())?; @@ -460,7 +445,7 @@ runtime_benchmarks! { let global_farm_id = 1; let yield_farm_id = 2; - initialize_omnipool()?; + initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; @@ -482,7 +467,7 @@ runtime_benchmarks! { let global_farm_id = 1; let yield_farm_id = 2; - initialize_omnipool()?; + initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; initialize_yield_farm(owner, global_farm_id, BTC.into())?; @@ -509,7 +494,7 @@ runtime_benchmarks! { let deposit_id = 1; - initialize_omnipool()?; + initialize_omnipool(None)?; //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; @@ -559,7 +544,7 @@ runtime_benchmarks! { let deposit_id = 1; - initialize_omnipool()?; + initialize_omnipool(None)?; //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; @@ -611,7 +596,7 @@ runtime_benchmarks! { let yield_farm_id = 2; let deposit_id = 1; - initialize_omnipool()?; + initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; initialize_yield_farm(owner, global_farm_id, BTC.into())?; @@ -639,7 +624,7 @@ runtime_benchmarks! { let deposit_id = 1; - initialize_omnipool()?; + initialize_omnipool(None)?; //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; @@ -696,7 +681,7 @@ runtime_benchmarks! { let deposit_id = 1; - initialize_omnipool()?; + initialize_omnipool(None)?; //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; @@ -752,7 +737,7 @@ runtime_benchmarks! { let deposit_id = 1; - initialize_omnipool()?; + initialize_omnipool(None)?; //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; @@ -790,69 +775,43 @@ runtime_benchmarks! { let farms = farm_entries[0..c as usize].to_vec(); set_period(250); - }: _(RawOrigin::Signed(lp1),deposit_id, farms.try_into().unwrap())*/ + }: _(RawOrigin::Signed(lp1),deposit_id, farms.try_into().unwrap()) - /*add_liquidity_stableswap_omnipool_and_join_farms { - let caller: T::AccountId = account("caller", 0, 1); - let lp_provider: T::AccountId = account("provider", 0, 1); + add_liquidity_stableswap_omnipool_and_join_farms { + //Init stableswap first + let caller: AccountId = account("caller", 0, 1); + let lp_provider: AccountId = account("provider", 0, 1); let initial_liquidity = 1_000_000_000_000_000u128; let liquidity_added = 300_000_000_000_000u128; - let mut initial: Vec> = vec![]; - let mut added_liquidity: Vec> = vec![]; - let mut asset_ids: Vec = Vec::new() ; + let mut initial: Vec> = vec![]; + let mut added_liquidity: Vec> = vec![]; + let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::register_sufficient_asset( - None, - Some(name.try_into().unwrap()), - AssetKind::Token, + let asset_id = register_asset_with_decimals( + name, 1u128, - Some(b"xDUM".to_vec().try_into().unwrap()), - Some(18u8), - None, - None, - )?; + 18u8 + ).unwrap(); asset_ids.push(asset_id); - T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; - T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; + Currencies::update_balance(RawOrigin::Root.into(), caller.clone(),asset_id, 1_000_000_000_000_000i128)?; + Currencies::update_balance(RawOrigin::Root.into(), lp_provider.clone(),asset_id, 1_000_000_000_000_000_000_000i128)?; initial.push(AssetAmount::new(asset_id, initial_liquidity)); added_liquidity.push(AssetAmount::new(asset_id, liquidity_added)); } - /* - let name = b"BSX".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; - // Register new asset in asset registry - with_transaction(|| { - TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( - None, - Some(name), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )) - })?; - */ - - let name = b"PO2".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; - let pool_id = T::AssetRegistry::register_sufficient_asset( - None, - Some(name.try_into().unwrap()), - AssetKind::Token, + let name : Vec = b"PO2".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + let pool_id = register_asset_with_decimals( + name, 1u128, - Some(b"xDUM".to_vec().try_into().unwrap()), - Some(18u8), - None, - None, - )?; + 18u8 + ).unwrap(); let amplification = 100u16; let trade_fee = Permill::from_percent(1); - let successful_origin = T::AuthorityOrigin::try_successful_origin().unwrap(); - OmnipoolLiquidityMining::create_pool(successful_origin, + let successful_origin = ::AuthorityOrigin::try_successful_origin().unwrap(); + Stableswap::create_pool(successful_origin, pool_id, asset_ids, amplification, @@ -860,7 +819,7 @@ runtime_benchmarks! { )?; // Worst case is adding additional liquidity and not initial liquidity - OmnipoolLiquidityMining::add_liquidity(RawOrigin::Signed(caller).into(), + Stableswap::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, initial, )?; @@ -868,12 +827,69 @@ runtime_benchmarks! { let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); let deposit_id = 1; - }: _(RawOrigin::Signed(lp1),deposit_id.into(), vec![].try_into().unwrap(), vec![].try_into().unwrap())*/ + //Init LM farms + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + + let deposit_id = 1; + + initialize_omnipool(Some(pool_id))?; + + CircuitBreaker::set_add_liquidity_limit(RuntimeOrigin::root(), pool_id, Some((99, 100))).unwrap(); + let liquidity_added = 100_000_000_000_000_u128; + let omni_lp_provider: AccountId = create_funded_account("provider", 1, liquidity_added * 10, pool_id); + Omnipool::add_liquidity(RawOrigin::Signed(omni_lp_provider.clone()).into(), pool_id, liquidity_added)?; + + //gId: 1, yId: 2 + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner, 1, pool_id.into())?; + let lp1 = create_funded_account("lp_1", 1, 10 * ONE, pool_id.into()); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), pool_id.into(), 10 * ONE)?; + lm_deposit_shares(lp1, 1, 2, lp1_position_id)?; + + //gId: 3, yId: 4 + initialize_global_farm(owner2.clone())?; + initialize_yield_farm(owner2, 3, pool_id.into())?; + let lp2 = create_funded_account("lp_2", 1, 10 * ONE, pool_id.into()); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), pool_id.into(), 10 * ONE)?; + lm_deposit_shares(lp2, 3, 4, lp2_position_id)?; + + //gId: 5, yId: 6 + initialize_global_farm(owner3.clone())?; + initialize_yield_farm(owner3, 5, pool_id.into())?; + let lp3 = create_funded_account("lp_3", 1, 10 * ONE, pool_id.into()); + let lp3_position_id = omnipool_add_liquidity(lp3.clone(), pool_id.into(), 10 * ONE)?; + lm_deposit_shares(lp3, 5, 6, lp3_position_id)?; + + //gId: 7, yId: 8 + initialize_global_farm(owner4.clone())?; + initialize_yield_farm(owner4, 7, pool_id.into())?; + let lp4 = create_funded_account("lp_4", 1, 10 * ONE, pool_id.into()); + let lp4_position_id = omnipool_add_liquidity(lp4.clone(), pool_id.into(), 10 * ONE)?; + lm_deposit_shares(lp4, 7, 8, lp4_position_id)?; + + //gId: 9, yId: 10 + initialize_global_farm(owner5.clone())?; + initialize_yield_farm(owner5, 9, pool_id.into())?; + let lp5 = create_funded_account("lp_5", 1, 10 * ONE, pool_id.into()); + let lp5_position_id = omnipool_add_liquidity(lp5.clone(), pool_id.into(), 10 * ONE)?; + lm_deposit_shares(lp5, 9, 10, lp5_position_id)?; + + let lp6 = create_funded_account("lp_6", 5, 10 * ONE, pool_id.into()); + + set_period(200); + let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; + let farms = farms_entries[0..5 as usize].to_vec(); + + }: _(RawOrigin::Signed(lp_provider),pool_id, added_liquidity.try_into().unwrap(), farms.try_into().unwrap()) } -fn get_max_entries() -> u32 { - T::MaxFarmEntriesPerDeposit::get() +fn get_max_entries() -> u32 { + ::MaxFarmEntriesPerDeposit::get() as u32 } #[cfg(test)] From ea0af62e63f852e6cbb61f0c48d5d93cfe624efd Mon Sep 17 00:00:00 2001 From: dmoka Date: Sun, 1 Dec 2024 18:25:23 +0100 Subject: [PATCH 09/36] parameterize benchmark test --- runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index 66326fc6e..3bc87ad90 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -778,6 +778,8 @@ runtime_benchmarks! { }: _(RawOrigin::Signed(lp1),deposit_id, farms.try_into().unwrap()) add_liquidity_stableswap_omnipool_and_join_farms { + let c in 1..get_max_entries(); + //Init stableswap first let caller: AccountId = account("caller", 0, 1); let lp_provider: AccountId = account("provider", 0, 1); @@ -882,7 +884,7 @@ runtime_benchmarks! { set_period(200); let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; - let farms = farms_entries[0..5 as usize].to_vec(); + let farms = farms_entries[0..c as usize].to_vec(); }: _(RawOrigin::Signed(lp_provider),pool_id, added_liquidity.try_into().unwrap(), farms.try_into().unwrap()) From d53b4dd3b24a2cb7895d37630112492422ee2a88 Mon Sep 17 00:00:00 2001 From: dmoka Date: Sun, 1 Dec 2024 18:44:39 +0100 Subject: [PATCH 10/36] use stableswap max asset const config in OMNI LM --- Cargo.lock | 1 + pallets/omnipool-liquidity-mining/Cargo.toml | 1 + pallets/omnipool-liquidity-mining/src/lib.rs | 4 +++- runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs | 4 +--- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 91ba37521..4a92d724c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8777,6 +8777,7 @@ dependencies = [ "pallet-ema-oracle", "pallet-liquidity-mining", "pallet-omnipool", + "pallet-stableswap", "parity-scale-codec", "pretty_assertions", "primitive-types", diff --git a/pallets/omnipool-liquidity-mining/Cargo.toml b/pallets/omnipool-liquidity-mining/Cargo.toml index f755e4675..fdd70724f 100644 --- a/pallets/omnipool-liquidity-mining/Cargo.toml +++ b/pallets/omnipool-liquidity-mining/Cargo.toml @@ -20,6 +20,7 @@ log = { workspace = true } # local primitives = { workspace = true } pallet-omnipool = { workspace = true } +pallet-stableswap = { workspace = true } # primitives sp-runtime = { workspace = true } diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index afb48716d..f25fb755f 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -74,6 +74,8 @@ use sp_runtime::{ArithmeticError, FixedU128, Perquintill}; use sp_std::vec; pub use weights::WeightInfo; +pub const MAX_ASSETS_IN_POOL: u32 = pallet_stableswap::MAX_ASSETS_IN_POOL; + type OmnipoolPallet = pallet_omnipool::Pallet; type PeriodOf = BlockNumberFor; @@ -1087,7 +1089,7 @@ pub mod pallet { pub fn add_liquidity_stableswap_omnipool_and_join_farms( origin: OriginFor, stable_pool_id: T::AssetId, - stable_asset_amounts: BoundedVec, T::MaxFarmEntriesPerDeposit>, //TODO: This sohuld be max stable asset amounts + stable_asset_amounts: BoundedVec, ConstU32>, farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, ) -> DispatchResult { let who = ensure_signed(origin.clone())?; diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index 3bc87ad90..d3b1592c2 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -46,8 +46,6 @@ const DOT: AssetId = 1_000_004; const G_FARM_TOTAL_REWARDS: Balance = 10_000_000 * ONE; const REWARD_CURRENCY: AssetId = HDX; -pub const MAX_ASSETS_IN_POOL: u32 = 5; - fn fund(to: AccountId, currency: AssetId, amount: Balance) -> DispatchResult { Currencies::deposit(currency, &to, amount) } @@ -789,7 +787,7 @@ runtime_benchmarks! { let mut initial: Vec> = vec![]; let mut added_liquidity: Vec> = vec![]; let mut asset_ids: Vec = Vec::new() ; - for idx in 0..MAX_ASSETS_IN_POOL { + for idx in 0..pallet_stableswap::MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); let asset_id = register_asset_with_decimals( name, From 5f7cb150512d9cd9ede8e7ddc38560e6902609af Mon Sep 17 00:00:00 2001 From: dmoka Date: Sun, 1 Dec 2024 18:44:47 +0100 Subject: [PATCH 11/36] formatting --- pallets/omnipool-liquidity-mining/src/lib.rs | 4 +- pallets/stableswap/src/benchmarks.rs | 2 +- pallets/stableswap/src/lib.rs | 21 +++++--- pallets/stableswap/src/tests/add_liquidity.rs | 4 +- .../src/tests/calculate_spot_price.rs | 4 +- pallets/stableswap/src/tests/hooks.rs | 2 +- pallets/stableswap/src/tests/invariants.rs | 4 +- pallets/stableswap/src/tests/mock.rs | 2 +- pallets/stableswap/src/tests/price.rs | 4 +- .../stableswap/src/tests/remove_liquidity.rs | 4 +- pallets/stableswap/src/tests/trades.rs | 4 +- pallets/stableswap/src/trade_execution.rs | 2 +- pallets/stableswap/src/types.rs | 1 - runtime/hydradx/src/assets.rs | 2 +- runtime/hydradx/src/benchmarking/mod.rs | 4 +- .../benchmarking/omnipool_liquidity_mining.rs | 54 ++++++++++++++----- traits/src/lib.rs | 1 - traits/src/stableswap.rs | 35 ++++++------ 18 files changed, 93 insertions(+), 61 deletions(-) diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index f25fb755f..19e344dbf 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -1045,7 +1045,7 @@ pub mod pallet { /// Emits `SharesDeposited` event for the first farm entry /// Emits `SharesRedeposited` event for each farm entry after the first one #[pallet::call_index(17)] - #[pallet::weight(::WeightInfo::add_liquidity_and_join_farms(farm_entries.len() as u32))]//Same benchmark as add_liquidity_and_join_farms since it's the same logic + #[pallet::weight(::WeightInfo::add_liquidity_and_join_farms(farm_entries.len() as u32))] //Same benchmark as add_liquidity_and_join_farms since it's the same logic pub fn add_liquidity_with_limit_and_join_farms( origin: OriginFor, farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, @@ -1089,7 +1089,7 @@ pub mod pallet { pub fn add_liquidity_stableswap_omnipool_and_join_farms( origin: OriginFor, stable_pool_id: T::AssetId, - stable_asset_amounts: BoundedVec, ConstU32>, + stable_asset_amounts: BoundedVec, ConstU32>, //TODO: This sohuld be max stable asset amounts farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, ) -> DispatchResult { let who = ensure_signed(origin.clone())?; diff --git a/pallets/stableswap/src/benchmarks.rs b/pallets/stableswap/src/benchmarks.rs index c4145c7e3..b209c4209 100644 --- a/pallets/stableswap/src/benchmarks.rs +++ b/pallets/stableswap/src/benchmarks.rs @@ -19,13 +19,13 @@ use super::*; -use hydradx_traits::stableswap::AssetAmount; use frame_benchmarking::account; use frame_benchmarking::benchmarks; use frame_support::traits::EnsureOrigin; use frame_support::BoundedVec; use frame_system::{Pallet as System, RawOrigin}; use hydradx_traits::router::{PoolType, TradeExecution}; +use hydradx_traits::stableswap::AssetAmount; use orml_traits::MultiCurrency; use orml_traits::MultiCurrencyExtended; use sp_runtime::Permill; diff --git a/pallets/stableswap/src/lib.rs b/pallets/stableswap/src/lib.rs index add4966c9..733b8839b 100644 --- a/pallets/stableswap/src/lib.rs +++ b/pallets/stableswap/src/lib.rs @@ -56,7 +56,7 @@ extern crate core; use frame_support::pallet_prelude::{DispatchResult, Get}; use frame_support::{ensure, require_transactional, transactional, PalletId}; use frame_system::pallet_prelude::{BlockNumberFor, OriginFor}; -use hydradx_traits::{registry::Inspect, AccountIdFor, AMMAddLiquidity, stableswap::StableswapAddLiquidity}; +use hydradx_traits::{registry::Inspect, stableswap::StableswapAddLiquidity, AMMAddLiquidity, AccountIdFor}; pub use pallet::*; use sp_runtime::traits::{AccountIdConversion, BlockNumberProvider, Zero}; use sp_runtime::{ArithmeticError, DispatchError, Permill, SaturatedConversion}; @@ -69,9 +69,9 @@ pub mod types; pub mod weights; use crate::types::{Balance, PoolInfo, PoolState, StableswapHooks, Tradability}; -use hydradx_traits::stableswap::AssetAmount; use hydra_dx_math::stableswap::types::AssetReserve; use hydradx_traits::pools::DustRemovalAccountWhitelist; +use hydradx_traits::stableswap::AssetAmount; use orml_traits::MultiCurrency; use sp_std::collections::btree_map::BTreeMap; pub use weights::WeightInfo; @@ -1467,14 +1467,19 @@ impl Pallet { } impl StableswapAddLiquidity for Pallet { - fn add_liquidity(who: T::AccountId, pool_id: T::AssetId, assets: Vec>) -> Result { - let asset_amounts = assets.iter().map(|asset| { - AssetAmount { + fn add_liquidity( + who: T::AccountId, + pool_id: T::AssetId, + assets: Vec>, + ) -> Result { + let asset_amounts = assets + .iter() + .map(|asset| AssetAmount { asset_id: asset.asset_id, amount: asset.amount, - } - }).collect::>(); + }) + .collect::>(); Self::do_add_liquidity(&who, pool_id, &asset_amounts) } -} \ No newline at end of file +} diff --git a/pallets/stableswap/src/tests/add_liquidity.rs b/pallets/stableswap/src/tests/add_liquidity.rs index 21fd28c96..d2bff9e7e 100644 --- a/pallets/stableswap/src/tests/add_liquidity.rs +++ b/pallets/stableswap/src/tests/add_liquidity.rs @@ -1,8 +1,8 @@ use crate::tests::mock::*; -use crate::types::{PoolInfo}; -use hydradx_traits::stableswap::AssetAmount; +use crate::types::PoolInfo; use crate::{assert_balance, to_precision, Error}; use frame_support::{assert_noop, assert_ok}; +use hydradx_traits::stableswap::AssetAmount; use sp_runtime::Permill; use std::num::NonZeroU16; diff --git a/pallets/stableswap/src/tests/calculate_spot_price.rs b/pallets/stableswap/src/tests/calculate_spot_price.rs index 1ad4bf35d..4d7400f0f 100644 --- a/pallets/stableswap/src/tests/calculate_spot_price.rs +++ b/pallets/stableswap/src/tests/calculate_spot_price.rs @@ -2,11 +2,11 @@ use crate::assert_balance; use crate::tests::mock::*; -use crate::types::{PoolInfo}; -use hydradx_traits::stableswap::AssetAmount; +use crate::types::PoolInfo; use frame_support::assert_ok; use hydradx_traits::router::PoolType; use hydradx_traits::router::TradeExecution; +use hydradx_traits::stableswap::AssetAmount; use orml_traits::MultiCurrencyExtended; use proptest::prelude::ProptestConfig; use proptest::proptest; diff --git a/pallets/stableswap/src/tests/hooks.rs b/pallets/stableswap/src/tests/hooks.rs index 7885fce13..be69f70d9 100644 --- a/pallets/stableswap/src/tests/hooks.rs +++ b/pallets/stableswap/src/tests/hooks.rs @@ -1,7 +1,7 @@ use crate::tests::mock::*; use crate::types::{PoolInfo, PoolState}; -use hydradx_traits::stableswap::AssetAmount; use frame_support::assert_ok; +use hydradx_traits::stableswap::AssetAmount; use sp_runtime::Permill; use std::num::NonZeroU16; diff --git a/pallets/stableswap/src/tests/invariants.rs b/pallets/stableswap/src/tests/invariants.rs index c118fee8d..69ddb378c 100644 --- a/pallets/stableswap/src/tests/invariants.rs +++ b/pallets/stableswap/src/tests/invariants.rs @@ -1,7 +1,7 @@ use crate::tests::*; -use crate::types::{PoolInfo}; -use hydradx_traits::stableswap::AssetAmount; +use crate::types::PoolInfo; use frame_support::{assert_ok, BoundedVec}; +use hydradx_traits::stableswap::AssetAmount; use sp_runtime::{FixedU128, Permill}; use std::cmp::Ordering; use std::num::NonZeroU16; diff --git a/pallets/stableswap/src/tests/mock.rs b/pallets/stableswap/src/tests/mock.rs index 8a6ce5156..b0d4c3a9b 100644 --- a/pallets/stableswap/src/tests/mock.rs +++ b/pallets/stableswap/src/tests/mock.rs @@ -317,8 +317,8 @@ impl ExtBuilder { #[cfg(feature = "runtime-benchmarks")] use crate::types::BenchmarkHelper; use crate::types::{PoolInfo, PoolState, StableswapHooks}; -use hydradx_traits::stableswap::AssetAmount; use hydradx_traits::pools::DustRemovalAccountWhitelist; +use hydradx_traits::stableswap::AssetAmount; use hydradx_traits::{AccountIdFor, Inspect}; use sp_runtime::traits::Zero; diff --git a/pallets/stableswap/src/tests/price.rs b/pallets/stableswap/src/tests/price.rs index cb4b27870..d60a97b79 100644 --- a/pallets/stableswap/src/tests/price.rs +++ b/pallets/stableswap/src/tests/price.rs @@ -1,7 +1,7 @@ use crate::tests::*; -use crate::types::{PoolInfo}; -use hydradx_traits::stableswap::AssetAmount; +use crate::types::PoolInfo; use frame_support::assert_ok; +use hydradx_traits::stableswap::AssetAmount; use sp_runtime::{FixedU128, Permill}; use std::num::NonZeroU16; diff --git a/pallets/stableswap/src/tests/remove_liquidity.rs b/pallets/stableswap/src/tests/remove_liquidity.rs index 21336f325..244453aee 100644 --- a/pallets/stableswap/src/tests/remove_liquidity.rs +++ b/pallets/stableswap/src/tests/remove_liquidity.rs @@ -1,9 +1,9 @@ use crate::tests::mock::*; -use crate::types::{PoolInfo}; +use crate::types::PoolInfo; use crate::{assert_balance, Error, Event, Pools}; -use hydradx_traits::stableswap::AssetAmount; use frame_support::traits::Contains; use frame_support::{assert_noop, assert_ok, BoundedVec}; +use hydradx_traits::stableswap::AssetAmount; use sp_runtime::Permill; use std::num::NonZeroU16; diff --git a/pallets/stableswap/src/tests/trades.rs b/pallets/stableswap/src/tests/trades.rs index a1971a604..94703b4c3 100644 --- a/pallets/stableswap/src/tests/trades.rs +++ b/pallets/stableswap/src/tests/trades.rs @@ -1,7 +1,7 @@ use crate::tests::mock::*; -use crate::types::{PoolInfo}; -use hydradx_traits::stableswap::AssetAmount; +use crate::types::PoolInfo; use crate::{assert_balance, to_precision, Error}; +use hydradx_traits::stableswap::AssetAmount; use std::num::NonZeroU16; use frame_support::{assert_noop, assert_ok}; diff --git a/pallets/stableswap/src/trade_execution.rs b/pallets/stableswap/src/trade_execution.rs index 1466785b8..0dd0cbe44 100644 --- a/pallets/stableswap/src/trade_execution.rs +++ b/pallets/stableswap/src/trade_execution.rs @@ -1,7 +1,7 @@ -use hydradx_traits::stableswap::AssetAmount; use crate::{Balance, Config, Error, Pallet, Pools, D_ITERATIONS, Y_ITERATIONS}; use hydra_dx_math::stableswap::types::AssetReserve; use hydradx_traits::router::{ExecutorError, PoolType, TradeExecution}; +use hydradx_traits::stableswap::AssetAmount; use orml_traits::MultiCurrency; use sp_core::Get; use sp_runtime::{ArithmeticError, DispatchError, FixedU128}; diff --git a/pallets/stableswap/src/types.rs b/pallets/stableswap/src/types.rs index c1a10fc19..6cc7d0d94 100644 --- a/pallets/stableswap/src/types.rs +++ b/pallets/stableswap/src/types.rs @@ -74,7 +74,6 @@ where } } - bitflags::bitflags! { /// Indicates whether asset can be bought or sold to/from Omnipool and/or liquidity added/removed. #[derive(Encode,Decode, MaxEncodedLen, TypeInfo)] diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index d10ae8c12..5f5819b5c 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -46,6 +46,7 @@ use primitives::constants::{ use sp_runtime::{traits::Zero, ArithmeticError, DispatchError, DispatchResult, FixedPointNumber, Percent}; use crate::evm::precompiles::erc20_mapping::SetCodeForErc20Precompile; +use crate::Stableswap; use core::ops::RangeInclusive; use frame_support::{ parameter_types, @@ -58,7 +59,6 @@ use frame_support::{ }, BoundedVec, PalletId, }; -use crate::Stableswap; use frame_system::{EnsureRoot, EnsureSigned, RawOrigin}; use hydradx_traits::AMM; use orml_traits::{ diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index f41ac63c8..d99938708 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -6,12 +6,12 @@ pub mod duster; pub mod dynamic_evm_fee; pub mod multi_payment; pub mod omnipool; +pub mod omnipool_liquidity_mining; pub mod route_executor; pub mod tokens; pub mod vesting; pub mod xyk; pub mod xyk_liquidity_mining; -pub mod omnipool_liquidity_mining; use crate::{AssetLocation, AssetRegistry, EmaOracle, MultiTransactionPayment, Runtime, System, DOT_ASSET_LOCATION}; use frame_benchmarking::BenchmarkError; @@ -60,7 +60,7 @@ pub fn register_asset_with_decimals(name: Vec, deposit: Balance, decimals: u None, )) }) - .map_err(|_| ()) + .map_err(|_| ()) } pub fn register_external_asset(name: Vec) -> Result { diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index d3b1592c2..dce8bbd2c 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -20,6 +20,7 @@ use crate::*; use frame_benchmarking::{account, benchmarks, BenchmarkError}; use frame_support::assert_ok; use frame_support::storage::with_transaction; +use frame_support::traits::EnsureOrigin; use frame_support::traits::{OnFinalize, OnInitialize}; use frame_system::pallet_prelude::BlockNumberFor; use frame_system::RawOrigin; @@ -32,7 +33,6 @@ use primitives::AssetId; use sp_runtime::{traits::One, FixedU128, Permill}; use sp_runtime::{DispatchError, DispatchResult, Perquintill, TransactionOutcome}; use warehouse_liquidity_mining::LoyaltyCurve; -use frame_support::traits::EnsureOrigin; const ONE: Balance = 1_000_000_000_000; const BTC_ONE: Balance = 100_000_000; const HDX: AssetId = 0; @@ -57,10 +57,22 @@ pub const INITIAL_BALANCE: Balance = 10_000_000 * crate::benchmarking::xyk_liqui fn funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> AccountId { let account: AccountId = account(name, index, 0); //Necessary to pay ED in insufficient asset - Currencies::update_balance(RawOrigin::Root.into(), account.clone(), HDX, 500_000_000_000_000_000_000i128).unwrap(); + Currencies::update_balance( + RawOrigin::Root.into(), + account.clone(), + HDX, + 500_000_000_000_000_000_000i128, + ) + .unwrap(); for asset in assets { - Currencies::update_balance(RawOrigin::Root.into(), account.clone(), *asset, 500_000_000_000_000_000_000i128).unwrap(); + Currencies::update_balance( + RawOrigin::Root.into(), + account.clone(), + *asset, + 500_000_000_000_000_000_000i128, + ) + .unwrap(); } account } @@ -68,8 +80,20 @@ fn funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> Account fn fund_treasury() -> DispatchResult { let account = Treasury::account_id(); - Currencies::update_balance(RawOrigin::Root.into(), account.clone(), HDX, 500_000_000_000_000_000_000i128).unwrap(); - Currencies::update_balance(RawOrigin::Root.into(), account.clone(), REWARD_CURRENCY, INITIAL_BALANCE as i128).unwrap(); + Currencies::update_balance( + RawOrigin::Root.into(), + account.clone(), + HDX, + 500_000_000_000_000_000_000i128, + ) + .unwrap(); + Currencies::update_balance( + RawOrigin::Root.into(), + account.clone(), + REWARD_CURRENCY, + INITIAL_BALANCE as i128, + ) + .unwrap(); Ok(()) } @@ -77,9 +101,9 @@ fn fund_treasury() -> DispatchResult { fn create_funded_account(name: &'static str, index: u32, balance: Balance, asset: AssetId) -> AccountId { let account: AccountId = account(name, index, 0); //Necessary to pay ED in insufficient asset - Currencies::update_balance(RawOrigin::Root.into(), account.clone(),DAI, INITIAL_BALANCE as i128).unwrap(); - Currencies::update_balance(RawOrigin::Root.into(), account.clone(),LRNA, INITIAL_BALANCE as i128).unwrap(); - Currencies::update_balance(RawOrigin::Root.into(), account.clone(),0, INITIAL_BALANCE as i128).unwrap(); + Currencies::update_balance(RawOrigin::Root.into(), account.clone(), DAI, INITIAL_BALANCE as i128).unwrap(); + Currencies::update_balance(RawOrigin::Root.into(), account.clone(), LRNA, INITIAL_BALANCE as i128).unwrap(); + Currencies::update_balance(RawOrigin::Root.into(), account.clone(), 0, INITIAL_BALANCE as i128).unwrap(); assert_ok!(Currencies::update_balance( RawOrigin::Root.into(), account.clone(), @@ -237,7 +261,12 @@ fn initialize_omnipool(additional_asset: Option) -> DispatchResult { )?; if let Some(asset_id) = additional_asset { - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), asset_id.into(), (token_amount * 100) as Amount)?; + Currencies::update_balance( + RawOrigin::Root.into(), + acc.clone(), + asset_id.into(), + (token_amount * 100) as Amount, + )?; Omnipool::add_token( RawOrigin::Root.into(), asset_id.into(), @@ -247,7 +276,6 @@ fn initialize_omnipool(additional_asset: Option) -> DispatchResult { )?; } - //NOTE: This is necessary for oracle to provide price. set_period(10); @@ -290,7 +318,9 @@ fn set_period(to: u32) { as OnFinalize>>::on_finalize(b); as frame_support::traits::OnFinalize>>::on_finalize(b); - as OnInitialize>>::on_initialize(b + 1_u32); + as OnInitialize>>::on_initialize( + b + 1_u32, + ); as OnInitialize>>::on_initialize(b + 1_u32); as frame_support::traits::OnInitialize>>::on_initialize(b + 1_u32); @@ -837,7 +867,7 @@ runtime_benchmarks! { let deposit_id = 1; initialize_omnipool(Some(pool_id))?; - + CircuitBreaker::set_add_liquidity_limit(RuntimeOrigin::root(), pool_id, Some((99, 100))).unwrap(); let liquidity_added = 100_000_000_000_000_u128; let omni_lp_provider: AccountId = create_funded_account("provider", 1, liquidity_added * 10, pool_id); diff --git a/traits/src/lib.rs b/traits/src/lib.rs index f5f0bb394..b866b0eb0 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -288,7 +288,6 @@ pub trait AMMAddLiquidity { ) -> Result; } - /// Provides account's fee payment asset pub trait AccountFeeCurrency { type AssetId; diff --git a/traits/src/stableswap.rs b/traits/src/stableswap.rs index 70d8a3cbb..10d7aa6af 100644 --- a/traits/src/stableswap.rs +++ b/traits/src/stableswap.rs @@ -4,33 +4,32 @@ use frame_support::pallet_prelude::TypeInfo; use sp_std::vec::Vec; pub trait StableswapAddLiquidity { - fn add_liquidity( - who: AccountId, - pool_id: AssetId, - assets_amounts: Vec> - ) -> Result; + fn add_liquidity( + who: AccountId, + pool_id: AssetId, + assets_amounts: Vec>, + ) -> Result; } - #[derive(Debug, Clone, Encode, Decode, PartialEq, Eq, TypeInfo, Default)] pub struct AssetAmount { - pub asset_id: AssetId, - pub amount: u128, + pub asset_id: AssetId, + pub amount: u128, } impl AssetAmount { - pub fn new(asset_id: AssetId, amount: u128) -> Self { - Self { asset_id, amount } - } + pub fn new(asset_id: AssetId, amount: u128) -> Self { + Self { asset_id, amount } + } } impl From> for u128 { - fn from(value: AssetAmount) -> Self { - value.amount - } + fn from(value: AssetAmount) -> Self { + value.amount + } } impl From<&AssetAmount> for u128 { - fn from(value: &AssetAmount) -> Self { - value.amount - } -} \ No newline at end of file + fn from(value: &AssetAmount) -> Self { + value.amount + } +} From 41b244871ad1dd2476b88370d446339387b7ffbb Mon Sep 17 00:00:00 2001 From: dmoka Date: Sun, 1 Dec 2024 20:05:23 +0100 Subject: [PATCH 12/36] regenerate benchmark for add liq stable omni and join farms extnrisc --- pallets/omnipool-liquidity-mining/src/lib.rs | 8 +- .../omnipool-liquidity-mining/src/weights.rs | 79 +++++++ .../benchmarking/omnipool_liquidity_mining.rs | 6 +- .../pallet_omnipool_liquidity_mining.rs | 219 ++++++++++++------ 4 files changed, 238 insertions(+), 74 deletions(-) diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index 19e344dbf..84636e8eb 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -1015,7 +1015,7 @@ pub mod pallet { /// * `DepositDestroyed` if the deposit is fully withdrawn /// #[pallet::call_index(16)] - #[pallet::weight(::WeightInfo::exit_farms(yield_farm_ids.len() as u32))] + #[pallet::weight(::WeightInfo::exit_farms(yield_farm_ids.len() as u32))]//TODO: benchmark pub fn exit_farms_and_remove_liquidity( origin: OriginFor, deposit_id: DepositId, @@ -1024,7 +1024,7 @@ pub mod pallet { for yield_farm_id in yield_farm_ids.iter() { Self::withdraw_shares(origin.clone(), deposit_id, *yield_farm_id)?; } - + //TODO: finish let position_id = OmniPositionId::::get(deposit_id) .defensive_ok_or::>(InconsistentStateError::MissingLpPosition.into())?; @@ -1085,11 +1085,11 @@ pub mod pallet { /// Emits `SharesRedeposited` event for each farm entry after the first one /// #[pallet::call_index(18)] - #[pallet::weight(::WeightInfo::exit_farms(farm_entries.len() as u32))] //TODO: rebenchmark + #[pallet::weight(::WeightInfo::add_liquidity_stableswap_omnipool_and_join_farms(farm_entries.len() as u32))] pub fn add_liquidity_stableswap_omnipool_and_join_farms( origin: OriginFor, stable_pool_id: T::AssetId, - stable_asset_amounts: BoundedVec, ConstU32>, //TODO: This sohuld be max stable asset amounts + stable_asset_amounts: BoundedVec, ConstU32>, farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, ) -> DispatchResult { let who = ensure_signed(origin.clone())?; diff --git a/pallets/omnipool-liquidity-mining/src/weights.rs b/pallets/omnipool-liquidity-mining/src/weights.rs index 12541055e..54e94aad1 100644 --- a/pallets/omnipool-liquidity-mining/src/weights.rs +++ b/pallets/omnipool-liquidity-mining/src/weights.rs @@ -64,6 +64,7 @@ pub trait WeightInfo { fn withdraw_shares() -> Weight; fn join_farms(c: u32) -> Weight; fn add_liquidity_and_join_farms(c: u32) -> Weight; + fn add_liquidity_stableswap_omnipool_and_join_farms(c: u32) -> Weight; fn exit_farms(c: u32) -> Weight; } @@ -486,4 +487,82 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().writes((12_u64).saturating_mul(c.into()))) .saturating_add(Weight::from_parts(0, 5242).saturating_mul(c.into())) } + + /// Storage: `Stableswap::Pools` (r:1 w:0) + /// Proof: `Stableswap::Pools` (`max_values`: None, `max_size`: Some(57), added: 2532, mode: `MaxEncodedLen`) + /// Storage: `Stableswap::AssetTradability` (r:5 w:0) + /// Proof: `Stableswap::AssetTradability` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:8 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:13 w:13) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `Tokens::TotalIssuance` (r:2 w:2) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:7 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:7 w:7) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Router::SkipEd` (r:1 w:0) + /// Proof: `Router::SkipEd` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `EmaOracle::Accumulator` (r:1 w:1) + /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) + /// Storage: `Omnipool::Assets` (r:1 w:1) + /// Proof: `Omnipool::Assets` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) + /// Storage: `EmaOracle::Oracles` (r:5 w:0) + /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) + /// Storage: `Omnipool::HubAssetImbalance` (r:1 w:1) + /// Proof: `Omnipool::HubAssetImbalance` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) + /// Storage: `Omnipool::NextPositionId` (r:1 w:1) + /// Proof: `Omnipool::NextPositionId` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:2 w:2) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:2 w:2) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(190), added: 2665, mode: `MaxEncodedLen`) + /// Storage: `Uniques::CollectionMaxSupply` (r:2 w:0) + /// Proof: `Uniques::CollectionMaxSupply` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Storage: `CircuitBreaker::LiquidityAddLimitPerAsset` (r:1 w:0) + /// Proof: `CircuitBreaker::LiquidityAddLimitPerAsset` (`max_values`: None, `max_size`: Some(29), added: 2504, mode: `MaxEncodedLen`) + /// Storage: `CircuitBreaker::AllowedAddLiquidityAmountPerAsset` (r:1 w:1) + /// Proof: `CircuitBreaker::AllowedAddLiquidityAmountPerAsset` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `CircuitBreaker::LiquidityRemoveLimitPerAsset` (r:1 w:0) + /// Proof: `CircuitBreaker::LiquidityRemoveLimitPerAsset` (`max_values`: None, `max_size`: Some(29), added: 2504, mode: `MaxEncodedLen`) + /// Storage: `CircuitBreaker::AllowedRemoveLiquidityAmountPerAsset` (r:1 w:1) + /// Proof: `CircuitBreaker::AllowedRemoveLiquidityAmountPerAsset` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::YieldFarm` (r:5 w:5) + /// Proof: `OmnipoolWarehouseLM::YieldFarm` (`max_values`: None, `max_size`: Some(198), added: 2673, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:5 w:5) + /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::DepositSequencer` (r:1 w:1) + /// Proof: `OmnipoolWarehouseLM::DepositSequencer` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:3) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(112), added: 2587, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ItemPriceOf` (r:0 w:1) + /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(113), added: 2588, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolLiquidityMining::OmniPositionId` (r:0 w:1) + /// Proof: `OmnipoolLiquidityMining::OmniPositionId` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Omnipool::Positions` (r:0 w:1) + /// Proof: `Omnipool::Positions` (`max_values`: None, `max_size`: Some(100), added: 2575, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::Deposit` (r:0 w:1) + /// Proof: `OmnipoolWarehouseLM::Deposit` (`max_values`: None, `max_size`: Some(385), added: 2860, mode: `MaxEncodedLen`) + /// The range of component `c` is `[1, 5]`. + fn add_liquidity_stableswap_omnipool_and_join_farms(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `22068 + c * (507 ±0)` + // Estimated: `34569 + c * (2680 ±0)` + // Minimum execution time: 1_247_561_000 picoseconds. + Weight::from_parts(1_200_125_260, 34569) + // Standard Error: 863_778 + .saturating_add(Weight::from_parts(91_357_644, 0).saturating_mul(c.into())) + .saturating_add(RocksDbWeight::get().reads(62_u64)) + .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(c.into()))) + .saturating_add(RocksDbWeight::get().writes(35_u64)) + .saturating_add(RocksDbWeight::get().writes((3_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 2680).saturating_mul(c.into())) + } } diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index dce8bbd2c..dae5703c5 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -15,9 +15,9 @@ #![cfg(feature = "runtime-benchmarks")] -use crate::benchmarking::{register_asset, register_asset_with_decimals, register_external_asset}; +use crate::benchmarking::{register_asset, register_asset_with_decimals}; use crate::*; -use frame_benchmarking::{account, benchmarks, BenchmarkError}; +use frame_benchmarking::{account, BenchmarkError}; use frame_support::assert_ok; use frame_support::storage::with_transaction; use frame_support::traits::EnsureOrigin; @@ -28,7 +28,6 @@ use hydradx_traits::liquidity_mining::{GlobalFarmId, YieldFarmId}; use hydradx_traits::registry::{AssetKind, Create}; use hydradx_traits::stableswap::AssetAmount; use orml_benchmarking::runtime_benchmarks; -use orml_traits::MultiCurrencyExtended; use primitives::AssetId; use sp_runtime::{traits::One, FixedU128, Permill}; use sp_runtime::{DispatchError, DispatchResult, Perquintill, TransactionOutcome}; @@ -50,7 +49,6 @@ fn fund(to: AccountId, currency: AssetId, amount: Balance) -> DispatchResult { Currencies::deposit(currency, &to, amount) } -const SEED: u32 = 0; pub const INITIAL_BALANCE: Balance = 10_000_000 * crate::benchmarking::xyk_liquidity_mining::ONE; //TODO: this is use in many places, refactor diff --git a/runtime/hydradx/src/weights/pallet_omnipool_liquidity_mining.rs b/runtime/hydradx/src/weights/pallet_omnipool_liquidity_mining.rs index d0798dee0..5413daa42 100644 --- a/runtime/hydradx/src/weights/pallet_omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/weights/pallet_omnipool_liquidity_mining.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for `pallet_omnipool_liquidity_mining` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-11-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-12-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` @@ -53,22 +53,32 @@ pub struct HydraWeight(PhantomData); impl pallet_omnipool_liquidity_mining::WeightInfo for HydraWeight { /// Storage: `AssetRegistry::Assets` (r:2 w:0) /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:2 w:2) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `OmnipoolWarehouseLM::FarmSequencer` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::FarmSequencer` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Duster::AccountBlacklist` (r:0 w:1) + /// Storage: `Router::SkipEd` (r:1 w:0) + /// Proof: `Router::SkipEd` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:1) /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:0 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) fn create_global_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `557` + // Measured: `2927` // Estimated: `6196` - // Minimum execution time: 80_478_000 picoseconds. - Weight::from_parts(81_067_000, 6196) - .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Minimum execution time: 108_804_000 picoseconds. + Weight::from_parts(109_967_000, 6196) + .saturating_add(T::DbWeight::get().reads(12_u64)) + .saturating_add(T::DbWeight::get().writes(6_u64)) } /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) @@ -76,10 +86,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn update_global_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `573` + // Measured: `3644` // Estimated: `3670` - // Minimum execution time: 21_983_000 picoseconds. - Weight::from_parts(22_223_000, 3670) + // Minimum execution time: 39_051_000 picoseconds. + Weight::from_parts(39_347_000, 3670) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -91,10 +101,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) fn terminate_global_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `964` + // Measured: `5476` // Estimated: `6196` - // Minimum execution time: 79_330_000 picoseconds. - Weight::from_parts(80_136_000, 6196) + // Minimum execution time: 101_287_000 picoseconds. + Weight::from_parts(102_290_000, 6196) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -116,10 +126,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `OmnipoolWarehouseLM::YieldFarm` (`max_values`: None, `max_size`: Some(198), added: 2673, mode: `MaxEncodedLen`) fn create_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `2403` + // Measured: `6716` // Estimated: `6294` - // Minimum execution time: 124_419_000 picoseconds. - Weight::from_parts(125_396_000, 6294) + // Minimum execution time: 150_403_000 picoseconds. + Weight::from_parts(151_610_000, 6294) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -139,10 +149,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn update_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `2573` + // Measured: `7222` // Estimated: `6294` - // Minimum execution time: 127_834_000 picoseconds. - Weight::from_parts(128_532_000, 6294) + // Minimum execution time: 154_461_000 picoseconds. + Weight::from_parts(155_496_000, 6294) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -160,10 +170,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn stop_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `2179` + // Measured: `6828` // Estimated: `6294` - // Minimum execution time: 120_676_000 picoseconds. - Weight::from_parts(121_462_000, 6294) + // Minimum execution time: 149_416_000 picoseconds. + Weight::from_parts(150_646_000, 6294) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -183,10 +193,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn resume_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `2609` + // Measured: `7339` // Estimated: `6294` - // Minimum execution time: 125_235_000 picoseconds. - Weight::from_parts(126_052_000, 6294) + // Minimum execution time: 152_894_000 picoseconds. + Weight::from_parts(153_877_000, 6294) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -200,10 +210,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn terminate_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `924` + // Measured: `5877` // Estimated: `6196` - // Minimum execution time: 75_314_000 picoseconds. - Weight::from_parts(76_282_000, 6196) + // Minimum execution time: 97_304_000 picoseconds. + Weight::from_parts(97_707_000, 6196) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -239,10 +249,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `OmnipoolWarehouseLM::Deposit` (`max_values`: None, `max_size`: Some(385), added: 2860, mode: `MaxEncodedLen`) fn deposit_shares() -> Weight { // Proof Size summary in bytes: - // Measured: `4210` + // Measured: `10092` // Estimated: `11598` - // Minimum execution time: 210_850_000 picoseconds. - Weight::from_parts(212_191_000, 11598) + // Minimum execution time: 238_913_000 picoseconds. + Weight::from_parts(240_368_000, 11598) .saturating_add(T::DbWeight::get().reads(17_u64)) .saturating_add(T::DbWeight::get().writes(14_u64)) } @@ -268,19 +278,19 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn redeposit_shares() -> Weight { // Proof Size summary in bytes: - // Measured: `4447` + // Measured: `13014` // Estimated: `11598` - // Minimum execution time: 174_509_000 picoseconds. - Weight::from_parts(175_641_000, 11598) + // Minimum execution time: 201_956_000 picoseconds. + Weight::from_parts(203_655_000, 11598) .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } fn claim_rewards() -> Weight { // Proof Size summary in bytes: - // Measured: `0` + // Measured: `679` // Estimated: `0` - // Minimum execution time: 4_300_000 picoseconds. - Weight::from_parts(4_379_000, 0) + // Minimum execution time: 9_614_000 picoseconds. + Weight::from_parts(9_805_000, 0) } /// Storage: `Uniques::Asset` (r:2 w:2) /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) @@ -308,10 +318,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(113), added: 2588, mode: `MaxEncodedLen`) fn withdraw_shares() -> Weight { // Proof Size summary in bytes: - // Measured: `4039` + // Measured: `8796` // Estimated: `8799` - // Minimum execution time: 256_812_000 picoseconds. - Weight::from_parts(258_937_000, 8799) + // Minimum execution time: 290_740_000 picoseconds. + Weight::from_parts(298_216_000, 8799) .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(15_u64)) } @@ -348,21 +358,21 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// The range of component `c` is `[1, 5]`. fn join_farms(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `4182 + c * (474 ±0)` + // Measured: `18180 + c * (507 ±0)` // Estimated: `11598 + c * (2680 ±0)` - // Minimum execution time: 213_369_000 picoseconds. - Weight::from_parts(118_815_338, 11598) - // Standard Error: 53_827 - .saturating_add(Weight::from_parts(97_773_366, 0).saturating_mul(c.into())) + // Minimum execution time: 242_801_000 picoseconds. + Weight::from_parts(143_876_531, 11598) + // Standard Error: 56_986 + .saturating_add(Weight::from_parts(102_112_481, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(14_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(c.into()))) .saturating_add(T::DbWeight::get().writes(11_u64)) .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(c.into()))) .saturating_add(Weight::from_parts(0, 2680).saturating_mul(c.into())) } - /// Storage: `AssetRegistry::Assets` (r:3 w:0) + /// Storage: `AssetRegistry::Assets` (r:4 w:0) /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:3 w:3) + /// Storage: `Tokens::Accounts` (r:4 w:3) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `Omnipool::Assets` (r:1 w:1) /// Proof: `Omnipool::Assets` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) @@ -386,6 +396,8 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:7 w:7) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) @@ -396,7 +408,7 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `CircuitBreaker::AllowedAddLiquidityAmountPerAsset` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) /// Storage: `CircuitBreaker::LiquidityRemoveLimitPerAsset` (r:1 w:0) /// Proof: `CircuitBreaker::LiquidityRemoveLimitPerAsset` (`max_values`: None, `max_size`: Some(29), added: 2504, mode: `MaxEncodedLen`) - /// Storage: `CircuitBreaker::AllowedRemoveLiquidityAmountPerAsset` (r:1 w:0) + /// Storage: `CircuitBreaker::AllowedRemoveLiquidityAmountPerAsset` (r:1 w:1) /// Proof: `CircuitBreaker::AllowedRemoveLiquidityAmountPerAsset` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) /// Storage: `OmnipoolWarehouseLM::YieldFarm` (r:5 w:5) /// Proof: `OmnipoolWarehouseLM::YieldFarm` (`max_values`: None, `max_size`: Some(198), added: 2673, mode: `MaxEncodedLen`) @@ -404,8 +416,6 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) /// Storage: `OmnipoolWarehouseLM::DepositSequencer` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::DepositSequencer` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:0 w:1) - /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) /// Storage: `Uniques::Account` (r:0 w:3) /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(112), added: 2587, mode: `MaxEncodedLen`) /// Storage: `Uniques::ItemPriceOf` (r:0 w:1) @@ -419,13 +429,13 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// The range of component `c` is `[1, 5]`. fn add_liquidity_and_join_farms(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `5648 + c * (474 ±0)` + // Measured: `19713 + c * (507 ±0)` // Estimated: `14250 + c * (2680 ±0)` - // Minimum execution time: 402_449_000 picoseconds. - Weight::from_parts(304_741_540, 14250) - // Standard Error: 95_639 - .saturating_add(Weight::from_parts(100_600_771, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(33_u64)) + // Minimum execution time: 450_627_000 picoseconds. + Weight::from_parts(349_467_292, 14250) + // Standard Error: 100_882 + .saturating_add(Weight::from_parts(105_492_164, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(36_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(c.into()))) .saturating_add(T::DbWeight::get().writes(24_u64)) .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(c.into()))) @@ -445,7 +455,7 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:8 w:7) + /// Storage: `System::Account` (r:7 w:7) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:2 w:0) /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) @@ -458,16 +468,93 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// The range of component `c` is `[1, 5]`. fn exit_farms(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `3689 + c * (486 ±0)` - // Estimated: `8799 + c * (2680 ±0)` - // Minimum execution time: 218_233_000 picoseconds. - Weight::from_parts(63_160_481, 8799) - // Standard Error: 259_281 - .saturating_add(Weight::from_parts(156_947_806, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(11_u64)) + // Measured: `10759 + c * (518 ±0)` + // Estimated: `6294 + c * (2680 ±0)` + // Minimum execution time: 247_897_000 picoseconds. + Weight::from_parts(85_622_107, 6294) + // Standard Error: 252_234 + .saturating_add(Weight::from_parts(164_088_535, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(10_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(c.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(c.into()))) .saturating_add(Weight::from_parts(0, 2680).saturating_mul(c.into())) } + /// Storage: `Stableswap::Pools` (r:1 w:0) + /// Proof: `Stableswap::Pools` (`max_values`: None, `max_size`: Some(57), added: 2532, mode: `MaxEncodedLen`) + /// Storage: `Stableswap::AssetTradability` (r:5 w:0) + /// Proof: `Stableswap::AssetTradability` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:8 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:13 w:13) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `Tokens::TotalIssuance` (r:2 w:2) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:7 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:7 w:7) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Router::SkipEd` (r:1 w:0) + /// Proof: `Router::SkipEd` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `EmaOracle::Accumulator` (r:1 w:1) + /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) + /// Storage: `Omnipool::Assets` (r:1 w:1) + /// Proof: `Omnipool::Assets` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) + /// Storage: `EmaOracle::Oracles` (r:5 w:0) + /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) + /// Storage: `Omnipool::HubAssetImbalance` (r:1 w:1) + /// Proof: `Omnipool::HubAssetImbalance` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) + /// Storage: `Omnipool::NextPositionId` (r:1 w:1) + /// Proof: `Omnipool::NextPositionId` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:2 w:2) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:2 w:2) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(190), added: 2665, mode: `MaxEncodedLen`) + /// Storage: `Uniques::CollectionMaxSupply` (r:2 w:0) + /// Proof: `Uniques::CollectionMaxSupply` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Storage: `CircuitBreaker::LiquidityAddLimitPerAsset` (r:1 w:0) + /// Proof: `CircuitBreaker::LiquidityAddLimitPerAsset` (`max_values`: None, `max_size`: Some(29), added: 2504, mode: `MaxEncodedLen`) + /// Storage: `CircuitBreaker::AllowedAddLiquidityAmountPerAsset` (r:1 w:1) + /// Proof: `CircuitBreaker::AllowedAddLiquidityAmountPerAsset` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `CircuitBreaker::LiquidityRemoveLimitPerAsset` (r:1 w:0) + /// Proof: `CircuitBreaker::LiquidityRemoveLimitPerAsset` (`max_values`: None, `max_size`: Some(29), added: 2504, mode: `MaxEncodedLen`) + /// Storage: `CircuitBreaker::AllowedRemoveLiquidityAmountPerAsset` (r:1 w:1) + /// Proof: `CircuitBreaker::AllowedRemoveLiquidityAmountPerAsset` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::YieldFarm` (r:5 w:5) + /// Proof: `OmnipoolWarehouseLM::YieldFarm` (`max_values`: None, `max_size`: Some(198), added: 2673, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:5 w:5) + /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::DepositSequencer` (r:1 w:1) + /// Proof: `OmnipoolWarehouseLM::DepositSequencer` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:3) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(112), added: 2587, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ItemPriceOf` (r:0 w:1) + /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(113), added: 2588, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolLiquidityMining::OmniPositionId` (r:0 w:1) + /// Proof: `OmnipoolLiquidityMining::OmniPositionId` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Omnipool::Positions` (r:0 w:1) + /// Proof: `Omnipool::Positions` (`max_values`: None, `max_size`: Some(100), added: 2575, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::Deposit` (r:0 w:1) + /// Proof: `OmnipoolWarehouseLM::Deposit` (`max_values`: None, `max_size`: Some(385), added: 2860, mode: `MaxEncodedLen`) + /// The range of component `c` is `[1, 5]`. + fn add_liquidity_stableswap_omnipool_and_join_farms(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `22068 + c * (507 ±0)` + // Estimated: `34569 + c * (2680 ±0)` + // Minimum execution time: 1_600_568_000 picoseconds. + Weight::from_parts(1_514_241_156, 34569) + // Standard Error: 366_013 + .saturating_add(Weight::from_parts(104_749_719, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(62_u64)) + .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(35_u64)) + .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 2680).saturating_mul(c.into())) + } } \ No newline at end of file From e4517bb1fd8f05373a582a157ebc4a09c2a1d8ee Mon Sep 17 00:00:00 2001 From: dmoka Date: Sun, 1 Dec 2024 20:18:02 +0100 Subject: [PATCH 13/36] use bounded vec for stableswap extrinsic --- pallets/stableswap/src/lib.rs | 6 ++--- pallets/stableswap/src/tests/add_liquidity.rs | 22 +++++++++---------- pallets/stableswap/src/tests/hooks.rs | 2 +- pallets/stableswap/src/tests/invariants.rs | 10 ++++----- pallets/stableswap/src/tests/mock.rs | 2 +- pallets/stableswap/src/tests/price.rs | 4 ++-- .../stableswap/src/tests/remove_liquidity.rs | 18 +++++++-------- pallets/stableswap/src/trade_execution.rs | 19 ++++++++-------- 8 files changed, 41 insertions(+), 42 deletions(-) diff --git a/pallets/stableswap/src/lib.rs b/pallets/stableswap/src/lib.rs index 733b8839b..3c3015204 100644 --- a/pallets/stableswap/src/lib.rs +++ b/pallets/stableswap/src/lib.rs @@ -56,7 +56,7 @@ extern crate core; use frame_support::pallet_prelude::{DispatchResult, Get}; use frame_support::{ensure, require_transactional, transactional, PalletId}; use frame_system::pallet_prelude::{BlockNumberFor, OriginFor}; -use hydradx_traits::{registry::Inspect, stableswap::StableswapAddLiquidity, AMMAddLiquidity, AccountIdFor}; +use hydradx_traits::{registry::Inspect, stableswap::StableswapAddLiquidity, AccountIdFor}; pub use pallet::*; use sp_runtime::traits::{AccountIdConversion, BlockNumberProvider, Zero}; use sp_runtime::{ArithmeticError, DispatchError, Permill, SaturatedConversion}; @@ -476,7 +476,7 @@ pub mod pallet { pub fn add_liquidity( origin: OriginFor, pool_id: T::AssetId, - assets: Vec>, + assets: BoundedVec, ConstU32>, ) -> DispatchResult { let who = ensure_signed(origin)?; @@ -1186,7 +1186,7 @@ impl Pallet { pool_id, who: who.clone(), shares: share_amount, - assets: assets.clone().to_vec(), + assets: assets.to_vec(), }); Ok(share_amount) diff --git a/pallets/stableswap/src/tests/add_liquidity.rs b/pallets/stableswap/src/tests/add_liquidity.rs index d2bff9e7e..c9872d9f3 100644 --- a/pallets/stableswap/src/tests/add_liquidity.rs +++ b/pallets/stableswap/src/tests/add_liquidity.rs @@ -43,7 +43,7 @@ fn add_initial_liquidity_should_work_when_called_first_time() { vec![ AssetAmount::new(asset_a, initial_liquidity_amount), AssetAmount::new(asset_b, initial_liquidity_amount), - ] + ].try_into().unwrap() )); assert_balance!(BOB, asset_a, 100 * ONE); @@ -92,7 +92,7 @@ fn add_initial_liquidity_should_fail_when_lp_has_insufficient_balance() { vec![ AssetAmount::new(asset_a, initial_liquidity_amount), AssetAmount::new(asset_b, initial_liquidity_amount), - ] + ].try_into().unwrap() ), Error::::InsufficientBalance ); @@ -150,7 +150,7 @@ fn add_liquidity_should_work_when_initial_liquidity_has_been_provided() { vec![ AssetAmount::new(asset_a, amount_added), AssetAmount::new(asset_b, amount_added), - ] + ].try_into().unwrap() )); assert_balance!(BOB, asset_a, 100 * ONE); @@ -207,7 +207,7 @@ fn add_liquidity_should_work_when_order_is_not_sorted() { vec![ AssetAmount::new(asset_b, amount_added), AssetAmount::new(asset_a, amount_added), - ] + ].try_into().unwrap() )); assert_balance!(BOB, asset_a, 100 * ONE); @@ -262,7 +262,7 @@ fn add_liquidity_should_fail_when_providing_insufficient_liquidity() { vec![ AssetAmount::new(asset_b, amount_added), AssetAmount::new(asset_a, amount_added), - ] + ].try_into().unwrap() ), Error::::InsufficientTradingAmount ); @@ -316,7 +316,7 @@ fn add_liquidity_should_work_when_providing_one_asset_only() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount_added),] + vec![AssetAmount::new(asset_a, amount_added),].try_into().unwrap() )); }); } @@ -375,7 +375,7 @@ fn add_liquidity_should_fail_when_providing_one_asset_not_in_pool() { vec![ AssetAmount::new(asset_a, amount_added), AssetAmount::new(asset_e, amount_added), - ] + ].try_into().unwrap() ), Error::::AssetNotInPool ); @@ -425,7 +425,7 @@ fn add_liquidity_should_fail_when_provided_list_contains_same_assets() { vec![ AssetAmount::new(asset_a, amount_added), AssetAmount::new(asset_a, amount_added), - ] + ].try_into().unwrap() ), Error::::IncorrectAssets ); @@ -471,7 +471,7 @@ fn add_initial_liquidity_should_work_when_asset_have_different_decimals() { vec![ AssetAmount::new(asset_a, initial_liquidity_amount_a), AssetAmount::new(asset_b, initial_liquidity_amount_b), - ] + ].try_into().unwrap() )); assert_balance!(BOB, asset_a, to_precision!(100, dec_a)); @@ -526,7 +526,7 @@ fn add_liquidity_should_work_correctly() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount),] + vec![AssetAmount::new(asset_a, amount),].try_into().unwrap() )); let received = Tokens::free_balance(pool_id, &BOB); assert_eq!(received, 1947597621401945851); @@ -576,7 +576,7 @@ fn add_liquidity_should_work_correctly_when_fee_is_applied() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount),] + vec![AssetAmount::new(asset_a, amount),].try_into().unwrap() )); let received = Tokens::free_balance(pool_id, &BOB); assert_eq!(received, 1947487201901031408); diff --git a/pallets/stableswap/src/tests/hooks.rs b/pallets/stableswap/src/tests/hooks.rs index be69f70d9..a8b983f0a 100644 --- a/pallets/stableswap/src/tests/hooks.rs +++ b/pallets/stableswap/src/tests/hooks.rs @@ -48,7 +48,7 @@ fn add_liquidity_should_provide_correct_values_in_the_hook() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount)], + vec![AssetAmount::new(asset_a, amount)].try_into().unwrap(), )); let (p, state) = last_liquidity_changed_hook_state().unwrap(); assert_eq!(p, pool_id); diff --git a/pallets/stableswap/src/tests/invariants.rs b/pallets/stableswap/src/tests/invariants.rs index 69ddb378c..ec69f6bcf 100644 --- a/pallets/stableswap/src/tests/invariants.rs +++ b/pallets/stableswap/src/tests/invariants.rs @@ -94,7 +94,7 @@ proptest! { pool_id, vec![ AssetAmount::new(asset_a, added_liquidity), - ] + ].try_into().unwrap() )); let final_shares = Tokens::total_issuance(pool_id); let delta_s = final_shares - initial_shares; @@ -167,7 +167,7 @@ proptest! { pool_id, vec![ AssetAmount::new(asset_a, added_liquidity), - ] + ].try_into().unwrap() )); let final_shares = Tokens::total_issuance(pool_id); let delta_s = final_shares - initial_shares; @@ -843,7 +843,7 @@ proptest! { pool_id, vec![ AssetAmount::new(asset_a, added_liquidity), - ] + ].try_into().unwrap() )); let final_shares = Tokens::total_issuance(pool_id); let delta_s = final_shares - initial_shares; @@ -945,7 +945,7 @@ proptest! { pool_id, vec![ AssetAmount::new(asset_a, added_liquidity), - ] + ].try_into().unwrap() )); let final_shares = Tokens::total_issuance(pool_id); let delta_s = final_shares - initial_shares; @@ -1264,7 +1264,7 @@ proptest! { pool_id, vec![ AssetAmount::new(asset_a, added_liquidity), - ] + ].try_into().unwrap() )); let final_shares = Tokens::total_issuance(pool_id); let delta_s = final_shares - initial_shares; diff --git a/pallets/stableswap/src/tests/mock.rs b/pallets/stableswap/src/tests/mock.rs index b0d4c3a9b..e35c689d8 100644 --- a/pallets/stableswap/src/tests/mock.rs +++ b/pallets/stableswap/src/tests/mock.rs @@ -304,7 +304,7 @@ impl ExtBuilder { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(initial_liquid.account), pool_id, - initial_liquid.assets + initial_liquid.assets.try_into().unwrap() )); } } diff --git a/pallets/stableswap/src/tests/price.rs b/pallets/stableswap/src/tests/price.rs index d60a97b79..338a3136a 100644 --- a/pallets/stableswap/src/tests/price.rs +++ b/pallets/stableswap/src/tests/price.rs @@ -182,7 +182,7 @@ fn test_share_price_in_add_remove_liquidity() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount)], + vec![AssetAmount::new(asset_a, amount)].try_into().unwrap(), )); let final_shares = Tokens::total_issuance(pool_id); @@ -327,7 +327,7 @@ fn test_share_price_case() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount)], + vec![AssetAmount::new(asset_a, amount)].try_into().unwrap(), )); let final_shares = Tokens::total_issuance(pool_id); diff --git a/pallets/stableswap/src/tests/remove_liquidity.rs b/pallets/stableswap/src/tests/remove_liquidity.rs index 244453aee..6243bfee4 100644 --- a/pallets/stableswap/src/tests/remove_liquidity.rs +++ b/pallets/stableswap/src/tests/remove_liquidity.rs @@ -53,7 +53,7 @@ fn remove_liquidity_should_work_when_withdrawing_all_shares() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount_added),] + vec![AssetAmount::new(asset_a, amount_added),].try_into().unwrap() )); let shares = Tokens::free_balance(pool_id, &BOB); @@ -121,7 +121,7 @@ fn remove_liquidity_should_apply_fee_when_withdrawing_all_shares() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount_added)] + vec![AssetAmount::new(asset_a, amount_added)].try_into().unwrap() )); let shares = Tokens::free_balance(pool_id, &BOB); @@ -246,7 +246,7 @@ fn remove_liquidity_should_fail_when_requested_asset_not_in_pool() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount_added)] + vec![AssetAmount::new(asset_a, amount_added)].try_into().unwrap() )); let shares = Tokens::free_balance(pool_id, &BOB); @@ -302,7 +302,7 @@ fn remove_liquidity_should_fail_when_remaining_shares_below_min_liquidity() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount_added)] + vec![AssetAmount::new(asset_a, amount_added)].try_into().unwrap() )); let shares = Tokens::free_balance(pool_id, &BOB); @@ -370,7 +370,7 @@ fn verify_remove_liquidity_against_research_impl() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount_added)] + vec![AssetAmount::new(asset_a, amount_added)].try_into().unwrap() )); let shares = Tokens::free_balance(pool_id, &BOB); @@ -436,7 +436,7 @@ fn remove_liquidity_fail_when_desired_min_limit_is_not_reached() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount_added)] + vec![AssetAmount::new(asset_a, amount_added)].try_into().unwrap() )); let shares = Tokens::free_balance(pool_id, &BOB); @@ -496,7 +496,7 @@ fn scenario_add_remove_with_different_decimals() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_c, 20 * one_c)] + vec![AssetAmount::new(asset_c, 20 * one_c)].try_into().unwrap() )); let shares = Tokens::free_balance(pool_id, &BOB); @@ -1041,7 +1041,7 @@ fn remove_multi_asset_liquidity_should_work_when_withdrawing_some_shares() { assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount_added),] + vec![AssetAmount::new(asset_a, amount_added),].try_into().unwrap() )); let shares = Tokens::free_balance(pool_id, &BOB); @@ -1130,7 +1130,7 @@ fn remove_multi_asset_liquidity_should_work_when_withdrawing_all_remaining_share assert_ok!(Stableswap::add_liquidity( RuntimeOrigin::signed(BOB), pool_id, - vec![AssetAmount::new(asset_a, amount_added),] + vec![AssetAmount::new(asset_a, amount_added),].try_into().unwrap() )); let shares = Tokens::free_balance(pool_id, &BOB); diff --git a/pallets/stableswap/src/trade_execution.rs b/pallets/stableswap/src/trade_execution.rs index 0dd0cbe44..372075fe5 100644 --- a/pallets/stableswap/src/trade_execution.rs +++ b/pallets/stableswap/src/trade_execution.rs @@ -3,7 +3,7 @@ use hydra_dx_math::stableswap::types::AssetReserve; use hydradx_traits::router::{ExecutorError, PoolType, TradeExecution}; use hydradx_traits::stableswap::AssetAmount; use orml_traits::MultiCurrency; -use sp_core::Get; +use sp_core::{Get}; use sp_runtime::{ArithmeticError, DispatchError, FixedU128}; use sp_std::vec; @@ -149,15 +149,14 @@ where Self::remove_liquidity_one_asset(who, pool_id, asset_out, amount_in, min_limit) .map_err(ExecutorError::Error) } else if asset_out == pool_id { - Self::add_liquidity( - who, - pool_id, - vec![AssetAmount { - asset_id: asset_in, - amount: amount_in, - }], - ) - .map_err(ExecutorError::Error) + let asset = vec![AssetAmount { + asset_id: asset_in, + amount: amount_in, + }] + .try_into() + .map_err(|_| ExecutorError::Error(ArithmeticError::Overflow.into()))?; + + Self::add_liquidity(who, pool_id, asset).map_err(ExecutorError::Error) } else { Self::sell(who, pool_id, asset_in, asset_out, amount_in, min_limit).map_err(ExecutorError::Error) } From 93462d1fe03f68ffd9fd3755810893132fb6a097 Mon Sep 17 00:00:00 2001 From: dmoka Date: Tue, 3 Dec 2024 09:35:24 +0100 Subject: [PATCH 14/36] remove not needed exit farms --- pallets/omnipool-liquidity-mining/src/lib.rs | 32 -------------------- 1 file changed, 32 deletions(-) diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index 84636e8eb..1e0cb6031 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -999,38 +999,6 @@ pub mod pallet { Ok(()) } - /// Exit from all specified yield farms then removes the linked liquidity - /// - /// This function will attempt to withdraw shares and claim rewards (if available) from all - /// specified yield farms for a given deposit. - /// - /// Parameters: - /// - `origin`: account owner of deposit(nft). - /// - `deposit_id`: id of the deposit to claim rewards for. - /// - `yield_farm_ids`: id(s) of yield farm(s) to exit from. - /// - /// Emits: - /// * `RewardClaimed` for each successful claim - /// * `SharesWithdrawn` for each successful withdrawal - /// * `DepositDestroyed` if the deposit is fully withdrawn - /// - #[pallet::call_index(16)] - #[pallet::weight(::WeightInfo::exit_farms(yield_farm_ids.len() as u32))]//TODO: benchmark - pub fn exit_farms_and_remove_liquidity( - origin: OriginFor, - deposit_id: DepositId, - yield_farm_ids: BoundedVec, - ) -> DispatchResult { - for yield_farm_id in yield_farm_ids.iter() { - Self::withdraw_shares(origin.clone(), deposit_id, *yield_farm_id)?; - } - //TODO: finish - let position_id = OmniPositionId::::get(deposit_id) - .defensive_ok_or::>(InconsistentStateError::MissingLpPosition.into())?; - - Ok(()) - } - /// This function allows user to add liquidity then use that shares to join multiple farms. /// /// Limit protection is applied. From 6dad012eb7518fcf231620f1eb700875be1f6377 Mon Sep 17 00:00:00 2001 From: dmoka Date: Tue, 3 Dec 2024 09:35:42 +0100 Subject: [PATCH 15/36] formatting --- pallets/stableswap/src/tests/add_liquidity.rs | 32 ++++++++++++++----- pallets/stableswap/src/trade_execution.rs | 2 +- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/pallets/stableswap/src/tests/add_liquidity.rs b/pallets/stableswap/src/tests/add_liquidity.rs index c9872d9f3..24b608b9c 100644 --- a/pallets/stableswap/src/tests/add_liquidity.rs +++ b/pallets/stableswap/src/tests/add_liquidity.rs @@ -43,7 +43,9 @@ fn add_initial_liquidity_should_work_when_called_first_time() { vec![ AssetAmount::new(asset_a, initial_liquidity_amount), AssetAmount::new(asset_b, initial_liquidity_amount), - ].try_into().unwrap() + ] + .try_into() + .unwrap() )); assert_balance!(BOB, asset_a, 100 * ONE); @@ -92,7 +94,9 @@ fn add_initial_liquidity_should_fail_when_lp_has_insufficient_balance() { vec![ AssetAmount::new(asset_a, initial_liquidity_amount), AssetAmount::new(asset_b, initial_liquidity_amount), - ].try_into().unwrap() + ] + .try_into() + .unwrap() ), Error::::InsufficientBalance ); @@ -150,7 +154,9 @@ fn add_liquidity_should_work_when_initial_liquidity_has_been_provided() { vec![ AssetAmount::new(asset_a, amount_added), AssetAmount::new(asset_b, amount_added), - ].try_into().unwrap() + ] + .try_into() + .unwrap() )); assert_balance!(BOB, asset_a, 100 * ONE); @@ -207,7 +213,9 @@ fn add_liquidity_should_work_when_order_is_not_sorted() { vec![ AssetAmount::new(asset_b, amount_added), AssetAmount::new(asset_a, amount_added), - ].try_into().unwrap() + ] + .try_into() + .unwrap() )); assert_balance!(BOB, asset_a, 100 * ONE); @@ -262,7 +270,9 @@ fn add_liquidity_should_fail_when_providing_insufficient_liquidity() { vec![ AssetAmount::new(asset_b, amount_added), AssetAmount::new(asset_a, amount_added), - ].try_into().unwrap() + ] + .try_into() + .unwrap() ), Error::::InsufficientTradingAmount ); @@ -375,7 +385,9 @@ fn add_liquidity_should_fail_when_providing_one_asset_not_in_pool() { vec![ AssetAmount::new(asset_a, amount_added), AssetAmount::new(asset_e, amount_added), - ].try_into().unwrap() + ] + .try_into() + .unwrap() ), Error::::AssetNotInPool ); @@ -425,7 +437,9 @@ fn add_liquidity_should_fail_when_provided_list_contains_same_assets() { vec![ AssetAmount::new(asset_a, amount_added), AssetAmount::new(asset_a, amount_added), - ].try_into().unwrap() + ] + .try_into() + .unwrap() ), Error::::IncorrectAssets ); @@ -471,7 +485,9 @@ fn add_initial_liquidity_should_work_when_asset_have_different_decimals() { vec![ AssetAmount::new(asset_a, initial_liquidity_amount_a), AssetAmount::new(asset_b, initial_liquidity_amount_b), - ].try_into().unwrap() + ] + .try_into() + .unwrap() )); assert_balance!(BOB, asset_a, to_precision!(100, dec_a)); diff --git a/pallets/stableswap/src/trade_execution.rs b/pallets/stableswap/src/trade_execution.rs index 372075fe5..5dda14d77 100644 --- a/pallets/stableswap/src/trade_execution.rs +++ b/pallets/stableswap/src/trade_execution.rs @@ -3,7 +3,7 @@ use hydra_dx_math::stableswap::types::AssetReserve; use hydradx_traits::router::{ExecutorError, PoolType, TradeExecution}; use hydradx_traits::stableswap::AssetAmount; use orml_traits::MultiCurrency; -use sp_core::{Get}; +use sp_core::Get; use sp_runtime::{ArithmeticError, DispatchError, FixedU128}; use sp_std::vec; From bb1be92851bd818a55332c88e5c8ce174009f41d Mon Sep 17 00:00:00 2001 From: dmoka Date: Tue, 3 Dec 2024 10:07:30 +0100 Subject: [PATCH 16/36] make clippy happy --- ...add_liquidity_with_limit_and_join_farms.rs | 2 - pallets/stableswap/src/benchmarks.rs | 28 +- runtime-mock/src/stableswap.rs | 2 +- .../benchmarking/omnipool_liquidity_mining.rs | 354 +++++++++--------- 4 files changed, 192 insertions(+), 194 deletions(-) diff --git a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs index 11124237f..980624a06 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs @@ -205,8 +205,6 @@ fn add_liquidity_join_farms_should_fail_when_doesnt_reach_limit() { .execute_with(|| { let gc_g_farm_id = 1; let gc_y_farm_id = 4; - let omnipool_position_id = 3; - let deposit_id = 1; let asset_in_position = KSM; let amount = 20 * ONE; let yield_farms = vec![(gc_g_farm_id, gc_y_farm_id)]; diff --git a/pallets/stableswap/src/benchmarks.rs b/pallets/stableswap/src/benchmarks.rs index b209c4209..a1751d2e4 100644 --- a/pallets/stableswap/src/benchmarks.rs +++ b/pallets/stableswap/src/benchmarks.rs @@ -98,9 +98,9 @@ benchmarks! { // Worst case is adding additional liquidity and not initial liquidity crate::Pallet::::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; - }: _(RawOrigin::Signed(lp_provider.clone()), pool_id, added_liquidity) + }: _(RawOrigin::Signed(lp_provider.clone()), pool_id, added_liquidity.try_into().unwrap()) verify { assert!(T::Currency::free_balance(pool_id, &lp_provider) > 0u128); } @@ -139,7 +139,7 @@ benchmarks! { crate::Pallet::::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; let desired_shares = 1198499641600967085948u128; }: _(RawOrigin::Signed(lp_provider.clone()), pool_id, desired_shares,asset_id, 1221886049851226) @@ -183,11 +183,11 @@ benchmarks! { // Worst case is adding additional liquidity and not initial liquidity crate::Pallet::::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; crate::Pallet::::add_liquidity(RawOrigin::Signed(lp_provider.clone()).into(), pool_id, - added_liquidity + added_liquidity.try_into().unwrap() )?; // just make sure that LP provided all his liquidity of this asset @@ -236,11 +236,11 @@ benchmarks! { // Worst case is adding additional liquidity and not initial liquidity crate::Pallet::::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; crate::Pallet::::add_liquidity(RawOrigin::Signed(lp_provider.clone()).into(), pool_id, - added_liquidity + added_liquidity.try_into().unwrap() )?; // just make sure that LP provided all his liquidity of this asset @@ -288,11 +288,11 @@ benchmarks! { // Worst case is adding additional liquidity and not initial liquidity crate::Pallet::::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; crate::Pallet::::add_liquidity(RawOrigin::Signed(lp_provider.clone()).into(), pool_id, - added_liquidity + added_liquidity.try_into().unwrap() )?; // just make sure that LP provided all his liquidity of this asset @@ -338,7 +338,7 @@ benchmarks! { )?; crate::Pallet::::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; let seller : T::AccountId = account("seller", 0, 1); @@ -392,7 +392,7 @@ benchmarks! { )?; crate::Pallet::::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; let buyer: T::AccountId = account("buyer", 0, 1); @@ -570,7 +570,7 @@ benchmarks! { )?; crate::Pallet::::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; let seller : T::AccountId = account("seller", 0, 1); @@ -634,7 +634,7 @@ benchmarks! { )?; crate::Pallet::::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; let buyer: T::AccountId = account("buyer", 0, 1); @@ -697,7 +697,7 @@ benchmarks! { )?; crate::Pallet::::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; let buyer: T::AccountId = account("buyer", 0, 1); diff --git a/runtime-mock/src/stableswap.rs b/runtime-mock/src/stableswap.rs index 303695b64..9742725d7 100644 --- a/runtime-mock/src/stableswap.rs +++ b/runtime-mock/src/stableswap.rs @@ -91,7 +91,7 @@ impl Stablepools { .map(|pool| { RuntimeCall::Stableswap(pallet_stableswap::Call::add_liquidity { pool_id: pool.pool_id, - assets: pool.get_asset_amounts(), + assets: pool.get_asset_amounts().try_into().unwrap(), }) }) .collect() diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index dae5703c5..6aa26f5fd 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -117,7 +117,7 @@ fn initialize_global_farm(owner: AccountId) -> DispatchResult { G_FARM_TOTAL_REWARDS, BlockNumberFor::::from(100_000_u32), BlockNumberFor::::from(1_u32), - REWARD_CURRENCY.into(), + REWARD_CURRENCY, owner, Perquintill::from_percent(20), 1_000, @@ -139,21 +139,21 @@ fn initialize_omnipool(additional_asset: Option) -> DispatchResult { let acc = Omnipool::protocol_account(); - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DAI.into(), stable_amount as Amount)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), HDX.into(), native_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DAI, stable_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), HDX, native_amount as Amount)?; - fund(acc.clone(), HDX.into(), 10_000_000_000_000_000 * ONE)?; + fund(acc.clone(), HDX, 10_000_000_000_000_000 * ONE)?; Omnipool::add_token( RawOrigin::Root.into(), - HDX.into(), + HDX, native_price, Permill::from_percent(100), acc.clone(), )?; Omnipool::add_token( RawOrigin::Root.into(), - DAI.into(), + DAI, stable_price, Permill::from_percent(100), acc.clone(), @@ -215,20 +215,20 @@ fn initialize_omnipool(additional_asset: Option) -> DispatchResult { })?; // Create account for token provider and set balance - let owner: AccountId = funded_account("owner2", 0, &vec![]); + let owner: AccountId = funded_account("owner2", 0, &[]); let token_price = FixedU128::from((1, 5)); let token_amount = 200_000_000_000_000u128; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), BSX.into(), token_amount as Amount)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), ETH.into(), token_amount as Amount)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), BTC.into(), token_amount as Amount)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DOT.into(), token_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), BSX, token_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), ETH, token_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), BTC, token_amount as Amount)?; + Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DOT, token_amount as Amount)?; // Add the token to the pool Omnipool::add_token( RawOrigin::Root.into(), - BSX.into(), + BSX, token_price, Permill::from_percent(100), owner.clone(), @@ -236,7 +236,7 @@ fn initialize_omnipool(additional_asset: Option) -> DispatchResult { Omnipool::add_token( RawOrigin::Root.into(), - ETH.into(), + ETH, token_price, Permill::from_percent(100), owner.clone(), @@ -244,7 +244,7 @@ fn initialize_omnipool(additional_asset: Option) -> DispatchResult { Omnipool::add_token( RawOrigin::Root.into(), - BTC.into(), + BTC, token_price, Permill::from_percent(100), owner.clone(), @@ -252,7 +252,7 @@ fn initialize_omnipool(additional_asset: Option) -> DispatchResult { Omnipool::add_token( RawOrigin::Root.into(), - DOT.into(), + DOT, token_price, Permill::from_percent(100), owner.clone(), @@ -262,12 +262,12 @@ fn initialize_omnipool(additional_asset: Option) -> DispatchResult { Currencies::update_balance( RawOrigin::Root.into(), acc.clone(), - asset_id.into(), + asset_id, (token_amount * 100) as Amount, )?; Omnipool::add_token( RawOrigin::Root.into(), - asset_id.into(), + asset_id, token_price, Permill::from_percent(100), owner, @@ -282,17 +282,17 @@ fn initialize_omnipool(additional_asset: Option) -> DispatchResult { //NOTE: This is necessary for oracle to provide price. fn do_lrna_hdx_trade() -> DispatchResult { - let trader = funded_account("tmp_trader", 0, &vec![REWARD_CURRENCY.into()]); + let trader = funded_account("tmp_trader", 0, &[REWARD_CURRENCY]); - fund(trader.clone(), LRNA.into(), 100 * ONE)?; + fund(trader.clone(), LRNA, 100 * ONE)?; - Omnipool::sell(RawOrigin::Signed(trader).into(), LRNA.into(), HDX.into(), ONE, 0) + Omnipool::sell(RawOrigin::Signed(trader).into(), LRNA, HDX, ONE, 0) } fn seed_lm_pot() -> DispatchResult { let pot = OmnipoolWarehouseLM::pot_account_id().unwrap(); - fund(pot, HDX.into(), 100 * ONE) + fund(pot, HDX, 100 * ONE) } fn omnipool_add_liquidity(lp: AccountId, asset: AssetId, amount: Balance) -> Result { @@ -333,22 +333,22 @@ runtime_benchmarks! { let planned_yielding_periods = BlockNumberFor::::from(100_000_u32); let blocks_per_period = BlockNumberFor::::from(100_u32); let reward_currency = register_asset(b"REW".to_vec(), 10000 * ONE).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - let owner = funded_account("owner", 0, &[reward_currency.into()]); + let owner = funded_account("owner", 0, &[REWARD_CURRENCY]); let yield_per_period = Perquintill::from_percent(20); let min_deposit = 1_000; let price_adjustment = FixedU128::from(10_u128); - }: _(RawOrigin::Root, G_FARM_TOTAL_REWARDS, planned_yielding_periods, blocks_per_period, reward_currency.into(), owner, yield_per_period, min_deposit, FixedU128::one()) + }: _(RawOrigin::Root, G_FARM_TOTAL_REWARDS, planned_yielding_periods, blocks_per_period, REWARD_CURRENCY, owner, yield_per_period, min_deposit, FixedU128::one()) update_global_farm { - let owner = funded_account("owner", 0, &[REWARD_CURRENCY.into()]); + let owner = funded_account("owner", 0, &[REWARD_CURRENCY]); let global_farm_id = 1; let yield_farm_id = 2; initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC)?; let planned_yielding_periods = BlockNumberFor::::from(100_000_u32); let yield_per_period = Perquintill::from_percent(20); @@ -358,23 +358,23 @@ runtime_benchmarks! { terminate_global_farm { - let owner = funded_account("owner", 0, &[REWARD_CURRENCY.into()]); + let owner = funded_account("owner", 0, &[REWARD_CURRENCY]); let global_farm_id = 1; let yield_farm_id = 2; initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC)?; - let lp = funded_account("lp_1", 1, &[BTC.into()]); - let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp = funded_account("lp_1", 1, &[BTC]); + let position_id = omnipool_add_liquidity(lp.clone(), BTC, 10 * BTC_ONE)?; set_period(100); lm_deposit_shares(lp, global_farm_id, yield_farm_id, position_id)?; - OmnipoolLiquidityMining::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, BTC.into())?; - OmnipoolLiquidityMining::terminate_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, yield_farm_id, BTC.into())?; + OmnipoolLiquidityMining::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, BTC)?; + OmnipoolLiquidityMining::terminate_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, yield_farm_id, BTC)?; set_period(200); }: _(RawOrigin::Signed(owner), global_farm_id) @@ -383,16 +383,16 @@ runtime_benchmarks! { create_yield_farm { fund_treasury().unwrap(); //To prevent BelowMinimum error - let owner = funded_account("owner", 0, &[HDX, REWARD_CURRENCY.into()]); + let owner = funded_account("owner", 0, &[HDX, REWARD_CURRENCY]); let global_farm_id = 1; initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC)?; - let lp = funded_account("lp_1", 1, &[BTC.into()]); - let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp = funded_account("lp_1", 1, &[BTC]); + let position_id = omnipool_add_liquidity(lp.clone(), BTC, 10 * BTC_ONE)?; set_period(100); lm_deposit_shares(lp, global_farm_id, 2, position_id)?; @@ -400,50 +400,50 @@ runtime_benchmarks! { set_period(1000); }: { - OmnipoolLiquidityMining::create_yield_farm(RawOrigin::Signed(owner).into(), global_farm_id, ETH.into(), FixedU128::one(), Some(LoyaltyCurve::default()))?; + OmnipoolLiquidityMining::create_yield_farm(RawOrigin::Signed(owner).into(), global_farm_id, ETH, FixedU128::one(), Some(LoyaltyCurve::default()))?; } verify { } update_yield_farm { - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let global_farm_id = 1; let yield_farm_id = 2; initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC)?; - let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); + let position_id = omnipool_add_liquidity(lp.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp, global_farm_id, yield_farm_id, position_id)?; set_period(200); - }: _(RawOrigin::Signed(owner), global_farm_id, BTC.into(), FixedU128::from(2_u128)) + }: _(RawOrigin::Signed(owner), global_farm_id, BTC, FixedU128::from(2_u128)) stop_yield_farm { - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let global_farm_id = 1; let yield_farm_id = 2; initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC)?; - let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); + let position_id = omnipool_add_liquidity(lp.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp, global_farm_id, yield_farm_id, position_id)?; set_period(200); - }: _(RawOrigin::Signed(owner), global_farm_id, BTC.into()) + }: _(RawOrigin::Signed(owner), global_farm_id, BTC) resume_yield_farm { - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let global_farm_id = 1; let eth_farm_id = 2; let btc_farm_id = 3; @@ -451,60 +451,60 @@ runtime_benchmarks! { initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner.clone(), global_farm_id, ETH.into())?; - initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + initialize_yield_farm(owner.clone(), global_farm_id, ETH)?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC)?; - let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); + let position_id = omnipool_add_liquidity(lp.clone(), BTC, 10 * BTC_ONE)?; - OmnipoolLiquidityMining::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, ETH.into())?; + OmnipoolLiquidityMining::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, ETH)?; set_period(200); lm_deposit_shares(lp, global_farm_id, btc_farm_id, position_id)?; set_period(400); - }: _(RawOrigin::Signed(owner), global_farm_id, eth_farm_id, ETH.into(), FixedU128::from(2)) + }: _(RawOrigin::Signed(owner), global_farm_id, eth_farm_id, ETH, FixedU128::from(2)) terminate_yield_farm { - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let global_farm_id = 1; let yield_farm_id = 2; initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner.clone(), global_farm_id, BTC.into())?; + initialize_yield_farm(owner.clone(), global_farm_id, BTC)?; - let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let position_id = omnipool_add_liquidity(lp.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); + let position_id = omnipool_add_liquidity(lp.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp, global_farm_id, yield_farm_id, position_id)?; set_period(200); - OmnipoolLiquidityMining::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, BTC.into())?; + OmnipoolLiquidityMining::stop_yield_farm(RawOrigin::Signed(owner.clone()).into(), global_farm_id, BTC)?; set_period(300); - }: _(RawOrigin::Signed(owner), global_farm_id, yield_farm_id, BTC.into()) + }: _(RawOrigin::Signed(owner), global_farm_id, yield_farm_id, BTC) deposit_shares { - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let global_farm_id = 1; let yield_farm_id = 2; initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner, global_farm_id, BTC.into())?; + initialize_yield_farm(owner, global_farm_id, BTC)?; - let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp1, global_farm_id, yield_farm_id, lp1_position_id)?; - let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC.into()); - let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC, 10 * BTC_ONE)?; set_period(200); @@ -512,11 +512,11 @@ runtime_benchmarks! { redeposit_shares { - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let deposit_id = 1; @@ -524,29 +524,29 @@ runtime_benchmarks! { //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner, 1, BTC.into())?; + initialize_yield_farm(owner, 1, BTC)?; //gId: 3, yId: 4 initialize_global_farm(owner2.clone())?; - initialize_yield_farm(owner2, 3, BTC.into())?; + initialize_yield_farm(owner2, 3, BTC)?; //gId: 5, yId: 6 initialize_global_farm(owner3.clone())?; - initialize_yield_farm(owner3, 5, BTC.into())?; + initialize_yield_farm(owner3, 5, BTC)?; //gId: 7, yId: 8 initialize_global_farm(owner4.clone())?; - initialize_yield_farm(owner4, 7, BTC.into())?; + initialize_yield_farm(owner4, 7, BTC)?; //gId: 9, yId: 10 initialize_global_farm(owner5.clone())?; - initialize_yield_farm(owner5, 9, BTC.into())?; + initialize_yield_farm(owner5, 9, BTC)?; - let lp1 = create_funded_account("lp_1", 5, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp1 = create_funded_account("lp_1", 5, 10 * BTC_ONE, BTC); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC, 10 * BTC_ONE)?; - let lp2 = create_funded_account("lp_2", 6, 1_000 * ONE, BTC.into()); - let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp2 = create_funded_account("lp_2", 6, 1_000 * ONE, BTC); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC, 10 * BTC_ONE)?; set_period(200); @@ -562,11 +562,11 @@ runtime_benchmarks! { }: _(RawOrigin::Signed(lp1), 9, 10, deposit_id) claim_rewards { - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let deposit_id = 1; @@ -574,29 +574,29 @@ runtime_benchmarks! { //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner, 1, BTC.into())?; + initialize_yield_farm(owner, 1, BTC)?; //gId: 3, yId: 4 initialize_global_farm(owner2.clone())?; - initialize_yield_farm(owner2, 3, BTC.into())?; + initialize_yield_farm(owner2, 3, BTC)?; //gId: 5, yId: 6 initialize_global_farm(owner3.clone())?; - initialize_yield_farm(owner3, 5, BTC.into())?; + initialize_yield_farm(owner3, 5, BTC)?; //gId: 7, yId: 8 initialize_global_farm(owner4.clone())?; - initialize_yield_farm(owner4, 7, BTC.into())?; + initialize_yield_farm(owner4, 7, BTC)?; //gId: 9, yId: 10 initialize_global_farm(owner5.clone())?; - initialize_yield_farm(owner5, 9, BTC.into())?; + initialize_yield_farm(owner5, 9, BTC)?; - let lp1 = create_funded_account("lp_1", 5, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp1 = create_funded_account("lp_1", 5, 10 * BTC_ONE, BTC); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC, 10 * BTC_ONE)?; //NOTE: This is necessary because paid rewards are lower than ED. - fund(lp1.clone(), REWARD_CURRENCY.into(), 100 * ONE)?; + fund(lp1.clone(), REWARD_CURRENCY, 100 * ONE)?; set_period(200); @@ -616,7 +616,7 @@ runtime_benchmarks! { } withdraw_shares { - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let global_farm_id = 1; let yield_farm_id = 2; @@ -625,13 +625,13 @@ runtime_benchmarks! { initialize_omnipool(None)?; initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner, global_farm_id, BTC.into())?; + initialize_yield_farm(owner, global_farm_id, BTC)?; - let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC, 10 * BTC_ONE)?; //NOTE: This is necessary because paid rewards are lower than ED. - fund(lp1.clone(), REWARD_CURRENCY.into(), 100 * ONE)?; + fund(lp1.clone(), REWARD_CURRENCY, 100 * ONE)?; set_period(200); @@ -642,11 +642,11 @@ runtime_benchmarks! { join_farms { let c in 1..get_max_entries(); - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let deposit_id = 1; @@ -654,41 +654,41 @@ runtime_benchmarks! { //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner, 1, BTC.into())?; - let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + initialize_yield_farm(owner, 1, BTC)?; + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp1, 1, 2, lp1_position_id)?; //gId: 3, yId: 4 initialize_global_farm(owner2.clone())?; - initialize_yield_farm(owner2, 3, BTC.into())?; - let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC.into()); - let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; + initialize_yield_farm(owner2, 3, BTC)?; + let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp2, 3, 4, lp2_position_id)?; //gId: 5, yId: 6 initialize_global_farm(owner3.clone())?; - initialize_yield_farm(owner3, 5, BTC.into())?; - let lp3 = create_funded_account("lp_3", 1, 10 * BTC_ONE, BTC.into()); - let lp3_position_id = omnipool_add_liquidity(lp3.clone(), BTC.into(), 10 * BTC_ONE)?; + initialize_yield_farm(owner3, 5, BTC)?; + let lp3 = create_funded_account("lp_3", 1, 10 * BTC_ONE, BTC); + let lp3_position_id = omnipool_add_liquidity(lp3.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp3, 5, 6, lp3_position_id)?; //gId: 7, yId: 8 initialize_global_farm(owner4.clone())?; - initialize_yield_farm(owner4, 7, BTC.into())?; - let lp4 = create_funded_account("lp_4", 1, 10 * BTC_ONE, BTC.into()); - let lp4_position_id = omnipool_add_liquidity(lp4.clone(), BTC.into(), 10 * BTC_ONE)?; + initialize_yield_farm(owner4, 7, BTC)?; + let lp4 = create_funded_account("lp_4", 1, 10 * BTC_ONE, BTC); + let lp4_position_id = omnipool_add_liquidity(lp4.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp4, 7, 8, lp4_position_id)?; //gId: 9, yId: 10 initialize_global_farm(owner5.clone())?; - initialize_yield_farm(owner5, 9, BTC.into())?; - let lp5 = create_funded_account("lp_5", 1, 10 * BTC_ONE, BTC.into()); - let lp5_position_id = omnipool_add_liquidity(lp5.clone(), BTC.into(), 10 * BTC_ONE)?; + initialize_yield_farm(owner5, 9, BTC)?; + let lp5 = create_funded_account("lp_5", 1, 10 * BTC_ONE, BTC); + let lp5_position_id = omnipool_add_liquidity(lp5.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp5, 9, 10, lp5_position_id)?; - let lp6 = create_funded_account("lp_6", 5, 10 * BTC_ONE, BTC.into()); - let lp6_position_id = omnipool_add_liquidity(lp6.clone(), BTC.into(), 10 * BTC_ONE)?; + let lp6 = create_funded_account("lp_6", 5, 10 * BTC_ONE, BTC); + let lp6_position_id = omnipool_add_liquidity(lp6.clone(), BTC, 10 * BTC_ONE)?; set_period(200); let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; @@ -699,11 +699,11 @@ runtime_benchmarks! { add_liquidity_and_join_farms { let c in 1..get_max_entries(); - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let deposit_id = 1; @@ -711,55 +711,55 @@ runtime_benchmarks! { //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner, 1, BTC.into())?; - let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), 10 * BTC_ONE)?; + initialize_yield_farm(owner, 1, BTC)?; + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp1, 1, 2, lp1_position_id)?; //gId: 3, yId: 4 initialize_global_farm(owner2.clone())?; - initialize_yield_farm(owner2, 3, BTC.into())?; - let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC.into()); - let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC.into(), 10 * BTC_ONE)?; + initialize_yield_farm(owner2, 3, BTC)?; + let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp2, 3, 4, lp2_position_id)?; //gId: 5, yId: 6 initialize_global_farm(owner3.clone())?; - initialize_yield_farm(owner3, 5, BTC.into())?; - let lp3 = create_funded_account("lp_3", 1, 10 * BTC_ONE, BTC.into()); - let lp3_position_id = omnipool_add_liquidity(lp3.clone(), BTC.into(), 10 * BTC_ONE)?; + initialize_yield_farm(owner3, 5, BTC)?; + let lp3 = create_funded_account("lp_3", 1, 10 * BTC_ONE, BTC); + let lp3_position_id = omnipool_add_liquidity(lp3.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp3, 5, 6, lp3_position_id)?; //gId: 7, yId: 8 initialize_global_farm(owner4.clone())?; - initialize_yield_farm(owner4, 7, BTC.into())?; - let lp4 = create_funded_account("lp_4", 1, 10 * BTC_ONE, BTC.into()); - let lp4_position_id = omnipool_add_liquidity(lp4.clone(), BTC.into(), 10 * BTC_ONE)?; + initialize_yield_farm(owner4, 7, BTC)?; + let lp4 = create_funded_account("lp_4", 1, 10 * BTC_ONE, BTC); + let lp4_position_id = omnipool_add_liquidity(lp4.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp4, 7, 8, lp4_position_id)?; //gId: 9, yId: 10 initialize_global_farm(owner5.clone())?; - initialize_yield_farm(owner5, 9, BTC.into())?; - let lp5 = create_funded_account("lp_5", 1, 10 * BTC_ONE, BTC.into()); - let lp5_position_id = omnipool_add_liquidity(lp5.clone(), BTC.into(), 10 * BTC_ONE)?; + initialize_yield_farm(owner5, 9, BTC)?; + let lp5 = create_funded_account("lp_5", 1, 10 * BTC_ONE, BTC); + let lp5_position_id = omnipool_add_liquidity(lp5.clone(), BTC, 10 * BTC_ONE)?; lm_deposit_shares(lp5, 9, 10, lp5_position_id)?; - let lp6 = create_funded_account("lp_6", 5, 10 * BTC_ONE, BTC.into()); + let lp6 = create_funded_account("lp_6", 5, 10 * BTC_ONE, BTC); set_period(200); let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; let farms = farms_entries[0..c as usize].to_vec(); - }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), BTC.into(), 10 * BTC_ONE) + }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), BTC, 10 * BTC_ONE) exit_farms { let c in 1..get_max_entries(); - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let deposit_id = 1; @@ -767,26 +767,26 @@ runtime_benchmarks! { //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner, 1, BTC.into())?; + initialize_yield_farm(owner, 1, BTC)?; //gId: 3, yId: 4 initialize_global_farm(owner2.clone())?; - initialize_yield_farm(owner2, 3, BTC.into())?; + initialize_yield_farm(owner2, 3, BTC)?; //gId: 5, yId: 6 initialize_global_farm(owner3.clone())?; - initialize_yield_farm(owner3, 5, BTC.into())?; + initialize_yield_farm(owner3, 5, BTC)?; //gId: 7, yId: 8 initialize_global_farm(owner4.clone())?; - initialize_yield_farm(owner4, 7, BTC.into())?; + initialize_yield_farm(owner4, 7, BTC)?; //gId: 9, yId: 10 initialize_global_farm(owner5.clone())?; - initialize_yield_farm(owner5, 9, BTC.into())?; + initialize_yield_farm(owner5, 9, BTC)?; - let lp1 = create_funded_account("lp_1", 5, 10 * BTC_ONE, BTC.into()); - let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC.into(), BTC_ONE)?; + let lp1 = create_funded_account("lp_1", 5, 10 * BTC_ONE, BTC); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC, BTC_ONE)?; set_period(200); @@ -829,7 +829,7 @@ runtime_benchmarks! { added_liquidity.push(AssetAmount::new(asset_id, liquidity_added)); } - let name : Vec = b"PO2".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; + let name : Vec = b"PO2".to_vec(); let pool_id = register_asset_with_decimals( name, 1u128, @@ -849,18 +849,18 @@ runtime_benchmarks! { // Worst case is adding additional liquidity and not initial liquidity Stableswap::add_liquidity(RawOrigin::Signed(caller).into(), pool_id, - initial, + initial.try_into().unwrap(), )?; - let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC.into()); + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); let deposit_id = 1; //Init LM farms - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); - let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY.into()); + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); let deposit_id = 1; @@ -873,40 +873,40 @@ runtime_benchmarks! { //gId: 1, yId: 2 initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner, 1, pool_id.into())?; - let lp1 = create_funded_account("lp_1", 1, 10 * ONE, pool_id.into()); - let lp1_position_id = omnipool_add_liquidity(lp1.clone(), pool_id.into(), 10 * ONE)?; + initialize_yield_farm(owner, 1, pool_id)?; + let lp1 = create_funded_account("lp_1", 1, 10 * ONE, pool_id); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), pool_id, 10 * ONE)?; lm_deposit_shares(lp1, 1, 2, lp1_position_id)?; //gId: 3, yId: 4 initialize_global_farm(owner2.clone())?; - initialize_yield_farm(owner2, 3, pool_id.into())?; - let lp2 = create_funded_account("lp_2", 1, 10 * ONE, pool_id.into()); - let lp2_position_id = omnipool_add_liquidity(lp2.clone(), pool_id.into(), 10 * ONE)?; + initialize_yield_farm(owner2, 3, pool_id)?; + let lp2 = create_funded_account("lp_2", 1, 10 * ONE, pool_id); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), pool_id, 10 * ONE)?; lm_deposit_shares(lp2, 3, 4, lp2_position_id)?; //gId: 5, yId: 6 initialize_global_farm(owner3.clone())?; - initialize_yield_farm(owner3, 5, pool_id.into())?; - let lp3 = create_funded_account("lp_3", 1, 10 * ONE, pool_id.into()); - let lp3_position_id = omnipool_add_liquidity(lp3.clone(), pool_id.into(), 10 * ONE)?; + initialize_yield_farm(owner3, 5, pool_id)?; + let lp3 = create_funded_account("lp_3", 1, 10 * ONE, pool_id); + let lp3_position_id = omnipool_add_liquidity(lp3.clone(), pool_id, 10 * ONE)?; lm_deposit_shares(lp3, 5, 6, lp3_position_id)?; //gId: 7, yId: 8 initialize_global_farm(owner4.clone())?; - initialize_yield_farm(owner4, 7, pool_id.into())?; - let lp4 = create_funded_account("lp_4", 1, 10 * ONE, pool_id.into()); - let lp4_position_id = omnipool_add_liquidity(lp4.clone(), pool_id.into(), 10 * ONE)?; + initialize_yield_farm(owner4, 7, pool_id)?; + let lp4 = create_funded_account("lp_4", 1, 10 * ONE, pool_id); + let lp4_position_id = omnipool_add_liquidity(lp4.clone(), pool_id, 10 * ONE)?; lm_deposit_shares(lp4, 7, 8, lp4_position_id)?; //gId: 9, yId: 10 initialize_global_farm(owner5.clone())?; - initialize_yield_farm(owner5, 9, pool_id.into())?; - let lp5 = create_funded_account("lp_5", 1, 10 * ONE, pool_id.into()); - let lp5_position_id = omnipool_add_liquidity(lp5.clone(), pool_id.into(), 10 * ONE)?; + initialize_yield_farm(owner5, 9, pool_id)?; + let lp5 = create_funded_account("lp_5", 1, 10 * ONE, pool_id); + let lp5_position_id = omnipool_add_liquidity(lp5.clone(), pool_id, 10 * ONE)?; lm_deposit_shares(lp5, 9, 10, lp5_position_id)?; - let lp6 = create_funded_account("lp_6", 5, 10 * ONE, pool_id.into()); + let lp6 = create_funded_account("lp_6", 5, 10 * ONE, pool_id); set_period(200); let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; From 07d34a3fbc9314d8153fa39049b2d26e3191090b Mon Sep 17 00:00:00 2001 From: dmoka Date: Wed, 4 Dec 2024 10:32:14 +0100 Subject: [PATCH 17/36] fix compilation erros --- integration-tests/src/dca.rs | 8 +++++--- integration-tests/src/omnipool_liquidity_mining.rs | 2 +- integration-tests/src/router.rs | 6 +++++- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/integration-tests/src/dca.rs b/integration-tests/src/dca.rs index 8698a29f7..23c39856c 100644 --- a/integration-tests/src/dca.rs +++ b/integration-tests/src/dca.rs @@ -2522,7 +2522,9 @@ mod stableswap { vec![AssetAmount { asset_id: stable_asset_1, amount: amount_to_sell, - }], + }] + .try_into() + .unwrap(), )); let alice_pool_id_balance = Currencies::free_balance(pool_id, &AccountId::from(ALICE)); @@ -4144,7 +4146,7 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { Stableswap::create_pool(RuntimeOrigin::root(), pool_id, asset_ids, amplification, fee)?; - Stableswap::add_liquidity(RuntimeOrigin::signed(BOB.into()), pool_id, initial)?; + Stableswap::add_liquidity(RuntimeOrigin::signed(BOB.into()), pool_id, initial.try_into().unwrap())?; Ok((pool_id, asset_in, asset_out)) } @@ -4208,7 +4210,7 @@ pub fn init_stableswap_with_three_assets_having_different_decimals( Stableswap::create_pool(RuntimeOrigin::root(), pool_id, asset_ids, amplification, fee)?; - Stableswap::add_liquidity(RuntimeOrigin::signed(BOB.into()), pool_id, initial)?; + Stableswap::add_liquidity(RuntimeOrigin::signed(BOB.into()), pool_id, initial.try_into().unwrap())?; Ok((pool_id, asset_in, asset_out)) } diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index 282a98eb0..0a6155e65 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -1817,7 +1817,7 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { Stableswap::create_pool(RuntimeOrigin::root(), pool_id, asset_ids, amplification, fee)?; - Stableswap::add_liquidity(RuntimeOrigin::signed(BOB.into()), pool_id, initial)?; + Stableswap::add_liquidity(RuntimeOrigin::signed(BOB.into()), pool_id, initial.try_into().unwrap())?; Ok((pool_id, asset_in, asset_out)) } diff --git a/integration-tests/src/router.rs b/integration-tests/src/router.rs index fa0b4b171..845bacca4 100644 --- a/integration-tests/src/router.rs +++ b/integration-tests/src/router.rs @@ -5588,7 +5588,11 @@ pub fn init_stableswap_with_details( fee, )?; - Stableswap::add_liquidity(hydradx_runtime::RuntimeOrigin::signed(BOB.into()), pool_id, initial)?; + Stableswap::add_liquidity( + hydradx_runtime::RuntimeOrigin::signed(BOB.into()), + pool_id, + initial.try_into().unwrap(), + )?; Ok((pool_id, asset_in, asset_out)) } From 46136ade4173b2b8beeab1bd7d3405271dce1cae Mon Sep 17 00:00:00 2001 From: dmoka Date: Wed, 4 Dec 2024 10:35:25 +0100 Subject: [PATCH 18/36] bump versions --- Cargo.lock | 14 +++++++------- integration-tests/Cargo.toml | 2 +- pallets/omnipool-liquidity-mining/Cargo.toml | 2 +- pallets/omnipool/Cargo.toml | 2 +- pallets/stableswap/Cargo.toml | 2 +- runtime-mock/Cargo.toml | 2 +- runtime/hydradx/Cargo.toml | 2 +- runtime/hydradx/src/lib.rs | 2 +- traits/Cargo.toml | 2 +- 9 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4a92d724c..a179dfcd1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4918,7 +4918,7 @@ dependencies = [ [[package]] name = "hydradx-runtime" -version = "272.0.0" +version = "273.0.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-parachain-system", @@ -5057,7 +5057,7 @@ dependencies = [ [[package]] name = "hydradx-traits" -version = "3.9.0" +version = "3.9.1" dependencies = [ "frame-support", "impl-trait-for-tuples", @@ -8736,7 +8736,7 @@ dependencies = [ [[package]] name = "pallet-omnipool" -version = "4.3.6" +version = "4.3.7" dependencies = [ "bitflags 1.3.2", "frame-benchmarking", @@ -8763,7 +8763,7 @@ dependencies = [ [[package]] name = "pallet-omnipool-liquidity-mining" -version = "2.4.0" +version = "2.5.0" dependencies = [ "frame-benchmarking", "frame-support", @@ -9100,7 +9100,7 @@ dependencies = [ [[package]] name = "pallet-stableswap" -version = "4.0.0" +version = "4.0.1" dependencies = [ "bitflags 1.3.2", "frame-benchmarking", @@ -12200,7 +12200,7 @@ dependencies = [ [[package]] name = "runtime-integration-tests" -version = "1.25.1" +version = "1.26.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-parachain-system", @@ -12323,7 +12323,7 @@ dependencies = [ [[package]] name = "runtime-mock" -version = "1.0.1" +version = "1.0.2" dependencies = [ "frame-remote-externalities", "frame-support", diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index 45adf2478..81e5cac07 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runtime-integration-tests" -version = "1.25.1" +version = "1.26.0" description = "Integration tests" authors = ["GalacticCouncil"] edition = "2021" diff --git a/pallets/omnipool-liquidity-mining/Cargo.toml b/pallets/omnipool-liquidity-mining/Cargo.toml index fdd70724f..14890102a 100644 --- a/pallets/omnipool-liquidity-mining/Cargo.toml +++ b/pallets/omnipool-liquidity-mining/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-omnipool-liquidity-mining" -version = "2.4.0" +version = "2.5.0" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/omnipool/Cargo.toml b/pallets/omnipool/Cargo.toml index ed8b09d59..e5cdb43c8 100644 --- a/pallets/omnipool/Cargo.toml +++ b/pallets/omnipool/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-omnipool" -version = "4.3.6" +version = "4.3.7" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/stableswap/Cargo.toml b/pallets/stableswap/Cargo.toml index 58c662547..2389277b4 100644 --- a/pallets/stableswap/Cargo.toml +++ b/pallets/stableswap/Cargo.toml @@ -1,6 +1,6 @@ [package] name = 'pallet-stableswap' -version = '4.0.0' +version = '4.0.1' description = 'AMM for correlated assets' authors = ['GalacticCouncil'] edition = '2021' diff --git a/runtime-mock/Cargo.toml b/runtime-mock/Cargo.toml index e1f2481d0..d1b2aaaff 100644 --- a/runtime-mock/Cargo.toml +++ b/runtime-mock/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runtime-mock" -version = "1.0.1" +version = "1.0.2" description = "Mock of the HydraDX Runtime for testing purposes" authors = ["GalacticCouncil"] edition = "2021" diff --git a/runtime/hydradx/Cargo.toml b/runtime/hydradx/Cargo.toml index feaf5f862..974de3e40 100644 --- a/runtime/hydradx/Cargo.toml +++ b/runtime/hydradx/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-runtime" -version = "272.0.0" +version = "273.0.0" authors = ["GalacticCouncil"] edition = "2021" license = "Apache 2.0" diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index 2dacb5560..2aa9330f3 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -111,7 +111,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("hydradx"), impl_name: create_runtime_str!("hydradx"), authoring_version: 1, - spec_version: 272, + spec_version: 273, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, diff --git a/traits/Cargo.toml b/traits/Cargo.toml index fcf3fd4b9..1e3f2c9dd 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-traits" -version = "3.9.0" +version = "3.9.1" description = "Shared traits" authors = ["GalacticCouncil"] edition = "2021" From b3b64ab2fedb887dc5bbc80a24e676592f3cb637 Mon Sep 17 00:00:00 2001 From: dmoka Date: Thu, 26 Dec 2024 11:43:44 +0100 Subject: [PATCH 19/36] add missing event assertions for new LM wrapper functions --- .../src/omnipool_liquidity_mining.rs | 232 ++++++++++++------ 1 file changed, 158 insertions(+), 74 deletions(-) diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index 0a6155e65..595ed45d6 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -633,6 +633,49 @@ fn add_liquidity_with_limit_and_join_farms_should_work_for_multiple_farms() { .unwrap(); assert_eq!(deposit, expected_deposit); + + expect_omnipool_liquidity_added_events(vec![pallet_omnipool::Event::LiquidityAdded { + who: CHARLIE.into(), + asset_id: ETH, + amount: 1_000 * UNITS, + position_id: 7, + } + .into()]); + + expect_lm_events(vec![ + pallet_omnipool_liquidity_mining::Event::SharesDeposited { + global_farm_id: global_farm_1_id, + yield_farm_id: yield_farm_1_id, + deposit_id: 1, + asset_id: ETH, + who: CHARLIE.into(), + shares_amount: 1_000 * UNITS, + position_id: 7, + } + .into(), + pallet_omnipool_liquidity_mining::Event::SharesRedeposited { + global_farm_id: global_farm_2_id, + yield_farm_id: yield_farm_2_id, + deposit_id: 1, + asset_id: ETH, + who: CHARLIE.into(), + shares_amount: 1_000 * UNITS, + position_id: 7, + } + .into(), + pallet_omnipool_liquidity_mining::Event::SharesRedeposited { + global_farm_id: global_farm_3_id, + yield_farm_id: yield_farm_3_id, + deposit_id: 1, + asset_id: ETH, + who: CHARLIE.into(), + shares_amount: 1_000 * UNITS, + position_id: 7, + } + .into(), + ]); + + }); } @@ -680,10 +723,7 @@ fn add_liquidity_with_limit_and_join_farms_should_fail_when_reaches_limit() { 100 * UNITS, )); - let position_id = hydradx_runtime::Omnipool::next_position_id(); - set_relaychain_block_number(400); - let deposit_id = 1; let farms = vec![ (global_farm_1_id, yield_farm_1_id), (global_farm_2_id, yield_farm_2_id), @@ -848,6 +888,60 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_for_multiple_far .unwrap(); assert_eq!(deposit, expected_deposit); + + expect_stableswap_liquidity_added_events(vec![pallet_stableswap::Event::LiquidityAdded { + pool_id: stable_pool_id, + who: CHARLIE.into(), + shares: 20044549999405, + assets: vec![ + AssetAmount::new(stable_asset_1, 10 * UNITS), + AssetAmount::new(stable_asset_2, 10 * UNITS), + ], + } + .into()]); + + let stableswap_shares_amount = 20044549999405; + expect_omnipool_liquidity_added_events(vec![pallet_omnipool::Event::LiquidityAdded { + who: CHARLIE.into(), + asset_id: stable_pool_id, + amount: stableswap_shares_amount, + position_id: 8, + } + .into()]); + + expect_lm_events(vec![ + pallet_omnipool_liquidity_mining::Event::SharesDeposited { + global_farm_id: global_farm_1_id, + yield_farm_id: yield_farm_1_id, + deposit_id: 1, + asset_id: stable_pool_id, + who: CHARLIE.into(), + shares_amount: stableswap_shares_amount, + position_id: 8, + } + .into(), + pallet_omnipool_liquidity_mining::Event::SharesRedeposited { + global_farm_id: global_farm_2_id, + yield_farm_id: yield_farm_2_id, + deposit_id: 1, + asset_id: stable_pool_id, + who: CHARLIE.into(), + shares_amount: stableswap_shares_amount, + position_id: 8, + } + .into(), + pallet_omnipool_liquidity_mining::Event::SharesRedeposited { + global_farm_id: global_farm_3_id, + yield_farm_id: yield_farm_3_id, + deposit_id: 1, + asset_id: stable_pool_id, + who: CHARLIE.into(), + shares_amount: stableswap_shares_amount, + position_id: 8, + } + .into(), + ]); + TransactionOutcome::Commit(DispatchResult::Ok(())) }); }); @@ -1450,8 +1544,6 @@ fn create_yield_farm(id: GlobalFarmId, asset: AssetId) { } fn omnipool_add_liquidity(lp: AccountId, asset: AssetId, amount: Balance) -> primitives::ItemId { - use hydradx_runtime::Omnipool; - let current_position_id = Omnipool::next_position_id(); assert_ok!(Omnipool::add_liquidity(RuntimeOrigin::signed(lp), asset, amount)); @@ -1770,6 +1862,67 @@ pub fn expect_reward_claimed_events(e: Vec) { pretty_assertions::assert_eq!(reward_claimed_events, e); } +pub fn expect_lm_events(e: Vec) { + let last_events = test_utils::last_events::(10); + + let mut reward_claimed_events = vec![]; + + for event in &last_events { + let e = event.clone(); + if matches!( + e, + RuntimeEvent::OmnipoolLiquidityMining( + pallet_omnipool_liquidity_mining::Event::::RewardClaimed { .. } + ) | RuntimeEvent::OmnipoolLiquidityMining(pallet_omnipool_liquidity_mining::Event::< + hydradx_runtime::Runtime, + >::SharesDeposited { .. }) + | RuntimeEvent::OmnipoolLiquidityMining(pallet_omnipool_liquidity_mining::Event::< + hydradx_runtime::Runtime, + >::SharesRedeposited { .. }) + ) { + reward_claimed_events.push(e); + } + } + + pretty_assertions::assert_eq!(reward_claimed_events, e); +} + +pub fn expect_stableswap_liquidity_added_events(e: Vec) { + let last_events = test_utils::last_events::(40); + + let mut events = vec![]; + + for event in &last_events { + let e = event.clone(); + if matches!( + e, + RuntimeEvent::Stableswap(pallet_stableswap::Event::::LiquidityAdded { .. }) + ) { + events.push(e); + } + } + + pretty_assertions::assert_eq!(events, e); +} + +pub fn expect_omnipool_liquidity_added_events(e: Vec) { + let last_events = test_utils::last_events::(10); + + let mut events = vec![]; + + for event in &last_events { + let e = event.clone(); + if matches!( + e, + RuntimeEvent::Omnipool(pallet_omnipool::Event::::LiquidityAdded { .. }) + ) { + events.push(e); + } + } + + pretty_assertions::assert_eq!(events, e); +} + //TODO: duplicated, remove duplication pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { let initial_liquidity = 1_000_000_000_000_000_000_000u128; @@ -1892,35 +2045,6 @@ fn fund_treasury() -> DispatchResult { (10000 * UNITS).try_into().unwrap(), )); - //>::update_balance(HDX, &treasury, 500_000_000_000_000_000_000i128)?; - /*Currencies::update_balance( - RawOrigin::Root.into(), - treasury.clone(), - HDX.into(), - 500_000_000_000_000_000_000i128 as Amount, - )?; - - Currencies::update_balance( - RawOrigin::Root.into(), - treasury.clone(), - ETH.into(), - 500_000_000_000_000_000_000i128 as Amount, - )?; - - Currencies::update_balance( - RawOrigin::Root.into(), - treasury.clone(), - BTC.into(), - 500_000_000_000_000_000_000i128 as Amount, - )?; - - Currencies::update_balance( - RawOrigin::Root.into(), - treasury.clone(), - HDX.into(), - 500_000_000_000_000_000_000i128 as Amount, - )?;*/ - Ok(()) } const G_FARM_TOTAL_REWARDS: Balance = 10_000_000 * UNITS; @@ -1992,46 +2116,6 @@ fn initialize_omnipool() -> DispatchResult { None, )) })?; - /*let name = b"ETH".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; - with_transaction(|| { - TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( - None, - Some(name), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )) - })?;*/ - /*let name = b"BTC".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; - with_transaction(|| { - TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( - None, - Some(name), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )) - })?;*/ - - /*let name = b"DOT".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; - with_transaction(|| { - TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( - None, - Some(name), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )) - })?;*/ // Create account for token provider and set balance let owner: AccountId = ALICE.into(); From 218ad603bfbe51e73740cfcd0a0fb96fbe178691 Mon Sep 17 00:00:00 2001 From: dmoka Date: Thu, 26 Dec 2024 13:32:24 +0100 Subject: [PATCH 20/36] bump versions --- Cargo.lock | 24 ++++++++++---------- integration-tests/Cargo.toml | 2 +- pallets/omnipool-liquidity-mining/Cargo.toml | 2 +- pallets/omnipool/Cargo.toml | 2 +- pallets/stableswap/Cargo.toml | 2 +- pallets/staking/Cargo.toml | 2 +- runtime-mock/Cargo.toml | 2 +- runtime/hydradx/Cargo.toml | 2 +- runtime/hydradx/src/lib.rs | 2 +- traits/Cargo.toml | 2 +- 10 files changed, 21 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bbd718876..8d21513f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4897,7 +4897,7 @@ dependencies = [ "pallet-referrals", "pallet-route-executor", "pallet-stableswap", - "pallet-staking 4.0.1", + "pallet-staking 4.0.2", "pallet-transaction-multi-payment", "pallet-uniques", "pallet-xyk", @@ -4918,7 +4918,7 @@ dependencies = [ [[package]] name = "hydradx-runtime" -version = "276.0.0" +version = "277.0.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-parachain-system", @@ -5009,7 +5009,7 @@ dependencies = [ "pallet-scheduler", "pallet-session", "pallet-stableswap", - "pallet-staking 4.0.1", + "pallet-staking 4.0.2", "pallet-state-trie-migration", "pallet-timestamp", "pallet-tips", @@ -5062,7 +5062,7 @@ dependencies = [ [[package]] name = "hydradx-traits" -version = "3.10.0" +version = "3.11.0" dependencies = [ "frame-support", "impl-trait-for-tuples", @@ -8778,7 +8778,7 @@ dependencies = [ [[package]] name = "pallet-omnipool" -version = "4.3.7" +version = "4.3.8" dependencies = [ "bitflags 1.3.2", "frame-benchmarking", @@ -8805,7 +8805,7 @@ dependencies = [ [[package]] name = "pallet-omnipool-liquidity-mining" -version = "2.5.0" +version = "2.6.0" dependencies = [ "frame-benchmarking", "frame-support", @@ -9142,7 +9142,7 @@ dependencies = [ [[package]] name = "pallet-stableswap" -version = "4.1.1" +version = "4.1.2" dependencies = [ "bitflags 1.3.2", "frame-benchmarking", @@ -9167,7 +9167,7 @@ dependencies = [ [[package]] name = "pallet-staking" -version = "4.0.1" +version = "4.0.2" dependencies = [ "frame-benchmarking", "frame-support", @@ -12244,7 +12244,7 @@ dependencies = [ [[package]] name = "runtime-integration-tests" -version = "1.26.0" +version = "1.27.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-parachain-system", @@ -12316,7 +12316,7 @@ dependencies = [ "pallet-scheduler", "pallet-session", "pallet-stableswap", - "pallet-staking 4.0.1", + "pallet-staking 4.0.2", "pallet-timestamp", "pallet-tips", "pallet-transaction-multi-payment", @@ -12370,7 +12370,7 @@ dependencies = [ [[package]] name = "runtime-mock" -version = "1.0.2" +version = "1.0.3" dependencies = [ "frame-remote-externalities", "frame-support", @@ -12381,7 +12381,7 @@ dependencies = [ "pallet-asset-registry", "pallet-omnipool", "pallet-stableswap", - "pallet-staking 4.0.1", + "pallet-staking 4.0.2", "primitives", "scraper", "serde", diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index aebb4d1f7..0486ef987 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runtime-integration-tests" -version = "1.26.0" +version = "1.27.0" description = "Integration tests" authors = ["GalacticCouncil"] edition = "2021" diff --git a/pallets/omnipool-liquidity-mining/Cargo.toml b/pallets/omnipool-liquidity-mining/Cargo.toml index 14890102a..4ce2b9cc6 100644 --- a/pallets/omnipool-liquidity-mining/Cargo.toml +++ b/pallets/omnipool-liquidity-mining/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-omnipool-liquidity-mining" -version = "2.5.0" +version = "2.6.0" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/omnipool/Cargo.toml b/pallets/omnipool/Cargo.toml index e5cdb43c8..d2de0e299 100644 --- a/pallets/omnipool/Cargo.toml +++ b/pallets/omnipool/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-omnipool" -version = "4.3.7" +version = "4.3.8" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/stableswap/Cargo.toml b/pallets/stableswap/Cargo.toml index 77fa25e35..b5f0d490f 100644 --- a/pallets/stableswap/Cargo.toml +++ b/pallets/stableswap/Cargo.toml @@ -1,6 +1,6 @@ [package] name = 'pallet-stableswap' -version = '4.1.1' +version = '4.1.2' description = 'AMM for correlated assets' authors = ['GalacticCouncil'] edition = '2021' diff --git a/pallets/staking/Cargo.toml b/pallets/staking/Cargo.toml index cccb4f3f8..7095dcdfa 100644 --- a/pallets/staking/Cargo.toml +++ b/pallets/staking/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-staking" -version = "4.0.1" +version = "4.0.2" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/runtime-mock/Cargo.toml b/runtime-mock/Cargo.toml index d1b2aaaff..40995f56a 100644 --- a/runtime-mock/Cargo.toml +++ b/runtime-mock/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runtime-mock" -version = "1.0.2" +version = "1.0.3" description = "Mock of the HydraDX Runtime for testing purposes" authors = ["GalacticCouncil"] edition = "2021" diff --git a/runtime/hydradx/Cargo.toml b/runtime/hydradx/Cargo.toml index 87644ded0..98c887f7f 100644 --- a/runtime/hydradx/Cargo.toml +++ b/runtime/hydradx/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-runtime" -version = "276.0.0" +version = "277.0.0" authors = ["GalacticCouncil"] edition = "2021" license = "Apache 2.0" diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index bfdd37be9..9d0b0bbed 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -113,7 +113,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("hydradx"), impl_name: create_runtime_str!("hydradx"), authoring_version: 1, - spec_version: 276, + spec_version: 277, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, diff --git a/traits/Cargo.toml b/traits/Cargo.toml index e1cd13374..0654d2730 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-traits" -version = "3.10.0" +version = "3.11.0" description = "Shared traits" authors = ["GalacticCouncil"] edition = "2021" From bb6df3bcd932e58402d5c34f576d4f5c57dab8b8 Mon Sep 17 00:00:00 2001 From: dmoka Date: Thu, 26 Dec 2024 13:46:27 +0100 Subject: [PATCH 21/36] make clippy happy --- pallets/stableswap/src/benchmarks.rs | 2 +- pallets/staking/src/benchmarks.rs | 2 +- pallets/staking/src/integrations/democracy_legacy.rs | 3 +++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/pallets/stableswap/src/benchmarks.rs b/pallets/stableswap/src/benchmarks.rs index 21223f938..37e4618cf 100644 --- a/pallets/stableswap/src/benchmarks.rs +++ b/pallets/stableswap/src/benchmarks.rs @@ -100,7 +100,7 @@ benchmarks! { pool_id, BoundedVec::truncate_from(initial), )?; - }: _(RawOrigin::Signed(lp_provider.clone()), pool_id, added_liquidity) + }: _(RawOrigin::Signed(lp_provider.clone()), pool_id, added_liquidity.try_into().unwrap()) verify { assert!(T::Currency::free_balance(pool_id, &lp_provider) > 0u128); } diff --git a/pallets/staking/src/benchmarks.rs b/pallets/staking/src/benchmarks.rs index 765d6e5ca..7adf5bee5 100644 --- a/pallets/staking/src/benchmarks.rs +++ b/pallets/staking/src/benchmarks.rs @@ -23,7 +23,7 @@ use frame_benchmarking::benchmarks; use frame_system::{Pallet as System, RawOrigin}; use orml_traits::MultiCurrencyExtended; use sp_std::vec::Vec; - +use crate::types::Voting; const UNIT: u128 = 1_000_000_000_000; fn init_staking(non_dustable_balance: Balance) -> DispatchResult diff --git a/pallets/staking/src/integrations/democracy_legacy.rs b/pallets/staking/src/integrations/democracy_legacy.rs index 013dcf980..95de039f1 100644 --- a/pallets/staking/src/integrations/democracy_legacy.rs +++ b/pallets/staking/src/integrations/democracy_legacy.rs @@ -6,6 +6,9 @@ use orml_traits::MultiCurrencyExtended; use pallet_democracy::traits::DemocracyHooks; use pallet_democracy::{AccountVote, ReferendumIndex}; use sp_runtime::FixedPointNumber; +use sp_core::Get; +use crate::types::Vote; + pub struct LegacyStakingDemocracy(sp_std::marker::PhantomData); From 94c0e1568e76bfd29ae6482f0689ef9acc115dad Mon Sep 17 00:00:00 2001 From: dmoka Date: Thu, 26 Dec 2024 13:46:42 +0100 Subject: [PATCH 22/36] formatting --- integration-tests/src/omnipool_liquidity_mining.rs | 14 ++++++-------- pallets/stableswap/src/tests/price.rs | 2 +- pallets/staking/src/benchmarks.rs | 2 +- .../staking/src/integrations/democracy_legacy.rs | 5 ++--- pallets/staking/src/tests/tests.rs | 2 +- 5 files changed, 11 insertions(+), 14 deletions(-) diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index 19c26384e..46bb18fa0 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -640,7 +640,7 @@ fn add_liquidity_with_limit_and_join_farms_should_work_for_multiple_farms() { amount: 1_000 * UNITS, position_id: 7, } - .into()]); + .into()]); expect_lm_events(vec![ pallet_omnipool_liquidity_mining::Event::SharesDeposited { @@ -652,7 +652,7 @@ fn add_liquidity_with_limit_and_join_farms_should_work_for_multiple_farms() { shares_amount: 1_000 * UNITS, position_id: 7, } - .into(), + .into(), pallet_omnipool_liquidity_mining::Event::SharesRedeposited { global_farm_id: global_farm_2_id, yield_farm_id: yield_farm_2_id, @@ -662,7 +662,7 @@ fn add_liquidity_with_limit_and_join_farms_should_work_for_multiple_farms() { shares_amount: 1_000 * UNITS, position_id: 7, } - .into(), + .into(), pallet_omnipool_liquidity_mining::Event::SharesRedeposited { global_farm_id: global_farm_3_id, yield_farm_id: yield_farm_3_id, @@ -672,10 +672,8 @@ fn add_liquidity_with_limit_and_join_farms_should_work_for_multiple_farms() { shares_amount: 1_000 * UNITS, position_id: 7, } - .into(), + .into(), ]); - - }); } @@ -898,7 +896,7 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_for_multiple_far AssetAmount::new(stable_asset_2, 10 * UNITS), ], } - .into()]); + .into()]); let stableswap_shares_amount = 20044549999405; expect_omnipool_liquidity_added_events(vec![pallet_omnipool::Event::LiquidityAdded { @@ -907,7 +905,7 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_for_multiple_far amount: stableswap_shares_amount, position_id: 8, } - .into()]); + .into()]); expect_lm_events(vec![ pallet_omnipool_liquidity_mining::Event::SharesDeposited { diff --git a/pallets/stableswap/src/tests/price.rs b/pallets/stableswap/src/tests/price.rs index d18493486..309e180bc 100644 --- a/pallets/stableswap/src/tests/price.rs +++ b/pallets/stableswap/src/tests/price.rs @@ -1,8 +1,8 @@ use crate::tests::*; use crate::types::PoolInfo; use frame_support::assert_ok; +use frame_support::BoundedVec; use hydradx_traits::stableswap::AssetAmount; -use frame_support::{BoundedVec}; use sp_runtime::{FixedU128, Permill}; use std::num::NonZeroU16; diff --git a/pallets/staking/src/benchmarks.rs b/pallets/staking/src/benchmarks.rs index 7adf5bee5..cae834e65 100644 --- a/pallets/staking/src/benchmarks.rs +++ b/pallets/staking/src/benchmarks.rs @@ -17,13 +17,13 @@ use super::*; +use crate::types::Voting; use crate::types::{Conviction, Vote}; use frame_benchmarking::account; use frame_benchmarking::benchmarks; use frame_system::{Pallet as System, RawOrigin}; use orml_traits::MultiCurrencyExtended; use sp_std::vec::Vec; -use crate::types::Voting; const UNIT: u128 = 1_000_000_000_000; fn init_staking(non_dustable_balance: Balance) -> DispatchResult diff --git a/pallets/staking/src/integrations/democracy_legacy.rs b/pallets/staking/src/integrations/democracy_legacy.rs index 95de039f1..bc886415b 100644 --- a/pallets/staking/src/integrations/democracy_legacy.rs +++ b/pallets/staking/src/integrations/democracy_legacy.rs @@ -1,14 +1,13 @@ use crate::pallet::{PositionVotes, Positions, ProcessedVotes}; +use crate::types::Vote; use crate::types::{Action, Balance, Conviction}; use crate::{Config, Pallet}; use frame_support::dispatch::DispatchResult; use orml_traits::MultiCurrencyExtended; use pallet_democracy::traits::DemocracyHooks; use pallet_democracy::{AccountVote, ReferendumIndex}; -use sp_runtime::FixedPointNumber; use sp_core::Get; -use crate::types::Vote; - +use sp_runtime::FixedPointNumber; pub struct LegacyStakingDemocracy(sp_std::marker::PhantomData); diff --git a/pallets/staking/src/tests/tests.rs b/pallets/staking/src/tests/tests.rs index 651aa5d84..78d1b007b 100644 --- a/pallets/staking/src/tests/tests.rs +++ b/pallets/staking/src/tests/tests.rs @@ -5,12 +5,12 @@ use crate::{ use super::*; +use crate::types::Voting; use frame_system::RawOrigin; use mock::Staking; use pallet_conviction_voting::traits::VotingHooks; use pallet_conviction_voting::AccountVote; use pretty_assertions::assert_eq; -use crate::types::Voting; //NOTE: Referendums with even indexes are finished. #[test] From 01a6011573ce868c30c2d848776be1ec3d67d32b Mon Sep 17 00:00:00 2001 From: dmoka Date: Thu, 26 Dec 2024 13:47:21 +0100 Subject: [PATCH 23/36] remove wrong comment --- pallets/omnipool-liquidity-mining/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index de084a429..5e131aa79 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -1047,7 +1047,6 @@ pub mod pallet { Ok(()) } - /// Add documentation similar we have for other extrinsics /// This function allows user to add liquidity to stableswap pool, /// then adding the stable shares as liquidity to omnipool /// then use that omnipool shares to join multiple farms. From 9a7d451377034ffbcf76bc510ac7d96a9e3b7cab Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 13:36:09 +0100 Subject: [PATCH 24/36] removed not used method --- pallets/omnipool-liquidity-mining/src/lib.rs | 60 -------------------- 1 file changed, 60 deletions(-) diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index 5e131aa79..1159f645a 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -1215,64 +1215,4 @@ impl Pallet { Ok((deposit_id, lp_position)) } - - #[require_transactional] - fn do_withdraw_shares( - origin: OriginFor, - deposit_id: DepositId, - yield_farm_id: YieldFarmId, - ) -> Result { - let owner = Self::ensure_nft_owner(origin, deposit_id)?; - - //NOTE: not tested - this should never fail. - let position_id = OmniPositionId::::get(deposit_id) - .defensive_ok_or::>(InconsistentStateError::MissingLpPosition.into())?; - let lp_position = OmnipoolPallet::::load_position(position_id, Self::account_id())?; - - //NOTE: not tested - this should never fail. - let global_farm_id = T::LiquidityMiningHandler::get_global_farm_id(deposit_id, yield_farm_id) - .defensive_ok_or::>(InconsistentStateError::DepositDataNotFound.into())?; - - let (withdrawn_amount, claim_data, is_destroyed) = T::LiquidityMiningHandler::withdraw_lp_shares( - owner.clone(), - deposit_id, - global_farm_id, - yield_farm_id, - lp_position.asset_id, - )?; - - if let Some((reward_currency, claimed, _)) = claim_data { - if !claimed.is_zero() { - Self::deposit_event(Event::RewardClaimed { - global_farm_id, - yield_farm_id, - who: owner.clone(), - claimed, - reward_currency, - deposit_id, - }); - } - } - - Self::deposit_event(Event::SharesWithdrawn { - global_farm_id, - yield_farm_id, - who: owner.clone(), - amount: withdrawn_amount, - deposit_id, - }); - - if is_destroyed { - Self::unlock_lp_postion(deposit_id, &owner)?; - ::NFTHandler::burn( - &::NFTCollectionId::get(), - &deposit_id, - Some(&owner), - )?; - - Self::deposit_event(Event::DepositDestroyed { who: owner, deposit_id }); - } - - Ok(withdrawn_amount) - } } From c289478cac8eea8271a25ff38e14c34559390826 Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 13:45:32 +0100 Subject: [PATCH 25/36] add separate benchmark for add_liquidity_with_limit_and_join_farms --- .../benchmarking/omnipool_liquidity_mining.rs | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index 6aa26f5fd..e3a1bcbd8 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -752,6 +752,62 @@ runtime_benchmarks! { }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), BTC, 10 * BTC_ONE) + add_liquidity_with_limit_and_join_farms { + let c in 1..get_max_entries(); + + let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); + + let deposit_id = 1; + + initialize_omnipool(None)?; + + //gId: 1, yId: 2 + initialize_global_farm(owner.clone())?; + initialize_yield_farm(owner, 1, BTC)?; + let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); + let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC, 10 * BTC_ONE)?; + lm_deposit_shares(lp1, 1, 2, lp1_position_id)?; + + //gId: 3, yId: 4 + initialize_global_farm(owner2.clone())?; + initialize_yield_farm(owner2, 3, BTC)?; + let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC); + let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC, 10 * BTC_ONE)?; + lm_deposit_shares(lp2, 3, 4, lp2_position_id)?; + + //gId: 5, yId: 6 + initialize_global_farm(owner3.clone())?; + initialize_yield_farm(owner3, 5, BTC)?; + let lp3 = create_funded_account("lp_3", 1, 10 * BTC_ONE, BTC); + let lp3_position_id = omnipool_add_liquidity(lp3.clone(), BTC, 10 * BTC_ONE)?; + lm_deposit_shares(lp3, 5, 6, lp3_position_id)?; + + //gId: 7, yId: 8 + initialize_global_farm(owner4.clone())?; + initialize_yield_farm(owner4, 7, BTC)?; + let lp4 = create_funded_account("lp_4", 1, 10 * BTC_ONE, BTC); + let lp4_position_id = omnipool_add_liquidity(lp4.clone(), BTC, 10 * BTC_ONE)?; + lm_deposit_shares(lp4, 7, 8, lp4_position_id)?; + + //gId: 9, yId: 10 + initialize_global_farm(owner5.clone())?; + initialize_yield_farm(owner5, 9, BTC)?; + let lp5 = create_funded_account("lp_5", 1, 10 * BTC_ONE, BTC); + let lp5_position_id = omnipool_add_liquidity(lp5.clone(), BTC, 10 * BTC_ONE)?; + lm_deposit_shares(lp5, 9, 10, lp5_position_id)?; + + let lp6 = create_funded_account("lp_6", 5, 10 * BTC_ONE, BTC); + + set_period(200); + let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; + let farms = farms_entries[0..c as usize].to_vec(); + + }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), BTC, 10 * BTC_ONE, 10 * BTC_ONE) + exit_farms { let c in 1..get_max_entries(); From d119148587ffbddd80f6db399242f4f95f490de2 Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 14:06:23 +0100 Subject: [PATCH 26/36] merge add liq with limit optional param --- .../src/omnipool_liquidity_mining.rs | 9 +-- pallets/omnipool-liquidity-mining/src/lib.rs | 43 ++------------ .../src/tests/add_liquidity_and_join_farms.rs | 4 ++ ...add_liquidity_with_limit_and_join_farms.rs | 20 +++---- .../benchmarking/omnipool_liquidity_mining.rs | 56 ------------------- 5 files changed, 23 insertions(+), 109 deletions(-) diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index 46bb18fa0..1347c90d5 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -471,6 +471,7 @@ fn add_liquidity_and_join_farms_should_work_for_multiple_farms() { farms.try_into().unwrap(), ETH, 1_000 * UNITS, + None )); //Assert that the ownership of the nft should be transferred to omnipool account @@ -577,12 +578,12 @@ fn add_liquidity_with_limit_and_join_farms_should_work_for_multiple_farms() { (global_farm_3_id, yield_farm_3_id), ]; assert_ok!( - hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_with_limit_and_join_farms( + hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_and_join_farms( RuntimeOrigin::signed(CHARLIE.into()), farms.try_into().unwrap(), ETH, 1_000 * UNITS, - 1_000 * UNITS + Some(1_000 * UNITS) ) ); @@ -728,12 +729,12 @@ fn add_liquidity_with_limit_and_join_farms_should_fail_when_reaches_limit() { (global_farm_3_id, yield_farm_3_id), ]; assert_noop!( - hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_with_limit_and_join_farms( + hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_and_join_farms( RuntimeOrigin::signed(CHARLIE.into()), farms.try_into().unwrap(), ETH, 1_000 * UNITS, - 1_000 * UNITS + 1 + Some(1_000 * UNITS + 1) ), pallet_omnipool::Error::::SlippageLimit ); diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index 1159f645a..9bd3c201c 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -969,12 +969,14 @@ pub mod pallet { farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, asset: T::AssetId, amount: Balance, + min_shares_limit: Option ) -> DispatchResult { ensure_signed(origin.clone())?; ensure!(!farm_entries.is_empty(), Error::::NoFarmEntriesSpecified); + let min_shares_limit = min_shares_limit.unwrap_or(Balance::MIN); let position_id = - OmnipoolPallet::::do_add_liquidity_with_limit(origin.clone(), asset, amount, Balance::MIN)?; + OmnipoolPallet::::do_add_liquidity_with_limit(origin.clone(), asset, amount, min_shares_limit)?; Self::join_farms(origin, farm_entries, position_id)?; @@ -1010,43 +1012,6 @@ pub mod pallet { Ok(()) } - /// This function allows user to add liquidity then use that shares to join multiple farms. - /// - /// Limit protection is applied. - /// - /// Parameters: - /// - `origin`: owner of the omnipool position to deposit into the liquidity mining. - /// - `farm_entries`: list of farms to join. - /// - `asset`: id of the asset to be deposited into the liquidity mining. - /// - `amount`: amount of the asset to be deposited into the liquidity mining. - /// - `min_shares_limit`: The min amount of delta share asset the user should receive in the position - /// - /// Emits `SharesDeposited` event for the first farm entry - /// Emits `SharesRedeposited` event for each farm entry after the first one - #[pallet::call_index(17)] - #[pallet::weight(::WeightInfo::add_liquidity_and_join_farms(farm_entries.len() as u32))] //Same benchmark as add_liquidity_and_join_farms since it's the same logic - pub fn add_liquidity_with_limit_and_join_farms( - origin: OriginFor, - farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, - asset: T::AssetId, - amount: Balance, - min_shares_limit: Balance, - ) -> DispatchResult { - ensure_signed(origin.clone())?; - ensure!(!farm_entries.is_empty(), Error::::NoFarmEntriesSpecified); - - let position_id = crate::OmnipoolPallet::::do_add_liquidity_with_limit( - origin.clone(), - asset, - amount, - min_shares_limit, - )?; - - Self::join_farms(origin, farm_entries, position_id)?; - - Ok(()) - } - /// This function allows user to add liquidity to stableswap pool, /// then adding the stable shares as liquidity to omnipool /// then use that omnipool shares to join multiple farms. @@ -1062,7 +1027,7 @@ pub mod pallet { /// Emits `SharesDeposited` event for the first farm entry /// Emits `SharesRedeposited` event for each farm entry after the first one /// - #[pallet::call_index(18)] + #[pallet::call_index(16)] #[pallet::weight(::WeightInfo::add_liquidity_stableswap_omnipool_and_join_farms(farm_entries.len() as u32))] pub fn add_liquidity_stableswap_omnipool_and_join_farms( origin: OriginFor, diff --git a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_and_join_farms.rs b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_and_join_farms.rs index 4cedb3903..790975df9 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_and_join_farms.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_and_join_farms.rs @@ -98,6 +98,7 @@ fn add_liquidity_and_join_farms_should_work_with_single_yield_farm() { yield_farms.try_into().unwrap(), asset_in_position, amount, + None )); //Assert that liquidity is added @@ -236,6 +237,7 @@ fn join_farms_should_work_with_multiple_yield_farm() { yield_farms.try_into().unwrap(), KSM, amount, + None )); //Assert that liquidity is added @@ -413,6 +415,7 @@ fn add_liquidity_and_join_farms_should_fail_when_origin_is_none() { yield_farms.try_into().unwrap(), KSM, 10 * ONE, + None ), BadOrigin ); @@ -481,6 +484,7 @@ fn join_farms_should_fail_when_no_farms_specified() { farms.try_into().unwrap(), KSM, 10 * ONE, + None ), Error::::NoFarmEntriesSpecified ); diff --git a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs index 980624a06..2f82993e0 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_with_limit_and_join_farms.rs @@ -83,12 +83,12 @@ fn add_liquidity_with_limit_and_join_farms_should_work_with_single_yield_farm() let amount = 20 * ONE; let yield_farms = vec![(gc_g_farm_id, gc_y_farm_id)]; - assert_ok!(OmnipoolMining::add_liquidity_with_limit_and_join_farms( + assert_ok!(OmnipoolMining::add_liquidity_and_join_farms( RuntimeOrigin::signed(LP1), yield_farms.try_into().unwrap(), asset_in_position, amount, - u128::MIN + Some(u128::MIN) )); //Assert that liquidity is added @@ -210,12 +210,12 @@ fn add_liquidity_join_farms_should_fail_when_doesnt_reach_limit() { let yield_farms = vec![(gc_g_farm_id, gc_y_farm_id)]; assert_noop!( - OmnipoolMining::add_liquidity_with_limit_and_join_farms( + OmnipoolMining::add_liquidity_and_join_farms( RuntimeOrigin::signed(LP1), yield_farms.try_into().unwrap(), asset_in_position, amount, - amount + 1 + Some(amount + 1) ), pallet_omnipool::Error::::SlippageLimit ); @@ -296,12 +296,12 @@ fn join_farms_should_work_with_multiple_yield_farm() { (bob_g_farm_id, bob_y_farm_id), ]; - assert_ok!(OmnipoolMining::add_liquidity_with_limit_and_join_farms( + assert_ok!(OmnipoolMining::add_liquidity_and_join_farms( RuntimeOrigin::signed(LP1), yield_farms.try_into().unwrap(), KSM, amount, - u128::MIN + Some(u128::MIN) )); //Assert that liquidity is added @@ -474,12 +474,12 @@ fn add_liquidity_and_join_farms_should_fail_when_origin_is_none() { ]; assert_noop!( - OmnipoolMining::add_liquidity_with_limit_and_join_farms( + OmnipoolMining::add_liquidity_and_join_farms( RuntimeOrigin::none(), yield_farms.try_into().unwrap(), KSM, 10 * ONE, - u128::MIN + Some(u128::MIN) ), BadOrigin ); @@ -543,12 +543,12 @@ fn join_farms_should_fail_when_no_farms_specified() { let farms = vec![]; assert_noop!( - OmnipoolMining::add_liquidity_with_limit_and_join_farms( + OmnipoolMining::add_liquidity_and_join_farms( RuntimeOrigin::signed(LP1), farms.try_into().unwrap(), KSM, 10 * ONE, - u128::MIN + Some(u128::MIN) ), Error::::NoFarmEntriesSpecified ); diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index e3a1bcbd8..6aa26f5fd 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -752,62 +752,6 @@ runtime_benchmarks! { }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), BTC, 10 * BTC_ONE) - add_liquidity_with_limit_and_join_farms { - let c in 1..get_max_entries(); - - let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); - let owner2 = create_funded_account("owner2", 1, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); - let owner3 = create_funded_account("owner3", 2, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); - let owner4 = create_funded_account("owner4", 3, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); - let owner5 = create_funded_account("owner5", 4, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); - - let deposit_id = 1; - - initialize_omnipool(None)?; - - //gId: 1, yId: 2 - initialize_global_farm(owner.clone())?; - initialize_yield_farm(owner, 1, BTC)?; - let lp1 = create_funded_account("lp_1", 1, 10 * BTC_ONE, BTC); - let lp1_position_id = omnipool_add_liquidity(lp1.clone(), BTC, 10 * BTC_ONE)?; - lm_deposit_shares(lp1, 1, 2, lp1_position_id)?; - - //gId: 3, yId: 4 - initialize_global_farm(owner2.clone())?; - initialize_yield_farm(owner2, 3, BTC)?; - let lp2 = create_funded_account("lp_2", 1, 10 * BTC_ONE, BTC); - let lp2_position_id = omnipool_add_liquidity(lp2.clone(), BTC, 10 * BTC_ONE)?; - lm_deposit_shares(lp2, 3, 4, lp2_position_id)?; - - //gId: 5, yId: 6 - initialize_global_farm(owner3.clone())?; - initialize_yield_farm(owner3, 5, BTC)?; - let lp3 = create_funded_account("lp_3", 1, 10 * BTC_ONE, BTC); - let lp3_position_id = omnipool_add_liquidity(lp3.clone(), BTC, 10 * BTC_ONE)?; - lm_deposit_shares(lp3, 5, 6, lp3_position_id)?; - - //gId: 7, yId: 8 - initialize_global_farm(owner4.clone())?; - initialize_yield_farm(owner4, 7, BTC)?; - let lp4 = create_funded_account("lp_4", 1, 10 * BTC_ONE, BTC); - let lp4_position_id = omnipool_add_liquidity(lp4.clone(), BTC, 10 * BTC_ONE)?; - lm_deposit_shares(lp4, 7, 8, lp4_position_id)?; - - //gId: 9, yId: 10 - initialize_global_farm(owner5.clone())?; - initialize_yield_farm(owner5, 9, BTC)?; - let lp5 = create_funded_account("lp_5", 1, 10 * BTC_ONE, BTC); - let lp5_position_id = omnipool_add_liquidity(lp5.clone(), BTC, 10 * BTC_ONE)?; - lm_deposit_shares(lp5, 9, 10, lp5_position_id)?; - - let lp6 = create_funded_account("lp_6", 5, 10 * BTC_ONE, BTC); - - set_period(200); - let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; - let farms = farms_entries[0..c as usize].to_vec(); - - }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), BTC, 10 * BTC_ONE, 10 * BTC_ONE) - exit_farms { let c in 1..get_max_entries(); From 60fc4fdfc8f79e74480f9f785488d2b2449ed688 Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 14:07:56 +0100 Subject: [PATCH 27/36] fix doc comment --- pallets/omnipool-liquidity-mining/src/lib.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index 9bd3c201c..af66d0629 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -1018,10 +1018,9 @@ pub mod pallet { /// /// Parameters: /// - `origin`: owner of the omnipool position to deposit into the liquidity mining. + /// - `stable_pool_id`: id of the stableswap pool to add liquidity to. + /// - `stable_asset_amounts`: amount of each asset to be deposited into the stableswap pool. /// - `farm_entries`: list of farms to join. - /// - `asset`: id of the asset to be deposited into the liquidity mining. - /// - `amount`: amount of the asset to be deposited into the liquidity mining. - /// - `min_shares_limit`: The min amount of delta share asset the user should receive in the position /// /// Emits `LiquidityAdded` events from both pool /// Emits `SharesDeposited` event for the first farm entry From 2dd05bc82d0cd513734bbdc6def2dddefb1d8b9f Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 14:44:33 +0100 Subject: [PATCH 28/36] remove duplicated test --- .../src/omnipool_liquidity_mining.rs | 221 +----------------- .../src/tests/mock.rs | 2 +- 2 files changed, 2 insertions(+), 221 deletions(-) diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index 1347c90d5..bca79eb14 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -47,6 +47,7 @@ use warehouse_liquidity_mining::{ }; use xcm_emulator::TestExt; + #[macro_export] macro_rules! assert_nft_owner { ( $coll:expr, $item: expr, $acc:expr ) => {{ @@ -2111,223 +2112,3 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { Ok((pool_id, asset_in, asset_out)) } -#[test] -pub fn create_yield_farm2() { - TestNet::reset(); - - Hydra::execute_with(|| { - fund_treasury().unwrap(); //To prevent BelowMinimum error - - let owner = ALICE; - >::update_balance(0, &owner.into(), INITIAL_BALANCE as i128).unwrap(); - assert_ok!(>::update_balance( - HDX, - &owner.into(), - G_FARM_TOTAL_REWARDS.try_into().unwrap(), - )); - let global_farm_id = 1; - - initialize_omnipool().unwrap(); - - initialize_global_farm(owner.clone().into()).unwrap(); - initialize_yield_farm(owner.clone().into(), global_farm_id, BTC.into()).unwrap(); - - let lp = BOB; - >::update_balance(0, &lp.into(), INITIAL_BALANCE as i128).unwrap(); - assert_ok!(>::update_balance( - BTC, - &lp.into(), - (10 * BTC_ONE).try_into().unwrap(), - )); - - let position_id = omnipool_add_liquidity(lp.clone().into(), BTC.into(), 10 * BTC_ONE); - - set_period(100); - lm_deposit_shares(lp.into(), global_farm_id, 2, position_id).unwrap(); - - set_period(200); - - assert_ok!(hydradx_runtime::OmnipoolLiquidityMining::create_yield_farm( - RuntimeOrigin::signed(owner.clone().into()), - global_farm_id, - ETH.into(), - FixedU128::one(), - Some(LoyaltyCurve::default()) - )); - }); -} -pub const INITIAL_BALANCE: Balance = 10_000_000 * UNITS; -const BTC_ONE: Balance = 100_000_000; - -fn fund_treasury() -> DispatchResult { - let account = Treasury::account_id(); - - >::update_balance(0, &account, INITIAL_BALANCE as i128).unwrap(); - assert_ok!(>::update_balance( - HDX, - &account, - (10000 * UNITS).try_into().unwrap(), - )); - - assert_ok!(>::update_balance( - ETH, - &account, - (10000 * UNITS).try_into().unwrap(), - )); - - assert_ok!(>::update_balance( - HDX, - &account, - (10000 * UNITS).try_into().unwrap(), - )); - - Ok(()) -} -const G_FARM_TOTAL_REWARDS: Balance = 10_000_000 * UNITS; - -fn initialize_global_farm(owner: AccountId) -> DispatchResult { - OmnipoolLiquidityMining::create_global_farm( - RawOrigin::Root.into(), - G_FARM_TOTAL_REWARDS, - BlockNumberFor::::from(100_000_u32), - BlockNumberFor::::from(1_u32), - HDX.into(), - owner, - Perquintill::from_percent(20), - 1_000, - FixedU128::one(), - )?; - - seed_lm_pot(); - - Ok(()) -} - -use orml_traits::MultiCurrencyExtended; -fn initialize_yield_farm(owner: AccountId, id: GlobalFarmId, asset: AssetId) -> DispatchResult { - OmnipoolLiquidityMining::create_yield_farm(RawOrigin::Signed(owner).into(), id, asset, FixedU128::one(), None) -} - -fn initialize_omnipool() -> DispatchResult { - let stable_amount: Balance = 1_000_000_000_000_000u128; - let native_amount: Balance = 1_000_000_000_000_000u128; - let stable_price: FixedU128 = FixedU128::from((1, 2)); - let native_price: FixedU128 = FixedU128::from(1); - - let acc = Omnipool::protocol_account(); - - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DAI.into(), stable_amount as Amount)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), HDX.into(), native_amount as Amount)?; - - fund(ALICE.clone().into(), HDX.into(), 10_000 * UNITS)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DAI.into(), stable_amount as Amount)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), HDX.into(), native_amount as Amount)?; - - Omnipool::add_token( - RawOrigin::Root.into(), - HDX.into(), - native_price, - Permill::from_percent(100), - acc.clone(), - )?; - Omnipool::add_token( - RawOrigin::Root.into(), - DAI.into(), - stable_price, - Permill::from_percent(100), - acc.clone(), - )?; - - let name = b"BSX".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; - // Register new asset in asset registry - with_transaction(|| { - TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( - None, - Some(name), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )) - })?; - - // Create account for token provider and set balance - let owner: AccountId = ALICE.into(); - - let token_price = FixedU128::from((1, 5)); - let token_amount = 200_000_000_000_000u128; - - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), ETH.into(), token_amount as Amount)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), BTC.into(), token_amount as Amount)?; - Currencies::update_balance(RawOrigin::Root.into(), acc.clone(), DOT.into(), token_amount as Amount)?; - - Omnipool::add_token( - RawOrigin::Root.into(), - ETH.into(), - token_price, - Permill::from_percent(100), - owner.clone(), - )?; - - Omnipool::add_token( - RawOrigin::Root.into(), - BTC.into(), - token_price, - Permill::from_percent(100), - owner.clone(), - )?; - - Omnipool::add_token( - RawOrigin::Root.into(), - DOT.into(), - token_price, - Permill::from_percent(100), - owner, - )?; - - //NOTE: This is necessary for oracle to provide price. - set_period(10); - - do_lrna_hdx_trade(); - - Ok(()) -} - -fn fund(to: AccountId, currency: AssetId, amount: Balance) -> DispatchResult { - Currencies::deposit(currency, &to, amount) -} - -fn lm_deposit_shares(who: AccountId, g_id: GlobalFarmId, y_id: YieldFarmId, position_id: ItemId) -> DispatchResult { - OmnipoolLiquidityMining::deposit_shares(RawOrigin::Signed(who).into(), g_id, y_id, position_id) -} - -use frame_support::traits::OnFinalize; -use frame_support::traits::OnInitialize; -use frame_system::pallet_prelude::BlockNumberFor; -use hydradx_runtime::OmnipoolLiquidityMining; -use hydradx_traits::liquidity_mining::YieldFarmId; -use primitives::Amount; -use primitives::ItemId; - -fn set_period(to: u32) { - //NOTE: predefined global farm has period size = 1 block. - while hydradx_runtime::System::block_number() < to { - let b = hydradx_runtime::System::block_number(); - - as OnFinalize>>::on_finalize(b); - as frame_support::traits::OnFinalize< - BlockNumberFor, - >>::on_finalize(b); - - as OnInitialize>>::on_initialize( - b + 1_u32, - ); - as frame_support::traits::OnInitialize< - BlockNumberFor, - >>::on_initialize(b + 1_u32); - - hydradx_runtime::System::set_block_number(b + 1_u32); - } -} diff --git a/pallets/omnipool-liquidity-mining/src/tests/mock.rs b/pallets/omnipool-liquidity-mining/src/tests/mock.rs index fe7632d8c..24465cd5b 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mock.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mock.rs @@ -68,7 +68,7 @@ pub const DAI: AssetId = 2; pub const DOT: AssetId = 1_000; pub const KSM: AssetId = 1_001; pub const ACA: AssetId = 1_002; -pub const USDT: AssetId = 2_000; +pub const USDT: AssetId = 1_003; pub const LP1: AccountId = 1; pub const LP2: AccountId = 2; From be0598d7bee95566565894a8889fd62c4bfb11a7 Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 14:55:44 +0100 Subject: [PATCH 29/36] fix benchmark tests --- .../src/benchmarking/omnipool_liquidity_mining.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs index 6aa26f5fd..c53921ee2 100644 --- a/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/benchmarking/omnipool_liquidity_mining.rs @@ -608,12 +608,7 @@ runtime_benchmarks! { set_period(400); - }: { - //We fire and forget as claim rewards is disabled - let _ = OmnipoolLiquidityMining::claim_rewards(RawOrigin::Signed(lp1).into(), deposit_id, 10); - } verify { - - } + }: _(RawOrigin::Signed(lp1), deposit_id, 10) withdraw_shares { let owner = create_funded_account("owner", 0, G_FARM_TOTAL_REWARDS, REWARD_CURRENCY); @@ -750,7 +745,7 @@ runtime_benchmarks! { let farms_entries = [(1,2), (3,4), (5,6), (7,8), (9, 10)]; let farms = farms_entries[0..c as usize].to_vec(); - }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), BTC, 10 * BTC_ONE) + }: _(RawOrigin::Signed(lp6), farms.try_into().unwrap(), BTC, 10 * BTC_ONE, Some(10 * BTC_ONE)) exit_farms { let c in 1..get_max_entries(); From d924359eec9ffc733732cc592e8143156841804a Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 14:56:20 +0100 Subject: [PATCH 30/36] formatting --- .../src/omnipool_liquidity_mining.rs | 18 +++++++----------- pallets/omnipool-liquidity-mining/src/lib.rs | 2 +- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index bca79eb14..fbf457b07 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -47,7 +47,6 @@ use warehouse_liquidity_mining::{ }; use xcm_emulator::TestExt; - #[macro_export] macro_rules! assert_nft_owner { ( $coll:expr, $item: expr, $acc:expr ) => {{ @@ -578,15 +577,13 @@ fn add_liquidity_with_limit_and_join_farms_should_work_for_multiple_farms() { (global_farm_2_id, yield_farm_2_id), (global_farm_3_id, yield_farm_3_id), ]; - assert_ok!( - hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_and_join_farms( - RuntimeOrigin::signed(CHARLIE.into()), - farms.try_into().unwrap(), - ETH, - 1_000 * UNITS, - Some(1_000 * UNITS) - ) - ); + assert_ok!(hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_and_join_farms( + RuntimeOrigin::signed(CHARLIE.into()), + farms.try_into().unwrap(), + ETH, + 1_000 * UNITS, + Some(1_000 * UNITS) + )); //Assert that the ownership of the nft should be transferred to omnipool account let lm_account = hydradx_runtime::OmnipoolLiquidityMining::account_id(); @@ -2111,4 +2108,3 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { Ok((pool_id, asset_in, asset_out)) } - diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index af66d0629..cf63f8c2f 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -969,7 +969,7 @@ pub mod pallet { farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, asset: T::AssetId, amount: Balance, - min_shares_limit: Option + min_shares_limit: Option, ) -> DispatchResult { ensure_signed(origin.clone())?; ensure!(!farm_entries.is_empty(), Error::::NoFarmEntriesSpecified); From 274d57ff3cf19941d580151254e8f505a82f4103 Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 15:23:05 +0100 Subject: [PATCH 31/36] rebench ommnipool lm on ref machine --- .../pallet_omnipool_liquidity_mining.rs | 152 +++++++++--------- 1 file changed, 79 insertions(+), 73 deletions(-) diff --git a/runtime/hydradx/src/weights/pallet_omnipool_liquidity_mining.rs b/runtime/hydradx/src/weights/pallet_omnipool_liquidity_mining.rs index 5413daa42..a3bbe625a 100644 --- a/runtime/hydradx/src/weights/pallet_omnipool_liquidity_mining.rs +++ b/runtime/hydradx/src/weights/pallet_omnipool_liquidity_mining.rs @@ -19,7 +19,7 @@ //! Autogenerated weights for `pallet_omnipool_liquidity_mining` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-12-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2025-01-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` @@ -53,32 +53,22 @@ pub struct HydraWeight(PhantomData); impl pallet_omnipool_liquidity_mining::WeightInfo for HydraWeight { /// Storage: `AssetRegistry::Assets` (r:2 w:0) /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:2 w:2) - /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `OmnipoolWarehouseLM::FarmSequencer` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::FarmSequencer` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Router::SkipEd` (r:1 w:0) - /// Proof: `Router::SkipEd` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) - /// Storage: `Duster::AccountBlacklist` (r:1 w:1) + /// Storage: `Duster::AccountBlacklist` (r:0 w:1) /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) - /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) - /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) - /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:0 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) fn create_global_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `2927` + // Measured: `2129` // Estimated: `6196` - // Minimum execution time: 108_804_000 picoseconds. - Weight::from_parts(109_967_000, 6196) - .saturating_add(T::DbWeight::get().reads(12_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) + // Minimum execution time: 90_481_000 picoseconds. + Weight::from_parts(91_380_000, 6196) + .saturating_add(T::DbWeight::get().reads(5_u64)) + .saturating_add(T::DbWeight::get().writes(5_u64)) } /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) @@ -86,10 +76,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn update_global_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `3644` + // Measured: `3677` // Estimated: `3670` - // Minimum execution time: 39_051_000 picoseconds. - Weight::from_parts(39_347_000, 3670) + // Minimum execution time: 38_098_000 picoseconds. + Weight::from_parts(38_901_000, 3670) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -101,10 +91,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) fn terminate_global_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `5476` + // Measured: `5542` // Estimated: `6196` - // Minimum execution time: 101_287_000 picoseconds. - Weight::from_parts(102_290_000, 6196) + // Minimum execution time: 100_122_000 picoseconds. + Weight::from_parts(100_967_000, 6196) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -126,10 +116,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `OmnipoolWarehouseLM::YieldFarm` (`max_values`: None, `max_size`: Some(198), added: 2673, mode: `MaxEncodedLen`) fn create_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `6716` + // Measured: `6782` // Estimated: `6294` - // Minimum execution time: 150_403_000 picoseconds. - Weight::from_parts(151_610_000, 6294) + // Minimum execution time: 148_370_000 picoseconds. + Weight::from_parts(149_053_000, 6294) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -149,10 +139,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn update_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `7222` + // Measured: `7288` // Estimated: `6294` - // Minimum execution time: 154_461_000 picoseconds. - Weight::from_parts(155_496_000, 6294) + // Minimum execution time: 150_769_000 picoseconds. + Weight::from_parts(151_538_000, 6294) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -170,10 +160,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn stop_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `6828` + // Measured: `6861` // Estimated: `6294` - // Minimum execution time: 149_416_000 picoseconds. - Weight::from_parts(150_646_000, 6294) + // Minimum execution time: 144_649_000 picoseconds. + Weight::from_parts(145_558_000, 6294) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -193,10 +183,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn resume_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `7339` + // Measured: `7405` // Estimated: `6294` - // Minimum execution time: 152_894_000 picoseconds. - Weight::from_parts(153_877_000, 6294) + // Minimum execution time: 148_870_000 picoseconds. + Weight::from_parts(150_397_000, 6294) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -210,10 +200,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn terminate_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `5877` + // Measured: `5910` // Estimated: `6196` - // Minimum execution time: 97_304_000 picoseconds. - Weight::from_parts(97_707_000, 6196) + // Minimum execution time: 95_762_000 picoseconds. + Weight::from_parts(96_563_000, 6196) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -249,10 +239,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `OmnipoolWarehouseLM::Deposit` (`max_values`: None, `max_size`: Some(385), added: 2860, mode: `MaxEncodedLen`) fn deposit_shares() -> Weight { // Proof Size summary in bytes: - // Measured: `10092` + // Measured: `10158` // Estimated: `11598` - // Minimum execution time: 238_913_000 picoseconds. - Weight::from_parts(240_368_000, 11598) + // Minimum execution time: 234_027_000 picoseconds. + Weight::from_parts(235_062_000, 11598) .saturating_add(T::DbWeight::get().reads(17_u64)) .saturating_add(T::DbWeight::get().writes(14_u64)) } @@ -278,19 +268,35 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn redeposit_shares() -> Weight { // Proof Size summary in bytes: - // Measured: `13014` + // Measured: `13080` // Estimated: `11598` - // Minimum execution time: 201_956_000 picoseconds. - Weight::from_parts(203_655_000, 11598) + // Minimum execution time: 198_366_000 picoseconds. + Weight::from_parts(200_041_000, 11598) .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } + /// Storage: `Uniques::Asset` (r:1 w:0) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::Deposit` (r:1 w:1) + /// Proof: `OmnipoolWarehouseLM::Deposit` (`max_values`: None, `max_size`: Some(385), added: 2860, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::YieldFarm` (r:1 w:1) + /// Proof: `OmnipoolWarehouseLM::YieldFarm` (`max_values`: None, `max_size`: Some(198), added: 2673, mode: `MaxEncodedLen`) + /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) + /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:1 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:3) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `EmaOracle::Oracles` (r:2 w:0) + /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn claim_rewards() -> Weight { // Proof Size summary in bytes: - // Measured: `679` - // Estimated: `0` - // Minimum execution time: 9_614_000 picoseconds. - Weight::from_parts(9_805_000, 0) + // Measured: `10326` + // Estimated: `8799` + // Minimum execution time: 196_703_000 picoseconds. + Weight::from_parts(197_662_000, 8799) + .saturating_add(T::DbWeight::get().reads(10_u64)) + .saturating_add(T::DbWeight::get().writes(6_u64)) } /// Storage: `Uniques::Asset` (r:2 w:2) /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) @@ -318,10 +324,10 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(113), added: 2588, mode: `MaxEncodedLen`) fn withdraw_shares() -> Weight { // Proof Size summary in bytes: - // Measured: `8796` + // Measured: `8862` // Estimated: `8799` - // Minimum execution time: 290_740_000 picoseconds. - Weight::from_parts(298_216_000, 8799) + // Minimum execution time: 282_836_000 picoseconds. + Weight::from_parts(284_344_000, 8799) .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(15_u64)) } @@ -358,12 +364,12 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// The range of component `c` is `[1, 5]`. fn join_farms(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `18180 + c * (507 ±0)` + // Measured: `18246 + c * (507 ±0)` // Estimated: `11598 + c * (2680 ±0)` - // Minimum execution time: 242_801_000 picoseconds. - Weight::from_parts(143_876_531, 11598) - // Standard Error: 56_986 - .saturating_add(Weight::from_parts(102_112_481, 0).saturating_mul(c.into())) + // Minimum execution time: 236_921_000 picoseconds. + Weight::from_parts(140_743_915, 11598) + // Standard Error: 42_402 + .saturating_add(Weight::from_parts(99_358_082, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(14_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(c.into()))) .saturating_add(T::DbWeight::get().writes(11_u64)) @@ -429,12 +435,12 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// The range of component `c` is `[1, 5]`. fn add_liquidity_and_join_farms(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `19713 + c * (507 ±0)` + // Measured: `19814 + c * (507 ±0)` // Estimated: `14250 + c * (2680 ±0)` - // Minimum execution time: 450_627_000 picoseconds. - Weight::from_parts(349_467_292, 14250) - // Standard Error: 100_882 - .saturating_add(Weight::from_parts(105_492_164, 0).saturating_mul(c.into())) + // Minimum execution time: 437_831_000 picoseconds. + Weight::from_parts(339_543_241, 14250) + // Standard Error: 99_795 + .saturating_add(Weight::from_parts(102_639_074, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(36_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(c.into()))) .saturating_add(T::DbWeight::get().writes(24_u64)) @@ -468,12 +474,12 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// The range of component `c` is `[1, 5]`. fn exit_farms(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `10759 + c * (518 ±0)` + // Measured: `10825 + c * (518 ±0)` // Estimated: `6294 + c * (2680 ±0)` - // Minimum execution time: 247_897_000 picoseconds. - Weight::from_parts(85_622_107, 6294) - // Standard Error: 252_234 - .saturating_add(Weight::from_parts(164_088_535, 0).saturating_mul(c.into())) + // Minimum execution time: 242_444_000 picoseconds. + Weight::from_parts(85_667_874, 6294) + // Standard Error: 267_883 + .saturating_add(Weight::from_parts(158_223_923, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(10_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(c.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -545,12 +551,12 @@ impl pallet_omnipool_liquidity_mining::WeightInfo for H /// The range of component `c` is `[1, 5]`. fn add_liquidity_stableswap_omnipool_and_join_farms(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `22068 + c * (507 ±0)` + // Measured: `22169 + c * (507 ±0)` // Estimated: `34569 + c * (2680 ±0)` - // Minimum execution time: 1_600_568_000 picoseconds. - Weight::from_parts(1_514_241_156, 34569) - // Standard Error: 366_013 - .saturating_add(Weight::from_parts(104_749_719, 0).saturating_mul(c.into())) + // Minimum execution time: 1_556_415_000 picoseconds. + Weight::from_parts(1_475_121_600, 34569) + // Standard Error: 254_438 + .saturating_add(Weight::from_parts(100_323_450, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(62_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(c.into()))) .saturating_add(T::DbWeight::get().writes(35_u64)) From f39e64f6e19775be17fed26cce9b84192344cb36 Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 16:46:24 +0100 Subject: [PATCH 32/36] only join farms when specified --- .../src/omnipool_liquidity_mining.rs | 110 ++++++++++++++++++ pallets/omnipool-liquidity-mining/src/lib.rs | 5 +- 2 files changed, 113 insertions(+), 2 deletions(-) diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index fbf457b07..9535fdce5 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -944,6 +944,116 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_work_for_multiple_far }); } +#[test] +fn add_liquidity_stableswap_omnipool_and_join_farms_should_add_only_liquidty_when_no_farms_specified() { + TestNet::reset(); + + Hydra::execute_with(|| { + let _ = with_transaction(|| { + //Arrange + let (stable_pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + + init_omnipool(); + seed_lm_pot(); + + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + stable_pool_id, + 30_000_000 * UNITS as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + stable_pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); + + //NOTE: necessary to get oracle price. + hydradx_run_to_block(100); + + set_relaychain_block_number(300); + + assert_ok!(hydradx_runtime::Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + CHARLIE.into(), + ETH, + 10_000 * UNITS as i128, + )); + + //Add some liquidiity to make sure that it does not interfere with the new liquidty add + assert_ok!(hydradx_runtime::Omnipool::add_liquidity( + RuntimeOrigin::signed(CHARLIE.into()), + ETH, + 100 * UNITS, + )); + + let position_id = hydradx_runtime::Omnipool::next_position_id(); + + set_relaychain_block_number(400); + let deposit_id = 1; + let farms = vec![]; + + //Act + assert_ok!(hydradx_runtime::Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_1, + 100 * UNITS as i128, + )); + assert_ok!(hydradx_runtime::Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_2, + 100 * UNITS as i128, + )); + assert_ok!( + hydradx_runtime::OmnipoolLiquidityMining::add_liquidity_stableswap_omnipool_and_join_farms( + RuntimeOrigin::signed(CHARLIE.into()), + stable_pool_id, + vec![ + AssetAmount::new(stable_asset_1, 10 * UNITS), + AssetAmount::new(stable_asset_2, 10 * UNITS) + ] + .try_into() + .unwrap(), + farms.try_into().unwrap() + ) + ); + + assert_nft_owner!(hydradx_runtime::OmnipoolCollectionId::get(), position_id, CHARLIE.into()); + + set_relaychain_block_number(500); + + expect_stableswap_liquidity_added_events(vec![pallet_stableswap::Event::LiquidityAdded { + pool_id: stable_pool_id, + who: CHARLIE.into(), + shares: 20044549999405, + assets: vec![ + AssetAmount::new(stable_asset_1, 10 * UNITS), + AssetAmount::new(stable_asset_2, 10 * UNITS), + ], + } + .into()]); + + let stableswap_shares_amount = 20044549999405; + expect_omnipool_liquidity_added_events(vec![pallet_omnipool::Event::LiquidityAdded { + who: CHARLIE.into(), + asset_id: stable_pool_id, + amount: stableswap_shares_amount, + position_id: 8, + } + .into()]); + + expect_lm_events(vec![]); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} + #[test] fn withdraw_shares_should_work_when_deposit_exists() { TestNet::reset(); diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index cf63f8c2f..0af71d5f5 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -1035,7 +1035,6 @@ pub mod pallet { farm_entries: BoundedVec<(GlobalFarmId, YieldFarmId), T::MaxFarmEntriesPerDeposit>, ) -> DispatchResult { let who = ensure_signed(origin.clone())?; - ensure!(!farm_entries.is_empty(), Error::::NoFarmEntriesSpecified); let stablepool_shares = T::Stableswap::add_liquidity(who, stable_pool_id, stable_asset_amounts.to_vec())?; @@ -1046,7 +1045,9 @@ pub mod pallet { Balance::MIN, )?; - Self::join_farms(origin, farm_entries, position_id)?; + if !farm_entries.is_empty() { + Self::join_farms(origin, farm_entries, position_id)?; + } Ok(()) } From 94be437e3e19b2bc6217d7997ddcc0749c42588a Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 16:48:05 +0100 Subject: [PATCH 33/36] bump runtime version --- Cargo.lock | 2 +- runtime/hydradx/Cargo.toml | 2 +- runtime/hydradx/src/lib.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8d21513f6..d8627bb70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4918,7 +4918,7 @@ dependencies = [ [[package]] name = "hydradx-runtime" -version = "277.0.0" +version = "278.0.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-parachain-system", diff --git a/runtime/hydradx/Cargo.toml b/runtime/hydradx/Cargo.toml index 98c887f7f..91b0ade81 100644 --- a/runtime/hydradx/Cargo.toml +++ b/runtime/hydradx/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-runtime" -version = "277.0.0" +version = "278.0.0" authors = ["GalacticCouncil"] edition = "2021" license = "Apache 2.0" diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index 9d0b0bbed..3ec6418bd 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -113,7 +113,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("hydradx"), impl_name: create_runtime_str!("hydradx"), authoring_version: 1, - spec_version: 277, + spec_version: 278, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, From 48cef98031ca69bbc000722e769d86028e7c9a9d Mon Sep 17 00:00:00 2001 From: dmoka Date: Fri, 3 Jan 2025 16:48:15 +0100 Subject: [PATCH 34/36] formatting --- integration-tests/src/omnipool_liquidity_mining.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/integration-tests/src/omnipool_liquidity_mining.rs b/integration-tests/src/omnipool_liquidity_mining.rs index 9535fdce5..18f2b00e9 100644 --- a/integration-tests/src/omnipool_liquidity_mining.rs +++ b/integration-tests/src/omnipool_liquidity_mining.rs @@ -1023,7 +1023,11 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_add_only_liquidty_whe ) ); - assert_nft_owner!(hydradx_runtime::OmnipoolCollectionId::get(), position_id, CHARLIE.into()); + assert_nft_owner!( + hydradx_runtime::OmnipoolCollectionId::get(), + position_id, + CHARLIE.into() + ); set_relaychain_block_number(500); @@ -1036,7 +1040,7 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_add_only_liquidty_whe AssetAmount::new(stable_asset_2, 10 * UNITS), ], } - .into()]); + .into()]); let stableswap_shares_amount = 20044549999405; expect_omnipool_liquidity_added_events(vec![pallet_omnipool::Event::LiquidityAdded { @@ -1045,7 +1049,7 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_add_only_liquidty_whe amount: stableswap_shares_amount, position_id: 8, } - .into()]); + .into()]); expect_lm_events(vec![]); From 9bb2171ea7b9e6f527a797841a2050f255abb146 Mon Sep 17 00:00:00 2001 From: dmoka Date: Mon, 6 Jan 2025 12:32:41 +0100 Subject: [PATCH 35/36] delete not valid test --- ...dity_stableswap_omnipool_and_join_farms.rs | 76 +------------------ 1 file changed, 1 insertion(+), 75 deletions(-) diff --git a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs index 775f596a8..c10aff35e 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs @@ -408,78 +408,4 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_fail_when_origin_is_n BadOrigin ); }); -} - -#[test] -fn add_liquidity_stableswap_omnipool_and_join_farms_should_fail_when_no_farm_specified() { - let token_amount = 2000 * ONE; - ExtBuilder::default() - .with_endowed_accounts(vec![ - (Omnipool::protocol_account(), DAI, 1000 * ONE), - (Omnipool::protocol_account(), HDX, NATIVE_AMOUNT), - (LP1, STABLESWAP_POOL_ID, 500000 * ONE), - (LP1, KSM, 5000 * ONE), - (LP2, DOT, 2000 * ONE), - (GC, HDX, 100_000_000 * ONE), - (CHARLIE, HDX, 100_000_000 * ONE), - (BOB, HDX, 100_000_000 * ONE), - (ALICE, KSM, 10_000 * ONE), - (BOB, DOT, 10_000 * ONE), - ]) - .with_registered_asset(KSM) - .with_registered_asset(DOT) - .with_registered_asset(STABLESWAP_POOL_ID) - .with_initial_pool(FixedU128::from_float(0.5), FixedU128::from(1)) - .with_token(KSM, FixedU128::from_float(0.65), LP1, token_amount) - .with_token(STABLESWAP_POOL_ID, FixedU128::from_float(0.65), LP1, token_amount) - .with_global_farm( - //id: 1 - 80_000_000 * ONE, - 2_628_000, - 1, - HDX, - GC, - Perquintill::from_float(0.000_000_15_f64), - 1_000, - FixedU128::one(), - ) - .with_global_farm( - //id: 2 - 80_000_000 * ONE, - 2_628_000, - 1, - HDX, - CHARLIE, - Perquintill::from_float(0.000_000_15_f64), - 1_000, - FixedU128::one(), - ) - .with_global_farm( - //id: 3 - 60_000_000 * ONE, - 2_428_000, - 1, - HDX, - BOB, - Perquintill::from_float(0.000_000_14_f64), - 1_000, - FixedU128::one(), - ) - .with_yield_farm(GC, 1, STABLESWAP_POOL_ID, FixedU128::one(), None) //id: 4 - .build() - .execute_with(|| { - let amount = 20 * ONE; - let yield_farms = vec![]; - - //Act and assert - assert_noop!( - OmnipoolMining::add_liquidity_stableswap_omnipool_and_join_farms( - RuntimeOrigin::signed(LP1), - STABLESWAP_POOL_ID, - vec![AssetAmount::new(USDT, amount)].try_into().unwrap(), - yield_farms.try_into().unwrap(), - ), - Error::::NoFarmEntriesSpecified - ); - }); -} +} \ No newline at end of file From 13861e969e640e7e703adb97cd60fed33dd3393b Mon Sep 17 00:00:00 2001 From: dmoka Date: Mon, 6 Jan 2025 12:34:23 +0100 Subject: [PATCH 36/36] formatting --- .../tests/add_liquidity_stableswap_omnipool_and_join_farms.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs index c10aff35e..637de0cf6 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/add_liquidity_stableswap_omnipool_and_join_farms.rs @@ -408,4 +408,4 @@ fn add_liquidity_stableswap_omnipool_and_join_farms_should_fail_when_origin_is_n BadOrigin ); }); -} \ No newline at end of file +}