Skip to content

Commit

Permalink
feat: 🎸 benchmark
Browse files Browse the repository at this point in the history
  • Loading branch information
yooml committed Jun 5, 2024
1 parent 0db3c43 commit fcc6100
Show file tree
Hide file tree
Showing 14 changed files with 403 additions and 158 deletions.
18 changes: 10 additions & 8 deletions Cargo.lock

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

16 changes: 8 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,14 @@ bifrost-channel-commission = { path = "pallets/channel-commission", default-f
bifrost-clouds-convert = { path = "pallets/clouds-convert", default-features = false }

# Zenlink
merkle-distributor = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "add-new-fee-receiver", default-features = false }
zenlink-protocol = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "add-new-fee-receiver", default-features = false }
zenlink-protocol-rpc = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "add-new-fee-receiver" }
zenlink-protocol-runtime-api = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "add-new-fee-receiver", default-features = false }
zenlink-stable-amm = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "add-new-fee-receiver", default-features = false }
zenlink-stable-amm-rpc = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "add-new-fee-receiver" }
zenlink-stable-amm-runtime-api = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "add-new-fee-receiver", default-features = false }
zenlink-swap-router = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "add-new-fee-receiver", default-features = false }
merkle-distributor = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "release-polkadot-v1.6.0", default-features = false }
zenlink-protocol = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "release-polkadot-v1.6.0", default-features = false }
zenlink-protocol-rpc = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "release-polkadot-v1.6.0" }
zenlink-protocol-runtime-api = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "release-polkadot-v1.6.0", default-features = false }
zenlink-stable-amm = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "release-polkadot-v1.6.0", default-features = false }
zenlink-stable-amm-rpc = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "release-polkadot-v1.6.0" }
zenlink-stable-amm-runtime-api = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "release-polkadot-v1.6.0", default-features = false }
zenlink-swap-router = { git = "https://github.com/bifrost-finance/Zenlink-DEX-Module", branch = "release-polkadot-v1.6.0", default-features = false }

# Orml
orml-tokens = { version = "0.7.0", default-features = false }
Expand Down
2 changes: 2 additions & 0 deletions pallets/buy-back/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ sp-runtime = { workspace = true }
sp-std = { workspace = true }
xcm = { workspace = true }
zenlink-protocol = { workspace = true }
bifrost-ve-minting = { workspace = true }

[dev-dependencies]
bifrost-asset-registry = { workspace = true }
Expand All @@ -39,6 +40,7 @@ sp-core = { workspace = true }
sp-io = { workspace = true }
xcm-builder = { workspace = true }
xcm-executor = { workspace = true }
env_logger = { workspace = true }

[features]
default = ["std"]
Expand Down
63 changes: 24 additions & 39 deletions pallets/buy-back/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,71 +20,56 @@

#![cfg(feature = "runtime-benchmarks")]

use crate::{BalanceOf, Call, Config, Info, Pallet as SystemMaker, Pallet, *};
use bifrost_primitives::{CurrencyId, TokenSymbol};
use crate::{BalanceOf, Call, Config, Pallet, Pallet as BuyBack, *};
use bifrost_primitives::{CurrencyId, TokenSymbol, DOT};
use frame_benchmarking::v1::{account, benchmarks, BenchmarkError};
use frame_support::{
assert_ok,
traits::{EnsureOrigin, Hooks},
};
use frame_system::RawOrigin;
use orml_traits::MultiCurrency;
use sp_core::Get;
use sp_runtime::traits::{AccountIdConversion, UniqueSaturatedFrom};
// use crate::{Pallet as SystemMaker, *};
use sp_runtime::traits::UniqueSaturatedFrom;

benchmarks! {
set_config {
set_vtoken {
let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
let info = Info {
vcurrency_id: CurrencyId::VToken(TokenSymbol::KSM),
annualization: 600_000u32,
granularity: 1000u32.into(),
minimum_redeem: 20000u32.into()
};
}: _<T::RuntimeOrigin>(origin,CurrencyId::Token(TokenSymbol::KSM),info)
}: _<T::RuntimeOrigin>(origin,CurrencyId::VToken(TokenSymbol::KSM),1_000_000u32.into(),Permill::from_percent(2),1000u32.into(),1000u32.into(),true)

charge {
let test_account: T::AccountId = account("seed",1,1);

T::MultiCurrency::deposit(CurrencyId::Token(TokenSymbol::DOT), &test_account, BalanceOf::<T>::unique_saturated_from(100000000000u128))?;
}: _(RawOrigin::Signed(test_account),CurrencyId::Token(TokenSymbol::DOT),BalanceOf::<T>::unique_saturated_from(10000000000u128))
T::MultiCurrency::deposit(DOT, &test_account, BalanceOf::<T>::unique_saturated_from(1_000_000_000_000_000u128))?;
}: _(RawOrigin::Signed(test_account),DOT,BalanceOf::<T>::unique_saturated_from(9_000_000_000_000u128))

close {
remove_vtoken {
let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
assert_ok!(SystemMaker::<T>::set_config(
assert_ok!(BuyBack::<T>::set_vtoken(
T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?,
CurrencyId::Token(TokenSymbol::KSM),
Info {
vcurrency_id: CurrencyId::VToken(TokenSymbol::KSM),
annualization: 600_000u32,
granularity: 1000u32.into(),
minimum_redeem: 20000u32.into()
},
CurrencyId::VToken(TokenSymbol::KSM),
1_000_000u32.into(),
Permill::from_percent(2),
1000u32.into(),
1000u32.into(),
true
));
}: _<T::RuntimeOrigin>(origin,CurrencyId::Token(TokenSymbol::KSM))

payout {
let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
let pallet_account: T::AccountId = T::SystemMakerPalletId::get().into_account_truncating();
T::MultiCurrency::deposit(CurrencyId::Token(TokenSymbol::DOT), &pallet_account, BalanceOf::<T>::unique_saturated_from(100000000000u128))?;
}: _<T::RuntimeOrigin>(origin,CurrencyId::Token(TokenSymbol::DOT),BalanceOf::<T>::unique_saturated_from(10000000000u128))

on_idle {
let origin = T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
assert_ok!(SystemMaker::<T>::set_config(
assert_ok!(BuyBack::<T>::set_vtoken(
T::ControlOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?,
CurrencyId::Token(TokenSymbol::KSM),
Info {
vcurrency_id: CurrencyId::VToken(TokenSymbol::KSM),
annualization: 600_000u32,
granularity: 1000u32.into(),
minimum_redeem: 20000u32.into()
},
CurrencyId::VToken(TokenSymbol::KSM),
1_000_000u32.into(),
Permill::from_percent(2),
1000u32.into(),
1000u32.into(),
true
));
}: {
SystemMaker::<T>::on_idle(BlockNumberFor::<T>::from(0u32),Weight::from_parts(0, u64::MAX));
BuyBack::<T>::on_idle(BlockNumberFor::<T>::from(0u32),Weight::from_parts(0, u64::MAX));
}

impl_benchmark_test_suite!(SystemMaker,crate::mock::ExtBuilder::default().build(),crate::mock::Runtime);
impl_benchmark_test_suite!(BuyBack,crate::mock::ExtBuilder::default().build(),crate::mock::Runtime);
}
24 changes: 19 additions & 5 deletions pallets/buy-back/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ pub mod weights;
use bifrost_primitives::{
currency::BNC, CurrencyId, CurrencyIdConversion, CurrencyIdRegister, TryConvertFrom,
};
use bifrost_ve_minting::VeMintingInterface;
use cumulus_primitives_core::ParaId;
use frame_support::{
pallet_prelude::*,
Expand Down Expand Up @@ -94,6 +95,13 @@ pub mod pallet {
type ParachainId: Get<ParaId>;

type CurrencyIdRegister: CurrencyIdRegister<CurrencyId>;

type VeMinting: VeMintingInterface<
AccountIdOf<Self>,
CurrencyIdOf<Self>,
BalanceOf<Self>,
BlockNumberFor<Self>,
>;
}

#[pallet::event]
Expand Down Expand Up @@ -133,7 +141,7 @@ pub mod pallet {
let buyback_address = T::BuyBackAccount::get().into_account_truncating();
let liquidity_address = T::LiquidityAccount::get().into_account_truncating();
for (asset_id, mut info) in Infos::<T>::iter() {
if info.if_auto == false {
if !info.if_auto {
continue;
}

Expand Down Expand Up @@ -172,7 +180,7 @@ pub mod pallet {
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::set_config())]
#[pallet::weight(T::WeightInfo::set_vtoken())]
pub fn set_vtoken(
origin: OriginFor<T>,
asset_id: CurrencyIdOf<T>,
Expand Down Expand Up @@ -235,7 +243,7 @@ pub mod pallet {
}

#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::close())]
#[pallet::weight(T::WeightInfo::remove_vtoken())]
pub fn remove_vtoken(origin: OriginFor<T>, asset_id: CurrencyIdOf<T>) -> DispatchResult {
T::ControlOrigin::ensure_origin(origin)?;

Expand All @@ -249,7 +257,10 @@ pub mod pallet {

impl<T: Config> Pallet<T> {
#[transactional]
fn buy_back(buyback_address: &AccountIdOf<T>, currency_id: CurrencyId) -> DispatchResult {
pub fn buy_back(
buyback_address: &AccountIdOf<T>,
currency_id: CurrencyId,
) -> DispatchResult {
let asset_id: AssetId =
AssetId::try_convert_from(currency_id, T::ParachainId::get().into())
.map_err(|_| DispatchError::Other("Conversion Error."))?;
Expand All @@ -266,7 +277,10 @@ pub mod pallet {
0,
&path,
&buyback_address,
)
)?;

let bnc_balance = T::MultiCurrency::free_balance(BNC, &buyback_address);
T::VeMinting::notify_reward(0, &Some(buyback_address.clone()), vec![(BNC, bnc_balance)])
}

#[transactional]
Expand Down
38 changes: 35 additions & 3 deletions pallets/buy-back/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use frame_support::{
derive_impl, ord_parameter_types,
pallet_prelude::Get,
parameter_types,
sp_runtime::{DispatchError, DispatchResult},
sp_runtime::{traits::ConvertInto, DispatchError, DispatchResult},
traits::{Everything, Nothing},
PalletId,
};
Expand Down Expand Up @@ -77,6 +77,7 @@ frame_support::construct_runtime!(
ZenlinkProtocol: zenlink_protocol,
AssetRegistry: bifrost_asset_registry,
PolkadotXcm: pallet_xcm,
VeMinting: bifrost_ve_minting,
}
);

Expand Down Expand Up @@ -105,7 +106,7 @@ impl frame_system::Config for Runtime {
}

parameter_types! {
pub const GetNativeCurrencyId: CurrencyId = CurrencyId::Native(TokenSymbol::ASG);
pub const GetNativeCurrencyId: CurrencyId = CurrencyId::Native(TokenSymbol::BNC);
}

pub type AdaptedBasicCurrency =
Expand Down Expand Up @@ -184,6 +185,7 @@ impl bifrost_buy_back::Config for Runtime {
type LiquidityAccount = LiquidityAccount;
type ParachainId = ParaInfo;
type CurrencyIdRegister = AssetIdMaps<Runtime>;
type VeMinting = VeMinting;
}

pub struct ParaInfo;
Expand Down Expand Up @@ -509,6 +511,35 @@ impl pallet_xcm::Config for Runtime {
type RemoteLockConsumerIdentifier = ();
}

parameter_types! {
pub const VeMintingTokenType: CurrencyId = CurrencyId::VToken(TokenSymbol::BNC);
pub VeMintingPalletId: PalletId = PalletId(*b"bf/vemnt");
pub IncentivePalletId: PalletId = PalletId(*b"bf/veict");
pub const Week: BlockNumber = 50400; // a week
pub const MaxBlock: BlockNumber = 10512000; // four years
pub const Multiplier: Balance = 10_u128.pow(12);
pub const VoteWeightMultiplier: Balance = 1;
pub const MaxPositions: u32 = 10;
pub const MarkupRefreshLimit: u32 = 100;
}

impl bifrost_ve_minting::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type MultiCurrency = Currencies;
type ControlOrigin = EnsureSignedBy<One, AccountId>;
type TokenType = VeMintingTokenType;
type VeMintingPalletId = VeMintingPalletId;
type IncentivePalletId = IncentivePalletId;
type WeightInfo = ();
type BlockNumberToBalance = ConvertInto;
type Week = Week;
type MaxBlock = MaxBlock;
type Multiplier = Multiplier;
type VoteWeightMultiplier = VoteWeightMultiplier;
type MaxPositions = MaxPositions;
type MarkupRefreshLimit = MarkupRefreshLimit;
}

pub struct ExtBuilder {
endowed_accounts: Vec<(AccountId, CurrencyId, Balance)>,
}
Expand All @@ -533,13 +564,14 @@ impl ExtBuilder {
// (ALICE, RelayCurrencyId::get(), 10000),
(ALICE, VKSM, 10000),
(BOB, KSM, 100),
(BuyBackAccount::get().into_account_truncating(), VKSM, 10000),
(BuyBackAccount::get().into_account_truncating(), VKSM, 9000),
(BuyBackAccount::get().into_account_truncating(), KSM, 10000),
])
}

pub fn build(self) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
env_logger::try_init().unwrap_or(());

pallet_balances::GenesisConfig::<Runtime> {
balances: self
Expand Down
Loading

0 comments on commit fcc6100

Please sign in to comment.