From b695fd39bccaf461c7533388e2c2fba3ec26a007 Mon Sep 17 00:00:00 2001 From: Adel Golghalyani Date: Mon, 4 Nov 2024 13:47:03 +0100 Subject: [PATCH 01/11] add mocking for tests + benchmarks --- pallets/pallet-bonded-coins/src/lib.rs | 2 +- pallets/pallet-bonded-coins/src/mock.rs | 332 +++++++++++++++++++++++- 2 files changed, 332 insertions(+), 2 deletions(-) diff --git a/pallets/pallet-bonded-coins/src/lib.rs b/pallets/pallet-bonded-coins/src/lib.rs index 95ae8b8407..682e2838ac 100644 --- a/pallets/pallet-bonded-coins/src/lib.rs +++ b/pallets/pallet-bonded-coins/src/lib.rs @@ -366,7 +366,7 @@ pub mod pallet { ensure!(entry.is_manager(&who), Error::::NoPermission); entry.manager = manager.clone(); - Self::deposit_event(Event::ManagerUpdate { + Self::deposit_event(Event::ManagerUpdated { id: pool_id.clone(), manager, }); diff --git a/pallets/pallet-bonded-coins/src/mock.rs b/pallets/pallet-bonded-coins/src/mock.rs index 92cae110d3..a537b19988 100644 --- a/pallets/pallet-bonded-coins/src/mock.rs +++ b/pallets/pallet-bonded-coins/src/mock.rs @@ -1,6 +1,44 @@ -use substrate_fixed::types::I75F53; +use frame_support::{ + parameter_types, + traits::{ConstU128, ConstU32}, + weights::constants::RocksDbWeight, + Hashable, +}; +use frame_system::{EnsureRoot, EnsureSigned}; +use sp_runtime::{ + traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, + BoundedVec, BuildStorage, DispatchError, MultiSignature, +}; +use substrate_fixed::types::{I75F53, U75F53}; + +use crate::{ + curves::{polynomial::PolynomialParameters, Curve}, + traits::{FreezeAccounts, ResetTeam}, + types::{Locks, PoolStatus}, + Config, DepositCurrencyBalanceOf, PoolDetailsOf, +}; pub type Float = I75F53; +pub(crate) type FloatInput = U75F53; +pub type Hash = sp_core::H256; +pub type Balance = u128; +pub type AssetId = u32; +pub type Signature = MultiSignature; +pub type AccountPublic = ::Signer; +pub type AccountId = ::AccountId; + +// accounts +pub(crate) const ACCOUNT_00: AccountId = AccountId::new([0u8; 32]); +pub(crate) const ACCOUNT_01: AccountId = AccountId::new([1u8; 32]); +const ACCOUNT_99: AccountId = AccountId::new([99u8; 32]); +// assets +pub(crate) const DEFAULT_BONDED_CURRENCY_ID: AssetId = 0; +pub(crate) const DEFAULT_COLLATERAL_CURRENCY_ID: AssetId = AssetId::MAX; +pub(crate) const DEFAULT_COLLATERAL_DENOMINATION: u8 = 10; +pub(crate) const DEFAULT_BONDED_DENOMINATION: u8 = 10; +pub(crate) const DEFAULT_COLLATERAL_UNIT: Balance = 10u128.pow(10); +pub(crate) const DEFAULT_BONDED_UNIT: Balance = 10u128.pow(10); +pub const UNIT_NATIVE: Balance = 10u128.pow(15); // helper functions pub fn assert_relative_eq(target: Float, expected: Float, epsilon: Float) { @@ -11,3 +49,295 @@ pub fn assert_relative_eq(target: Float, expected: Float, epsilon: Float) { target ); } + +pub(crate) fn get_linear_bonding_curve() -> Curve { + let m = Float::from_num(0); + let n = Float::from_num(2); + let o = Float::from_num(3); + Curve::Polynomial(PolynomialParameters { m, n, o }) +} + +pub(crate) fn calculate_pool_id(currencies: Vec) -> AccountId { + AccountId::from(currencies.blake2_256()) +} + +#[cfg(test)] +pub mod runtime { + + use super::*; + + pub type Block = frame_system::mocking::MockBlock; + + pub fn generate_pool_details( + currencies: Vec, + curve: Curve, + transferable: Option, + state: Option>, + manager: Option, + collateral_id: Option, + owner: Option, + ) -> PoolDetailsOf { + let bonded_currencies = BoundedVec::truncate_from(currencies); + let transferable = transferable.unwrap_or(false); + let state = state.unwrap_or(PoolStatus::Active); + let owner = owner.unwrap_or(ACCOUNT_99); + let collateral_id = collateral_id.unwrap_or(DEFAULT_COLLATERAL_CURRENCY_ID); + PoolDetailsOf:: { + curve, + manager, + transferable, + bonded_currencies, + state, + collateral_id, + denomination: 10, + owner, + } + } + + pub(crate) fn events() -> Vec> { + System::events() + .into_iter() + .map(|r| r.event) + .filter_map(|e| { + if let RuntimeEvent::BondingPallet(e) = e { + Some(e) + } else { + None + } + }) + .collect::>() + } + + // trait implementations + impl ResetTeam for Assets { + fn reset_team( + _id: Self::AssetId, + _owner: AccountId, + _admin: AccountId, + _issuer: AccountId, + _freezer: AccountId, + ) -> frame_support::dispatch::DispatchResult { + Ok(()) + } + } + + impl FreezeAccounts for Assets { + type Error = DispatchError; + fn freeze(_asset_id: &AssetId, _who: &AccountId) -> Result<(), Self::Error> { + Ok(()) + } + + fn thaw(_asset_id: &AssetId, _who: &AccountId) -> Result<(), Self::Error> { + Ok(()) + } + } + + frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Balances: pallet_balances, + Assets: pallet_assets, + BondingPallet: crate, + } + ); + + parameter_types! { + pub const SS58Prefix: u8 = 38; + pub const BlockHashCount: u64 = 250; + } + + impl frame_system::Config for Test { + type AccountData = pallet_balances::AccountData; + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = BlockHashCount; + type BlockLength = (); + type BlockWeights = (); + type DbWeight = RocksDbWeight; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Lookup = IdentityLookup; + type MaxConsumers = ConstU32<16>; + type Nonce = u64; + type OnKilledAccount = (); + type OnNewAccount = (); + type OnSetCode = (); + type PalletInfo = PalletInfo; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeTask = (); + type SS58Prefix = SS58Prefix; + type SystemWeightInfo = (); + type Version = (); + } + + parameter_types! { + pub const ExistentialDeposit: Balance = 500; + pub const MaxLocks: u32 = 50; + pub const MaxReserves: u32 = 50; + } + + impl pallet_balances::Config for Test { + type AccountStore = System; + type Balance = Balance; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type FreezeIdentifier = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type RuntimeEvent = RuntimeEvent; + type RuntimeFreezeReason = (); + type RuntimeHoldReason = RuntimeHoldReason; + type WeightInfo = (); + } + + parameter_types! { + pub const StringLimit: u32 = 50; + + } + impl pallet_assets::Config for Test { + type ApprovalDeposit = ConstU128<0>; + type AssetAccountDeposit = ConstU128<0>; + type AssetDeposit = ConstU128<0>; + type AssetId = AssetId; + type AssetIdParameter = AssetId; + type Balance = Balance; + type CallbackHandle = (); + type CreateOrigin = EnsureSigned; + type Currency = Balances; + type Extra = (); + type ForceOrigin = EnsureRoot; + type Freezer = (); + type MetadataDepositBase = ConstU128<0>; + type MetadataDepositPerByte = ConstU128<0>; + type RemoveItemsLimit = ConstU32<5>; + type RuntimeEvent = RuntimeEvent; + type StringLimit = StringLimit; + type WeightInfo = (); + } + parameter_types! { + pub const CurrencyDeposit: Balance = 500; + pub const MaxCurrencies: u32 = 50; + pub const CollateralAssetId: u32 = u32::MAX; + } + + impl Config for Test { + type AssetId = AssetId; + type BaseDeposit = ExistentialDeposit; + type CollateralCurrency = Assets; + type CurveParameterInput = FloatInput; + type CurveParameterType = Float; + type DefaultOrigin = EnsureSigned; + type DepositCurrency = Balances; + type DepositPerCurrency = CurrencyDeposit; + type ForceOrigin = EnsureRoot; + type Fungibles = Assets; + type MaxCurrencies = MaxCurrencies; + type MaxStringLength = StringLimit; + type PoolCreateOrigin = EnsureSigned; + type PoolId = AccountId; + type RuntimeEvent = RuntimeEvent; + type RuntimeHoldReason = RuntimeHoldReason; + } + + #[derive(Clone, Default)] + pub(crate) struct ExtBuilder { + native_assets: Vec<(AccountId, DepositCurrencyBalanceOf)>, + bonded_balance: Vec<(AssetId, AccountId, Balance)>, + // denomination, pool_id, PoolDetails + pools: Vec<(u8, AccountId, PoolDetailsOf)>, + collaterals: Vec, + } + + impl ExtBuilder { + pub(crate) fn with_native_balances( + mut self, + native_assets: Vec<(AccountId, DepositCurrencyBalanceOf)>, + ) -> Self { + self.native_assets = native_assets; + self + } + + pub(crate) fn with_pools(mut self, pools: Vec<(u8, AccountId, PoolDetailsOf)>) -> Self { + self.pools = pools; + self + } + + pub(crate) fn with_bonded_balance(mut self, bonded_balance: Vec<(AssetId, AccountId, Balance)>) -> Self { + self.bonded_balance = bonded_balance; + self + } + + pub(crate) fn build(mut self) -> sp_io::TestExternalities { + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); + pallet_balances::GenesisConfig:: { + balances: self.native_assets.clone(), + } + .assimilate_storage(&mut storage) + .expect("assimilate should not fail"); + + let collateral_assets = self.collaterals.iter().map(|id| (*id, ACCOUNT_99, false, 0)); + + pallet_assets::GenesisConfig:: { + assets: self + .pools + .iter() + .map(|(_, owner, pool)| { + pool.bonded_currencies + .iter() + .map(|id| (*id, owner.to_owned(), false, 1u128)) + .collect::>() + }) + .flatten() + .chain(collateral_assets) + .collect(), + + accounts: self.bonded_balance, + metadata: self + .pools + .iter() + .map(|(denomination, _, pool_details)| { + pool_details + .bonded_currencies + .iter() + .map(|id| (*id, vec![], vec![], *denomination)) + .collect::, Vec, u8)>>() + }) + .flatten() + .collect(), + } + .assimilate_storage(&mut storage) + .expect("assimilate should not fail"); + + let mut ext = sp_io::TestExternalities::new(storage); + + ext.execute_with(|| { + System::set_block_number(System::block_number() + 1); + + self.pools.iter().for_each(|(_, pool_id, pool)| { + crate::Pools::::insert(pool_id.clone(), pool.clone()); + }); + }); + + ext + } + + #[cfg(feature = "runtime-benchmarks")] + pub(crate) fn build_with_keystore(self) -> sp_io::TestExternalities { + use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; + use sp_std::sync::Arc; + + let mut ext = self.build(); + + let keystore = MemoryKeystore::new(); + ext.register_extension(KeystoreExt(Arc::new(keystore))); + + ext + } + } +} From 53de697987dd7faad8c1dbbae25b52e6b9be55c7 Mon Sep 17 00:00:00 2001 From: Adel Golghalyani Date: Mon, 4 Nov 2024 14:03:44 +0100 Subject: [PATCH 02/11] remove some types --- pallets/pallet-bonded-coins/src/mock.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pallets/pallet-bonded-coins/src/mock.rs b/pallets/pallet-bonded-coins/src/mock.rs index a537b19988..cfa153b3e1 100644 --- a/pallets/pallet-bonded-coins/src/mock.rs +++ b/pallets/pallet-bonded-coins/src/mock.rs @@ -36,9 +36,6 @@ pub(crate) const DEFAULT_BONDED_CURRENCY_ID: AssetId = 0; pub(crate) const DEFAULT_COLLATERAL_CURRENCY_ID: AssetId = AssetId::MAX; pub(crate) const DEFAULT_COLLATERAL_DENOMINATION: u8 = 10; pub(crate) const DEFAULT_BONDED_DENOMINATION: u8 = 10; -pub(crate) const DEFAULT_COLLATERAL_UNIT: Balance = 10u128.pow(10); -pub(crate) const DEFAULT_BONDED_UNIT: Balance = 10u128.pow(10); -pub const UNIT_NATIVE: Balance = 10u128.pow(15); // helper functions pub fn assert_relative_eq(target: Float, expected: Float, epsilon: Float) { @@ -281,7 +278,7 @@ pub mod runtime { .assimilate_storage(&mut storage) .expect("assimilate should not fail"); - let collateral_assets = self.collaterals.iter().map(|id| (*id, ACCOUNT_99, false, 0)); + let collateral_assets = self.collaterals.into_iter().map(|id| (id, ACCOUNT_99, false, 0)); pallet_assets::GenesisConfig:: { assets: self From 249156d7a63319fb0d8ccfe5f78fbbd8a32ac4c6 Mon Sep 17 00:00:00 2001 From: Adel Golghalyani Date: Mon, 4 Nov 2024 15:35:32 +0100 Subject: [PATCH 03/11] update mocks --- pallets/pallet-bonded-coins/src/mock.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/pallets/pallet-bonded-coins/src/mock.rs b/pallets/pallet-bonded-coins/src/mock.rs index cfa153b3e1..6cc03123bd 100644 --- a/pallets/pallet-bonded-coins/src/mock.rs +++ b/pallets/pallet-bonded-coins/src/mock.rs @@ -12,10 +12,11 @@ use sp_runtime::{ use substrate_fixed::types::{I75F53, U75F53}; use crate::{ + self as pallet_bonded_coins, curves::{polynomial::PolynomialParameters, Curve}, traits::{FreezeAccounts, ResetTeam}, types::{Locks, PoolStatus}, - Config, DepositCurrencyBalanceOf, PoolDetailsOf, + DepositCurrencyBalanceOf, PoolDetailsOf, }; pub type Float = I75F53; @@ -223,7 +224,7 @@ pub mod runtime { pub const CollateralAssetId: u32 = u32::MAX; } - impl Config for Test { + impl pallet_bonded_coins::Config for Test { type AssetId = AssetId; type BaseDeposit = ExistentialDeposit; type CollateralCurrency = Assets; @@ -246,8 +247,8 @@ pub mod runtime { pub(crate) struct ExtBuilder { native_assets: Vec<(AccountId, DepositCurrencyBalanceOf)>, bonded_balance: Vec<(AssetId, AccountId, Balance)>, - // denomination, pool_id, PoolDetails - pools: Vec<(u8, AccountId, PoolDetailsOf)>, + // pool_id, PoolDetails + pools: Vec<(AccountId, PoolDetailsOf)>, collaterals: Vec, } @@ -260,7 +261,7 @@ pub mod runtime { self } - pub(crate) fn with_pools(mut self, pools: Vec<(u8, AccountId, PoolDetailsOf)>) -> Self { + pub(crate) fn with_pools(mut self, pools: Vec<(AccountId, PoolDetailsOf)>) -> Self { self.pools = pools; self } @@ -284,7 +285,7 @@ pub mod runtime { assets: self .pools .iter() - .map(|(_, owner, pool)| { + .map(|(owner, pool)| { pool.bonded_currencies .iter() .map(|id| (*id, owner.to_owned(), false, 1u128)) @@ -298,11 +299,11 @@ pub mod runtime { metadata: self .pools .iter() - .map(|(denomination, _, pool_details)| { + .map(|(_, pool_details)| { pool_details .bonded_currencies .iter() - .map(|id| (*id, vec![], vec![], *denomination)) + .map(|id| (*id, vec![], vec![], pool_details.denomination)) .collect::, Vec, u8)>>() }) .flatten() @@ -316,8 +317,8 @@ pub mod runtime { ext.execute_with(|| { System::set_block_number(System::block_number() + 1); - self.pools.iter().for_each(|(_, pool_id, pool)| { - crate::Pools::::insert(pool_id.clone(), pool.clone()); + self.pools.into_iter().for_each(|(pool_id, pool)| { + crate::Pools::::insert(pool_id, pool); }); }); From 1c1d5a5fb6f78e3039003e83da72643004692526 Mon Sep 17 00:00:00 2001 From: Raphael Date: Mon, 4 Nov 2024 16:25:10 +0100 Subject: [PATCH 04/11] test: fix and expand mocking --- pallets/pallet-bonded-coins/src/mock.rs | 29 ++++++++++++++++++------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/pallets/pallet-bonded-coins/src/mock.rs b/pallets/pallet-bonded-coins/src/mock.rs index 6cc03123bd..0cd8c82342 100644 --- a/pallets/pallet-bonded-coins/src/mock.rs +++ b/pallets/pallet-bonded-coins/src/mock.rs @@ -13,7 +13,10 @@ use substrate_fixed::types::{I75F53, U75F53}; use crate::{ self as pallet_bonded_coins, - curves::{polynomial::PolynomialParameters, Curve}, + curves::{ + polynomial::{PolynomialParameters, PolynomialParametersInput}, + Curve, CurveInput, + }, traits::{FreezeAccounts, ResetTeam}, types::{Locks, PoolStatus}, DepositCurrencyBalanceOf, PoolDetailsOf, @@ -55,6 +58,13 @@ pub(crate) fn get_linear_bonding_curve() -> Curve { Curve::Polynomial(PolynomialParameters { m, n, o }) } +pub(crate) fn get_linear_bonding_curve_input() -> CurveInput { + let m = FloatInput::from_num(0); + let n = FloatInput::from_num(2); + let o = FloatInput::from_num(3); + CurveInput::Polynomial(PolynomialParametersInput { m, n, o }) +} + pub(crate) fn calculate_pool_id(currencies: Vec) -> AccountId { AccountId::from(currencies.blake2_256()) } @@ -227,7 +237,7 @@ pub mod runtime { impl pallet_bonded_coins::Config for Test { type AssetId = AssetId; type BaseDeposit = ExistentialDeposit; - type CollateralCurrency = Assets; + type CollateralCurrencies = Assets; type CurveParameterInput = FloatInput; type CurveParameterType = Float; type DefaultOrigin = EnsureSigned; @@ -261,6 +271,11 @@ pub mod runtime { self } + pub(crate) fn with_collaterals(mut self, collaterals: Vec) -> Self { + self.collaterals = collaterals; + self + } + pub(crate) fn with_pools(mut self, pools: Vec<(AccountId, PoolDetailsOf)>) -> Self { self.pools = pools; self @@ -271,7 +286,7 @@ pub mod runtime { self } - pub(crate) fn build(mut self) -> sp_io::TestExternalities { + pub(crate) fn build(self) -> sp_io::TestExternalities { let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: self.native_assets.clone(), @@ -279,19 +294,18 @@ pub mod runtime { .assimilate_storage(&mut storage) .expect("assimilate should not fail"); - let collateral_assets = self.collaterals.into_iter().map(|id| (id, ACCOUNT_99, false, 0)); + let collateral_assets = self.collaterals.into_iter().map(|id| (id, ACCOUNT_99, false, 1)); pallet_assets::GenesisConfig:: { assets: self .pools .iter() - .map(|(owner, pool)| { + .flat_map(|(owner, pool)| { pool.bonded_currencies .iter() .map(|id| (*id, owner.to_owned(), false, 1u128)) .collect::>() }) - .flatten() .chain(collateral_assets) .collect(), @@ -299,14 +313,13 @@ pub mod runtime { metadata: self .pools .iter() - .map(|(_, pool_details)| { + .flat_map(|(_, pool_details)| { pool_details .bonded_currencies .iter() .map(|id| (*id, vec![], vec![], pool_details.denomination)) .collect::, Vec, u8)>>() }) - .flatten() .collect(), } .assimilate_storage(&mut storage) From 1bb6a5021b09ad19d8f5fef7694b7df8f5436f71 Mon Sep 17 00:00:00 2001 From: Adel Golghalyani Date: Tue, 5 Nov 2024 10:20:39 +0100 Subject: [PATCH 05/11] trait implementations --- pallets/pallet-bonded-coins/Cargo.toml | 3 +- pallets/pallet-bonded-coins/src/lib.rs | 2 +- pallets/pallet-bonded-coins/src/mock.rs | 26 +----------- pallets/pallet-bonded-coins/src/traits.rs | 50 ++++++++++++++++++++++- 4 files changed, 52 insertions(+), 29 deletions(-) diff --git a/pallets/pallet-bonded-coins/Cargo.toml b/pallets/pallet-bonded-coins/Cargo.toml index ca7aa6e714..b70dc775d0 100644 --- a/pallets/pallet-bonded-coins/Cargo.toml +++ b/pallets/pallet-bonded-coins/Cargo.toml @@ -20,6 +20,7 @@ scale-info = { workspace = true, features = ["derive"] } frame-benchmarking = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } +pallet-assets = { workspace = true } sp-arithmetic = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } @@ -30,7 +31,6 @@ log = { workspace = true } substrate-fixed = { workspace = true } [dev-dependencies] -pallet-assets = { workspace = true, features = ["std"] } pallet-balances = { workspace = true, features = ["std"] } serde = { workspace = true } sp-keystore = { workspace = true, features = ["std"] } @@ -50,6 +50,7 @@ std = [ "frame-benchmarking/std", "frame-support/std", "frame-system/std", + "pallet-assets/std", "parity-scale-codec/std", "scale-info/std", "substrate-fixed/std", diff --git a/pallets/pallet-bonded-coins/src/lib.rs b/pallets/pallet-bonded-coins/src/lib.rs index 9cf192f758..3a4fb657f5 100644 --- a/pallets/pallet-bonded-coins/src/lib.rs +++ b/pallets/pallet-bonded-coins/src/lib.rs @@ -60,7 +60,7 @@ pub mod pallet { type AccountIdLookupOf = <::Lookup as sp_runtime::traits::StaticLookup>::Source; - type AccountIdOf = ::AccountId; + pub(crate) type AccountIdOf = ::AccountId; pub(crate) type DepositCurrencyBalanceOf = <::DepositCurrency as InspectFungible<::AccountId>>::Balance; diff --git a/pallets/pallet-bonded-coins/src/mock.rs b/pallets/pallet-bonded-coins/src/mock.rs index 6cc03123bd..15ce4a9c9a 100644 --- a/pallets/pallet-bonded-coins/src/mock.rs +++ b/pallets/pallet-bonded-coins/src/mock.rs @@ -106,30 +106,6 @@ pub mod runtime { .collect::>() } - // trait implementations - impl ResetTeam for Assets { - fn reset_team( - _id: Self::AssetId, - _owner: AccountId, - _admin: AccountId, - _issuer: AccountId, - _freezer: AccountId, - ) -> frame_support::dispatch::DispatchResult { - Ok(()) - } - } - - impl FreezeAccounts for Assets { - type Error = DispatchError; - fn freeze(_asset_id: &AssetId, _who: &AccountId) -> Result<(), Self::Error> { - Ok(()) - } - - fn thaw(_asset_id: &AssetId, _who: &AccountId) -> Result<(), Self::Error> { - Ok(()) - } - } - frame_support::construct_runtime!( pub enum Test { @@ -227,7 +203,7 @@ pub mod runtime { impl pallet_bonded_coins::Config for Test { type AssetId = AssetId; type BaseDeposit = ExistentialDeposit; - type CollateralCurrency = Assets; + type CollateralCurrencies = Assets; type CurveParameterInput = FloatInput; type CurveParameterType = Float; type DefaultOrigin = EnsureSigned; diff --git a/pallets/pallet-bonded-coins/src/traits.rs b/pallets/pallet-bonded-coins/src/traits.rs index 48ede8cda7..554935208a 100644 --- a/pallets/pallet-bonded-coins/src/traits.rs +++ b/pallets/pallet-bonded-coins/src/traits.rs @@ -1,5 +1,9 @@ -use frame_support::{dispatch::DispatchResult, traits::fungibles::Inspect}; -use sp_runtime::DispatchError; +use frame_support::{dispatch::DispatchResult, traits::fungibles::roles::Inspect}; +use frame_system::RawOrigin; +use pallet_assets::{Config as AssetConfig, Pallet as AssetsPallet}; +use sp_runtime::{traits::StaticLookup, DispatchError}; + +use crate::AccountIdOf; pub trait FreezeAccounts { type Error: Into; @@ -9,6 +13,31 @@ pub trait FreezeAccounts { fn thaw(asset_id: &AssetId, who: &AccountId) -> Result<(), Self::Error>; } +type AssetIdOf = ::AssetId; + +impl FreezeAccounts, ::AssetId> for AssetsPallet +where + T: AssetConfig, + AccountIdOf: Clone, + <::Lookup as StaticLookup>::Source: From>, +{ + type Error = DispatchError; + + fn freeze(asset_id: &AssetIdOf, who: &AccountIdOf) -> Result<(), Self::Error> { + let asset_id: ::AssetId = asset_id.to_owned().into(); + let freezer = AssetsPallet::::freezer(asset_id.clone()).ok_or(Self::Error::Unavailable)?; + let origin = RawOrigin::Signed(freezer); + AssetsPallet::::freeze(origin.into(), asset_id.into(), who.to_owned().into()) + } + + fn thaw(asset_id: &AssetIdOf, who: &AccountIdOf) -> Result<(), Self::Error> { + let asset_id: ::AssetId = asset_id.to_owned().into(); + let admin = AssetsPallet::::admin(asset_id.clone()).ok_or(Self::Error::Unavailable)?; + let origin = RawOrigin::Signed(admin); + AssetsPallet::::thaw(origin.into(), asset_id.into(), who.to_owned().into()) + } +} + /// Copy from the Polkadot SDK. once we are at version 1.13.0, we can remove this. pub trait ResetTeam: Inspect { /// Reset the team for the asset with the given `id`. @@ -27,3 +56,20 @@ pub trait ResetTeam: Inspect { freezer: AccountId, ) -> DispatchResult; } + +impl ResetTeam> for AssetsPallet +where + T: AssetConfig, + <::Lookup as StaticLookup>::Source: From>, +{ + fn reset_team( + id: Self::AssetId, + owner: AccountIdOf, + admin: AccountIdOf, + issuer: AccountIdOf, + freezer: AccountIdOf, + ) -> DispatchResult { + let origin = RawOrigin::Signed(owner); + AssetsPallet::::set_team(origin.into(), id.into(), issuer.into(), admin.into(), freezer.into()) + } +} From ffdd9f3d8185035398e84f0e08f9b24f12f96ed4 Mon Sep 17 00:00:00 2001 From: Adel Golghalyani Date: Tue, 5 Nov 2024 10:23:57 +0100 Subject: [PATCH 06/11] clippy --- pallets/pallet-bonded-coins/src/mock.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pallets/pallet-bonded-coins/src/mock.rs b/pallets/pallet-bonded-coins/src/mock.rs index 15ce4a9c9a..4561d0bf7a 100644 --- a/pallets/pallet-bonded-coins/src/mock.rs +++ b/pallets/pallet-bonded-coins/src/mock.rs @@ -7,14 +7,13 @@ use frame_support::{ use frame_system::{EnsureRoot, EnsureSigned}; use sp_runtime::{ traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, - BoundedVec, BuildStorage, DispatchError, MultiSignature, + BoundedVec, BuildStorage, MultiSignature, }; use substrate_fixed::types::{I75F53, U75F53}; use crate::{ self as pallet_bonded_coins, curves::{polynomial::PolynomialParameters, Curve}, - traits::{FreezeAccounts, ResetTeam}, types::{Locks, PoolStatus}, DepositCurrencyBalanceOf, PoolDetailsOf, }; @@ -55,8 +54,8 @@ pub(crate) fn get_linear_bonding_curve() -> Curve { Curve::Polynomial(PolynomialParameters { m, n, o }) } -pub(crate) fn calculate_pool_id(currencies: Vec) -> AccountId { - AccountId::from(currencies.blake2_256()) +pub(crate) fn calculate_pool_id(currencies: &[AssetId]) -> AccountId { + AccountId::from(currencies.to_vec().blake2_256()) } #[cfg(test)] From 575271a11853f955abae7fa29517d1be4022b437 Mon Sep 17 00:00:00 2001 From: Adel Golghalyani Date: Tue, 5 Nov 2024 10:30:13 +0100 Subject: [PATCH 07/11] bool --- pallets/pallet-bonded-coins/src/mock.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pallets/pallet-bonded-coins/src/mock.rs b/pallets/pallet-bonded-coins/src/mock.rs index 0ebe9bf208..da16f4179a 100644 --- a/pallets/pallet-bonded-coins/src/mock.rs +++ b/pallets/pallet-bonded-coins/src/mock.rs @@ -78,14 +78,13 @@ pub mod runtime { pub fn generate_pool_details( currencies: Vec, curve: Curve, - transferable: Option, + transferable: bool, state: Option>, manager: Option, collateral_id: Option, owner: Option, ) -> PoolDetailsOf { let bonded_currencies = BoundedVec::truncate_from(currencies); - let transferable = transferable.unwrap_or(false); let state = state.unwrap_or(PoolStatus::Active); let owner = owner.unwrap_or(ACCOUNT_99); let collateral_id = collateral_id.unwrap_or(DEFAULT_COLLATERAL_CURRENCY_ID); From cb1bdd59504be003f6f6c19e3472a6337dd5af7e Mon Sep 17 00:00:00 2001 From: Adel Golghalyani Date: Tue, 5 Nov 2024 10:39:09 +0100 Subject: [PATCH 08/11] remove runtime mod --- pallets/pallet-bonded-coins/src/mock.rs | 449 ++++++++++++------------ 1 file changed, 221 insertions(+), 228 deletions(-) diff --git a/pallets/pallet-bonded-coins/src/mock.rs b/pallets/pallet-bonded-coins/src/mock.rs index da16f4179a..6e06324d7c 100644 --- a/pallets/pallet-bonded-coins/src/mock.rs +++ b/pallets/pallet-bonded-coins/src/mock.rs @@ -29,6 +29,7 @@ pub type AssetId = u32; pub type Signature = MultiSignature; pub type AccountPublic = ::Signer; pub type AccountId = ::AccountId; +pub type Block = frame_system::mocking::MockBlock; // accounts pub(crate) const ACCOUNT_00: AccountId = AccountId::new([0u8; 32]); @@ -68,261 +69,253 @@ pub(crate) fn calculate_pool_id(currencies: &[AssetId]) -> AccountId { AccountId::from(currencies.to_vec().blake2_256()) } -#[cfg(test)] -pub mod runtime { - - use super::*; - - pub type Block = frame_system::mocking::MockBlock; - - pub fn generate_pool_details( - currencies: Vec, - curve: Curve, - transferable: bool, - state: Option>, - manager: Option, - collateral_id: Option, - owner: Option, - ) -> PoolDetailsOf { - let bonded_currencies = BoundedVec::truncate_from(currencies); - let state = state.unwrap_or(PoolStatus::Active); - let owner = owner.unwrap_or(ACCOUNT_99); - let collateral_id = collateral_id.unwrap_or(DEFAULT_COLLATERAL_CURRENCY_ID); - PoolDetailsOf:: { - curve, - manager, - transferable, - bonded_currencies, - state, - collateral_id, - denomination: 10, - owner, - } +pub fn generate_pool_details( + currencies: Vec, + curve: Curve, + transferable: bool, + state: Option>, + manager: Option, + collateral_id: Option, + owner: Option, +) -> PoolDetailsOf { + let bonded_currencies = BoundedVec::truncate_from(currencies); + let state = state.unwrap_or(PoolStatus::Active); + let owner = owner.unwrap_or(ACCOUNT_99); + let collateral_id = collateral_id.unwrap_or(DEFAULT_COLLATERAL_CURRENCY_ID); + PoolDetailsOf:: { + curve, + manager, + transferable, + bonded_currencies, + state, + collateral_id, + denomination: 10, + owner, } +} + +pub(crate) fn events() -> Vec> { + System::events() + .into_iter() + .map(|r| r.event) + .filter_map(|e| { + if let RuntimeEvent::BondingPallet(e) = e { + Some(e) + } else { + None + } + }) + .collect::>() +} - pub(crate) fn events() -> Vec> { - System::events() - .into_iter() - .map(|r| r.event) - .filter_map(|e| { - if let RuntimeEvent::BondingPallet(e) = e { - Some(e) - } else { - None - } - }) - .collect::>() +frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Balances: pallet_balances, + Assets: pallet_assets, + BondingPallet: crate, } +); - frame_support::construct_runtime!( - pub enum Test - { - System: frame_system, - Balances: pallet_balances, - Assets: pallet_assets, - BondingPallet: crate, - } - ); +parameter_types! { + pub const SS58Prefix: u8 = 38; + pub const BlockHashCount: u64 = 250; +} - parameter_types! { - pub const SS58Prefix: u8 = 38; - pub const BlockHashCount: u64 = 250; - } +impl frame_system::Config for Test { + type AccountData = pallet_balances::AccountData; + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = BlockHashCount; + type BlockLength = (); + type BlockWeights = (); + type DbWeight = RocksDbWeight; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Lookup = IdentityLookup; + type MaxConsumers = ConstU32<16>; + type Nonce = u64; + type OnKilledAccount = (); + type OnNewAccount = (); + type OnSetCode = (); + type PalletInfo = PalletInfo; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeTask = (); + type SS58Prefix = SS58Prefix; + type SystemWeightInfo = (); + type Version = (); +} - impl frame_system::Config for Test { - type AccountData = pallet_balances::AccountData; - type AccountId = AccountId; - type BaseCallFilter = frame_support::traits::Everything; - type Block = Block; - type BlockHashCount = BlockHashCount; - type BlockLength = (); - type BlockWeights = (); - type DbWeight = RocksDbWeight; - type Hash = Hash; - type Hashing = BlakeTwo256; - type Lookup = IdentityLookup; - type MaxConsumers = ConstU32<16>; - type Nonce = u64; - type OnKilledAccount = (); - type OnNewAccount = (); - type OnSetCode = (); - type PalletInfo = PalletInfo; - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeTask = (); - type SS58Prefix = SS58Prefix; - type SystemWeightInfo = (); - type Version = (); - } +parameter_types! { + pub const ExistentialDeposit: Balance = 500; + pub const MaxLocks: u32 = 50; + pub const MaxReserves: u32 = 50; +} - parameter_types! { - pub const ExistentialDeposit: Balance = 500; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; - } +impl pallet_balances::Config for Test { + type AccountStore = System; + type Balance = Balance; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type FreezeIdentifier = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type RuntimeEvent = RuntimeEvent; + type RuntimeFreezeReason = (); + type RuntimeHoldReason = RuntimeHoldReason; + type WeightInfo = (); +} - impl pallet_balances::Config for Test { - type AccountStore = System; - type Balance = Balance; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type FreezeIdentifier = (); - type MaxFreezes = (); - type MaxLocks = MaxLocks; - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeEvent = RuntimeEvent; - type RuntimeFreezeReason = (); - type RuntimeHoldReason = RuntimeHoldReason; - type WeightInfo = (); - } +parameter_types! { + pub const StringLimit: u32 = 50; - parameter_types! { - pub const StringLimit: u32 = 50; +} +impl pallet_assets::Config for Test { + type ApprovalDeposit = ConstU128<0>; + type AssetAccountDeposit = ConstU128<0>; + type AssetDeposit = ConstU128<0>; + type AssetId = AssetId; + type AssetIdParameter = AssetId; + type Balance = Balance; + type CallbackHandle = (); + type CreateOrigin = EnsureSigned; + type Currency = Balances; + type Extra = (); + type ForceOrigin = EnsureRoot; + type Freezer = (); + type MetadataDepositBase = ConstU128<0>; + type MetadataDepositPerByte = ConstU128<0>; + type RemoveItemsLimit = ConstU32<5>; + type RuntimeEvent = RuntimeEvent; + type StringLimit = StringLimit; + type WeightInfo = (); +} +parameter_types! { + pub const CurrencyDeposit: Balance = 500; + pub const MaxCurrencies: u32 = 50; + pub const CollateralAssetId: u32 = u32::MAX; +} - } - impl pallet_assets::Config for Test { - type ApprovalDeposit = ConstU128<0>; - type AssetAccountDeposit = ConstU128<0>; - type AssetDeposit = ConstU128<0>; - type AssetId = AssetId; - type AssetIdParameter = AssetId; - type Balance = Balance; - type CallbackHandle = (); - type CreateOrigin = EnsureSigned; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type MetadataDepositBase = ConstU128<0>; - type MetadataDepositPerByte = ConstU128<0>; - type RemoveItemsLimit = ConstU32<5>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = StringLimit; - type WeightInfo = (); - } - parameter_types! { - pub const CurrencyDeposit: Balance = 500; - pub const MaxCurrencies: u32 = 50; - pub const CollateralAssetId: u32 = u32::MAX; - } +impl pallet_bonded_coins::Config for Test { + type AssetId = AssetId; + type BaseDeposit = ExistentialDeposit; + type CollateralCurrencies = Assets; + type CurveParameterInput = FloatInput; + type CurveParameterType = Float; + type DefaultOrigin = EnsureSigned; + type DepositCurrency = Balances; + type DepositPerCurrency = CurrencyDeposit; + type ForceOrigin = EnsureRoot; + type Fungibles = Assets; + type MaxCurrencies = MaxCurrencies; + type MaxStringLength = StringLimit; + type PoolCreateOrigin = EnsureSigned; + type PoolId = AccountId; + type RuntimeEvent = RuntimeEvent; + type RuntimeHoldReason = RuntimeHoldReason; +} - impl pallet_bonded_coins::Config for Test { - type AssetId = AssetId; - type BaseDeposit = ExistentialDeposit; - type CollateralCurrencies = Assets; - type CurveParameterInput = FloatInput; - type CurveParameterType = Float; - type DefaultOrigin = EnsureSigned; - type DepositCurrency = Balances; - type DepositPerCurrency = CurrencyDeposit; - type ForceOrigin = EnsureRoot; - type Fungibles = Assets; - type MaxCurrencies = MaxCurrencies; - type MaxStringLength = StringLimit; - type PoolCreateOrigin = EnsureSigned; - type PoolId = AccountId; - type RuntimeEvent = RuntimeEvent; - type RuntimeHoldReason = RuntimeHoldReason; - } +#[derive(Clone, Default)] +pub(crate) struct ExtBuilder { + native_assets: Vec<(AccountId, DepositCurrencyBalanceOf)>, + bonded_balance: Vec<(AssetId, AccountId, Balance)>, + // pool_id, PoolDetails + pools: Vec<(AccountId, PoolDetailsOf)>, + collaterals: Vec, +} - #[derive(Clone, Default)] - pub(crate) struct ExtBuilder { +impl ExtBuilder { + pub(crate) fn with_native_balances( + mut self, native_assets: Vec<(AccountId, DepositCurrencyBalanceOf)>, - bonded_balance: Vec<(AssetId, AccountId, Balance)>, - // pool_id, PoolDetails - pools: Vec<(AccountId, PoolDetailsOf)>, - collaterals: Vec, + ) -> Self { + self.native_assets = native_assets; + self } - impl ExtBuilder { - pub(crate) fn with_native_balances( - mut self, - native_assets: Vec<(AccountId, DepositCurrencyBalanceOf)>, - ) -> Self { - self.native_assets = native_assets; - self - } + pub(crate) fn with_collaterals(mut self, collaterals: Vec) -> Self { + self.collaterals = collaterals; + self + } - pub(crate) fn with_collaterals(mut self, collaterals: Vec) -> Self { - self.collaterals = collaterals; - self - } + pub(crate) fn with_pools(mut self, pools: Vec<(AccountId, PoolDetailsOf)>) -> Self { + self.pools = pools; + self + } - pub(crate) fn with_pools(mut self, pools: Vec<(AccountId, PoolDetailsOf)>) -> Self { - self.pools = pools; - self - } + pub(crate) fn with_bonded_balance(mut self, bonded_balance: Vec<(AssetId, AccountId, Balance)>) -> Self { + self.bonded_balance = bonded_balance; + self + } - pub(crate) fn with_bonded_balance(mut self, bonded_balance: Vec<(AssetId, AccountId, Balance)>) -> Self { - self.bonded_balance = bonded_balance; - self + pub(crate) fn build(self) -> sp_io::TestExternalities { + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); + pallet_balances::GenesisConfig:: { + balances: self.native_assets.clone(), } + .assimilate_storage(&mut storage) + .expect("assimilate should not fail"); + + let collateral_assets = self.collaterals.into_iter().map(|id| (id, ACCOUNT_99, false, 1)); + + pallet_assets::GenesisConfig:: { + assets: self + .pools + .iter() + .flat_map(|(owner, pool)| { + pool.bonded_currencies + .iter() + .map(|id| (*id, owner.to_owned(), false, 1u128)) + .collect::>() + }) + .chain(collateral_assets) + .collect(), + + accounts: self.bonded_balance, + metadata: self + .pools + .iter() + .flat_map(|(_, pool_details)| { + pool_details + .bonded_currencies + .iter() + .map(|id| (*id, vec![], vec![], pool_details.denomination)) + .collect::, Vec, u8)>>() + }) + .collect(), + } + .assimilate_storage(&mut storage) + .expect("assimilate should not fail"); - pub(crate) fn build(self) -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); - pallet_balances::GenesisConfig:: { - balances: self.native_assets.clone(), - } - .assimilate_storage(&mut storage) - .expect("assimilate should not fail"); - - let collateral_assets = self.collaterals.into_iter().map(|id| (id, ACCOUNT_99, false, 1)); - - pallet_assets::GenesisConfig:: { - assets: self - .pools - .iter() - .flat_map(|(owner, pool)| { - pool.bonded_currencies - .iter() - .map(|id| (*id, owner.to_owned(), false, 1u128)) - .collect::>() - }) - .chain(collateral_assets) - .collect(), - - accounts: self.bonded_balance, - metadata: self - .pools - .iter() - .flat_map(|(_, pool_details)| { - pool_details - .bonded_currencies - .iter() - .map(|id| (*id, vec![], vec![], pool_details.denomination)) - .collect::, Vec, u8)>>() - }) - .collect(), - } - .assimilate_storage(&mut storage) - .expect("assimilate should not fail"); - - let mut ext = sp_io::TestExternalities::new(storage); + let mut ext = sp_io::TestExternalities::new(storage); - ext.execute_with(|| { - System::set_block_number(System::block_number() + 1); + ext.execute_with(|| { + System::set_block_number(System::block_number() + 1); - self.pools.into_iter().for_each(|(pool_id, pool)| { - crate::Pools::::insert(pool_id, pool); - }); + self.pools.into_iter().for_each(|(pool_id, pool)| { + crate::Pools::::insert(pool_id, pool); }); + }); - ext - } + ext + } - #[cfg(feature = "runtime-benchmarks")] - pub(crate) fn build_with_keystore(self) -> sp_io::TestExternalities { - use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; - use sp_std::sync::Arc; + #[cfg(feature = "runtime-benchmarks")] + pub(crate) fn build_with_keystore(self) -> sp_io::TestExternalities { + use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; + use sp_std::sync::Arc; - let mut ext = self.build(); + let mut ext = self.build(); - let keystore = MemoryKeystore::new(); - ext.register_extension(KeystoreExt(Arc::new(keystore))); + let keystore = MemoryKeystore::new(); + ext.register_extension(KeystoreExt(Arc::new(keystore))); - ext - } + ext } } From e32acc273b772f990ab519d59c2c518ec63ea465 Mon Sep 17 00:00:00 2001 From: Adel Golghalyani Date: Tue, 5 Nov 2024 16:44:23 +0100 Subject: [PATCH 09/11] Revert "remove runtime mod" This reverts commit cb1bdd59504be003f6f6c19e3472a6337dd5af7e. --- pallets/pallet-bonded-coins/src/mock.rs | 449 ++++++++++++------------ 1 file changed, 228 insertions(+), 221 deletions(-) diff --git a/pallets/pallet-bonded-coins/src/mock.rs b/pallets/pallet-bonded-coins/src/mock.rs index 6e06324d7c..da16f4179a 100644 --- a/pallets/pallet-bonded-coins/src/mock.rs +++ b/pallets/pallet-bonded-coins/src/mock.rs @@ -29,7 +29,6 @@ pub type AssetId = u32; pub type Signature = MultiSignature; pub type AccountPublic = ::Signer; pub type AccountId = ::AccountId; -pub type Block = frame_system::mocking::MockBlock; // accounts pub(crate) const ACCOUNT_00: AccountId = AccountId::new([0u8; 32]); @@ -69,253 +68,261 @@ pub(crate) fn calculate_pool_id(currencies: &[AssetId]) -> AccountId { AccountId::from(currencies.to_vec().blake2_256()) } -pub fn generate_pool_details( - currencies: Vec, - curve: Curve, - transferable: bool, - state: Option>, - manager: Option, - collateral_id: Option, - owner: Option, -) -> PoolDetailsOf { - let bonded_currencies = BoundedVec::truncate_from(currencies); - let state = state.unwrap_or(PoolStatus::Active); - let owner = owner.unwrap_or(ACCOUNT_99); - let collateral_id = collateral_id.unwrap_or(DEFAULT_COLLATERAL_CURRENCY_ID); - PoolDetailsOf:: { - curve, - manager, - transferable, - bonded_currencies, - state, - collateral_id, - denomination: 10, - owner, +#[cfg(test)] +pub mod runtime { + + use super::*; + + pub type Block = frame_system::mocking::MockBlock; + + pub fn generate_pool_details( + currencies: Vec, + curve: Curve, + transferable: bool, + state: Option>, + manager: Option, + collateral_id: Option, + owner: Option, + ) -> PoolDetailsOf { + let bonded_currencies = BoundedVec::truncate_from(currencies); + let state = state.unwrap_or(PoolStatus::Active); + let owner = owner.unwrap_or(ACCOUNT_99); + let collateral_id = collateral_id.unwrap_or(DEFAULT_COLLATERAL_CURRENCY_ID); + PoolDetailsOf:: { + curve, + manager, + transferable, + bonded_currencies, + state, + collateral_id, + denomination: 10, + owner, + } } -} - -pub(crate) fn events() -> Vec> { - System::events() - .into_iter() - .map(|r| r.event) - .filter_map(|e| { - if let RuntimeEvent::BondingPallet(e) = e { - Some(e) - } else { - None - } - }) - .collect::>() -} -frame_support::construct_runtime!( - pub enum Test - { - System: frame_system, - Balances: pallet_balances, - Assets: pallet_assets, - BondingPallet: crate, + pub(crate) fn events() -> Vec> { + System::events() + .into_iter() + .map(|r| r.event) + .filter_map(|e| { + if let RuntimeEvent::BondingPallet(e) = e { + Some(e) + } else { + None + } + }) + .collect::>() } -); -parameter_types! { - pub const SS58Prefix: u8 = 38; - pub const BlockHashCount: u64 = 250; -} - -impl frame_system::Config for Test { - type AccountData = pallet_balances::AccountData; - type AccountId = AccountId; - type BaseCallFilter = frame_support::traits::Everything; - type Block = Block; - type BlockHashCount = BlockHashCount; - type BlockLength = (); - type BlockWeights = (); - type DbWeight = RocksDbWeight; - type Hash = Hash; - type Hashing = BlakeTwo256; - type Lookup = IdentityLookup; - type MaxConsumers = ConstU32<16>; - type Nonce = u64; - type OnKilledAccount = (); - type OnNewAccount = (); - type OnSetCode = (); - type PalletInfo = PalletInfo; - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeTask = (); - type SS58Prefix = SS58Prefix; - type SystemWeightInfo = (); - type Version = (); -} - -parameter_types! { - pub const ExistentialDeposit: Balance = 500; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; -} + frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Balances: pallet_balances, + Assets: pallet_assets, + BondingPallet: crate, + } + ); -impl pallet_balances::Config for Test { - type AccountStore = System; - type Balance = Balance; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type FreezeIdentifier = (); - type MaxFreezes = (); - type MaxLocks = MaxLocks; - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeEvent = RuntimeEvent; - type RuntimeFreezeReason = (); - type RuntimeHoldReason = RuntimeHoldReason; - type WeightInfo = (); -} + parameter_types! { + pub const SS58Prefix: u8 = 38; + pub const BlockHashCount: u64 = 250; + } -parameter_types! { - pub const StringLimit: u32 = 50; + impl frame_system::Config for Test { + type AccountData = pallet_balances::AccountData; + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type Block = Block; + type BlockHashCount = BlockHashCount; + type BlockLength = (); + type BlockWeights = (); + type DbWeight = RocksDbWeight; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Lookup = IdentityLookup; + type MaxConsumers = ConstU32<16>; + type Nonce = u64; + type OnKilledAccount = (); + type OnNewAccount = (); + type OnSetCode = (); + type PalletInfo = PalletInfo; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeTask = (); + type SS58Prefix = SS58Prefix; + type SystemWeightInfo = (); + type Version = (); + } -} -impl pallet_assets::Config for Test { - type ApprovalDeposit = ConstU128<0>; - type AssetAccountDeposit = ConstU128<0>; - type AssetDeposit = ConstU128<0>; - type AssetId = AssetId; - type AssetIdParameter = AssetId; - type Balance = Balance; - type CallbackHandle = (); - type CreateOrigin = EnsureSigned; - type Currency = Balances; - type Extra = (); - type ForceOrigin = EnsureRoot; - type Freezer = (); - type MetadataDepositBase = ConstU128<0>; - type MetadataDepositPerByte = ConstU128<0>; - type RemoveItemsLimit = ConstU32<5>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = StringLimit; - type WeightInfo = (); -} -parameter_types! { - pub const CurrencyDeposit: Balance = 500; - pub const MaxCurrencies: u32 = 50; - pub const CollateralAssetId: u32 = u32::MAX; -} + parameter_types! { + pub const ExistentialDeposit: Balance = 500; + pub const MaxLocks: u32 = 50; + pub const MaxReserves: u32 = 50; + } -impl pallet_bonded_coins::Config for Test { - type AssetId = AssetId; - type BaseDeposit = ExistentialDeposit; - type CollateralCurrencies = Assets; - type CurveParameterInput = FloatInput; - type CurveParameterType = Float; - type DefaultOrigin = EnsureSigned; - type DepositCurrency = Balances; - type DepositPerCurrency = CurrencyDeposit; - type ForceOrigin = EnsureRoot; - type Fungibles = Assets; - type MaxCurrencies = MaxCurrencies; - type MaxStringLength = StringLimit; - type PoolCreateOrigin = EnsureSigned; - type PoolId = AccountId; - type RuntimeEvent = RuntimeEvent; - type RuntimeHoldReason = RuntimeHoldReason; -} + impl pallet_balances::Config for Test { + type AccountStore = System; + type Balance = Balance; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type FreezeIdentifier = (); + type MaxFreezes = (); + type MaxLocks = MaxLocks; + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type RuntimeEvent = RuntimeEvent; + type RuntimeFreezeReason = (); + type RuntimeHoldReason = RuntimeHoldReason; + type WeightInfo = (); + } -#[derive(Clone, Default)] -pub(crate) struct ExtBuilder { - native_assets: Vec<(AccountId, DepositCurrencyBalanceOf)>, - bonded_balance: Vec<(AssetId, AccountId, Balance)>, - // pool_id, PoolDetails - pools: Vec<(AccountId, PoolDetailsOf)>, - collaterals: Vec, -} + parameter_types! { + pub const StringLimit: u32 = 50; -impl ExtBuilder { - pub(crate) fn with_native_balances( - mut self, - native_assets: Vec<(AccountId, DepositCurrencyBalanceOf)>, - ) -> Self { - self.native_assets = native_assets; - self } - - pub(crate) fn with_collaterals(mut self, collaterals: Vec) -> Self { - self.collaterals = collaterals; - self + impl pallet_assets::Config for Test { + type ApprovalDeposit = ConstU128<0>; + type AssetAccountDeposit = ConstU128<0>; + type AssetDeposit = ConstU128<0>; + type AssetId = AssetId; + type AssetIdParameter = AssetId; + type Balance = Balance; + type CallbackHandle = (); + type CreateOrigin = EnsureSigned; + type Currency = Balances; + type Extra = (); + type ForceOrigin = EnsureRoot; + type Freezer = (); + type MetadataDepositBase = ConstU128<0>; + type MetadataDepositPerByte = ConstU128<0>; + type RemoveItemsLimit = ConstU32<5>; + type RuntimeEvent = RuntimeEvent; + type StringLimit = StringLimit; + type WeightInfo = (); + } + parameter_types! { + pub const CurrencyDeposit: Balance = 500; + pub const MaxCurrencies: u32 = 50; + pub const CollateralAssetId: u32 = u32::MAX; } - pub(crate) fn with_pools(mut self, pools: Vec<(AccountId, PoolDetailsOf)>) -> Self { - self.pools = pools; - self + impl pallet_bonded_coins::Config for Test { + type AssetId = AssetId; + type BaseDeposit = ExistentialDeposit; + type CollateralCurrencies = Assets; + type CurveParameterInput = FloatInput; + type CurveParameterType = Float; + type DefaultOrigin = EnsureSigned; + type DepositCurrency = Balances; + type DepositPerCurrency = CurrencyDeposit; + type ForceOrigin = EnsureRoot; + type Fungibles = Assets; + type MaxCurrencies = MaxCurrencies; + type MaxStringLength = StringLimit; + type PoolCreateOrigin = EnsureSigned; + type PoolId = AccountId; + type RuntimeEvent = RuntimeEvent; + type RuntimeHoldReason = RuntimeHoldReason; } - pub(crate) fn with_bonded_balance(mut self, bonded_balance: Vec<(AssetId, AccountId, Balance)>) -> Self { - self.bonded_balance = bonded_balance; - self + #[derive(Clone, Default)] + pub(crate) struct ExtBuilder { + native_assets: Vec<(AccountId, DepositCurrencyBalanceOf)>, + bonded_balance: Vec<(AssetId, AccountId, Balance)>, + // pool_id, PoolDetails + pools: Vec<(AccountId, PoolDetailsOf)>, + collaterals: Vec, } - pub(crate) fn build(self) -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); - pallet_balances::GenesisConfig:: { - balances: self.native_assets.clone(), + impl ExtBuilder { + pub(crate) fn with_native_balances( + mut self, + native_assets: Vec<(AccountId, DepositCurrencyBalanceOf)>, + ) -> Self { + self.native_assets = native_assets; + self + } + + pub(crate) fn with_collaterals(mut self, collaterals: Vec) -> Self { + self.collaterals = collaterals; + self } - .assimilate_storage(&mut storage) - .expect("assimilate should not fail"); - - let collateral_assets = self.collaterals.into_iter().map(|id| (id, ACCOUNT_99, false, 1)); - - pallet_assets::GenesisConfig:: { - assets: self - .pools - .iter() - .flat_map(|(owner, pool)| { - pool.bonded_currencies - .iter() - .map(|id| (*id, owner.to_owned(), false, 1u128)) - .collect::>() - }) - .chain(collateral_assets) - .collect(), - - accounts: self.bonded_balance, - metadata: self - .pools - .iter() - .flat_map(|(_, pool_details)| { - pool_details - .bonded_currencies - .iter() - .map(|id| (*id, vec![], vec![], pool_details.denomination)) - .collect::, Vec, u8)>>() - }) - .collect(), + + pub(crate) fn with_pools(mut self, pools: Vec<(AccountId, PoolDetailsOf)>) -> Self { + self.pools = pools; + self + } + + pub(crate) fn with_bonded_balance(mut self, bonded_balance: Vec<(AssetId, AccountId, Balance)>) -> Self { + self.bonded_balance = bonded_balance; + self } - .assimilate_storage(&mut storage) - .expect("assimilate should not fail"); - let mut ext = sp_io::TestExternalities::new(storage); + pub(crate) fn build(self) -> sp_io::TestExternalities { + let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); + pallet_balances::GenesisConfig:: { + balances: self.native_assets.clone(), + } + .assimilate_storage(&mut storage) + .expect("assimilate should not fail"); + + let collateral_assets = self.collaterals.into_iter().map(|id| (id, ACCOUNT_99, false, 1)); + + pallet_assets::GenesisConfig:: { + assets: self + .pools + .iter() + .flat_map(|(owner, pool)| { + pool.bonded_currencies + .iter() + .map(|id| (*id, owner.to_owned(), false, 1u128)) + .collect::>() + }) + .chain(collateral_assets) + .collect(), + + accounts: self.bonded_balance, + metadata: self + .pools + .iter() + .flat_map(|(_, pool_details)| { + pool_details + .bonded_currencies + .iter() + .map(|id| (*id, vec![], vec![], pool_details.denomination)) + .collect::, Vec, u8)>>() + }) + .collect(), + } + .assimilate_storage(&mut storage) + .expect("assimilate should not fail"); - ext.execute_with(|| { - System::set_block_number(System::block_number() + 1); + let mut ext = sp_io::TestExternalities::new(storage); - self.pools.into_iter().for_each(|(pool_id, pool)| { - crate::Pools::::insert(pool_id, pool); + ext.execute_with(|| { + System::set_block_number(System::block_number() + 1); + + self.pools.into_iter().for_each(|(pool_id, pool)| { + crate::Pools::::insert(pool_id, pool); + }); }); - }); - ext - } + ext + } - #[cfg(feature = "runtime-benchmarks")] - pub(crate) fn build_with_keystore(self) -> sp_io::TestExternalities { - use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; - use sp_std::sync::Arc; + #[cfg(feature = "runtime-benchmarks")] + pub(crate) fn build_with_keystore(self) -> sp_io::TestExternalities { + use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; + use sp_std::sync::Arc; - let mut ext = self.build(); + let mut ext = self.build(); - let keystore = MemoryKeystore::new(); - ext.register_extension(KeystoreExt(Arc::new(keystore))); + let keystore = MemoryKeystore::new(); + ext.register_extension(KeystoreExt(Arc::new(keystore))); - ext + ext + } } } From e7c1c8d7fb2ebc51dfc8e314a04d0cbffe378ceb Mon Sep 17 00:00:00 2001 From: Adel Golghalyani Date: Tue, 5 Nov 2024 16:54:46 +0100 Subject: [PATCH 10/11] fix --- pallets/pallet-bonded-coins/Cargo.toml | 1 + pallets/pallet-bonded-coins/src/lib.rs | 2 +- pallets/pallet-bonded-coins/src/mock.rs | 18 ++++++++++++------ 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/pallets/pallet-bonded-coins/Cargo.toml b/pallets/pallet-bonded-coins/Cargo.toml index b70dc775d0..36e3d0e150 100644 --- a/pallets/pallet-bonded-coins/Cargo.toml +++ b/pallets/pallet-bonded-coins/Cargo.toml @@ -44,6 +44,7 @@ runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", "pallet-balances/runtime-benchmarks", ] std = [ diff --git a/pallets/pallet-bonded-coins/src/lib.rs b/pallets/pallet-bonded-coins/src/lib.rs index 3a4fb657f5..12386b40cb 100644 --- a/pallets/pallet-bonded-coins/src/lib.rs +++ b/pallets/pallet-bonded-coins/src/lib.rs @@ -7,7 +7,7 @@ pub use pallet::*; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; -#[cfg(test)] +#[cfg(any(test, feature = "runtime-benchmarks"))] mod mock; #[cfg(test)] mod tests; diff --git a/pallets/pallet-bonded-coins/src/mock.rs b/pallets/pallet-bonded-coins/src/mock.rs index da16f4179a..d1fcebd5ec 100644 --- a/pallets/pallet-bonded-coins/src/mock.rs +++ b/pallets/pallet-bonded-coins/src/mock.rs @@ -9,7 +9,10 @@ use sp_runtime::{ traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, BoundedVec, BuildStorage, MultiSignature, }; -use substrate_fixed::types::{I75F53, U75F53}; +use substrate_fixed::{ + traits::{FixedSigned, FixedUnsigned}, + types::{I75F53, U75F53}, +}; use crate::{ self as pallet_bonded_coins, @@ -50,17 +53,17 @@ pub fn assert_relative_eq(target: Float, expected: Float, epsilon: Float) { ); } -pub(crate) fn get_linear_bonding_curve() -> Curve { +pub(crate) fn get_linear_bonding_curve() -> Curve { let m = Float::from_num(0); let n = Float::from_num(2); let o = Float::from_num(3); Curve::Polynomial(PolynomialParameters { m, n, o }) } -pub(crate) fn get_linear_bonding_curve_input() -> CurveInput { - let m = FloatInput::from_num(0); - let n = FloatInput::from_num(2); - let o = FloatInput::from_num(3); +pub(crate) fn get_linear_bonding_curve_input() -> CurveInput { + let m = Float::from_num(0); + let n = Float::from_num(2); + let o = Float::from_num(3); CurveInput::Polynomial(PolynomialParametersInput { m, n, o }) } @@ -201,6 +204,9 @@ pub mod runtime { type RuntimeEvent = RuntimeEvent; type StringLimit = StringLimit; type WeightInfo = (); + + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); } parameter_types! { pub const CurrencyDeposit: Balance = 500; From 7300dd568781bd22468f65256a3d4c4fea813c64 Mon Sep 17 00:00:00 2001 From: Adel Golghalyani Date: Tue, 5 Nov 2024 17:03:29 +0100 Subject: [PATCH 11/11] fetch owner --- pallets/pallet-bonded-coins/src/traits.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pallets/pallet-bonded-coins/src/traits.rs b/pallets/pallet-bonded-coins/src/traits.rs index 554935208a..7f334c7688 100644 --- a/pallets/pallet-bonded-coins/src/traits.rs +++ b/pallets/pallet-bonded-coins/src/traits.rs @@ -24,14 +24,14 @@ where type Error = DispatchError; fn freeze(asset_id: &AssetIdOf, who: &AccountIdOf) -> Result<(), Self::Error> { - let asset_id: ::AssetId = asset_id.to_owned().into(); + let asset_id: ::AssetId = asset_id.to_owned(); let freezer = AssetsPallet::::freezer(asset_id.clone()).ok_or(Self::Error::Unavailable)?; let origin = RawOrigin::Signed(freezer); AssetsPallet::::freeze(origin.into(), asset_id.into(), who.to_owned().into()) } fn thaw(asset_id: &AssetIdOf, who: &AccountIdOf) -> Result<(), Self::Error> { - let asset_id: ::AssetId = asset_id.to_owned().into(); + let asset_id: ::AssetId = asset_id.to_owned(); let admin = AssetsPallet::::admin(asset_id.clone()).ok_or(Self::Error::Unavailable)?; let origin = RawOrigin::Signed(admin); AssetsPallet::::thaw(origin.into(), asset_id.into(), who.to_owned().into()) @@ -64,11 +64,12 @@ where { fn reset_team( id: Self::AssetId, - owner: AccountIdOf, + _owner: AccountIdOf, admin: AccountIdOf, issuer: AccountIdOf, freezer: AccountIdOf, ) -> DispatchResult { + let owner = AssetsPallet::::owner(id.clone()).ok_or(DispatchError::Unavailable)?; let origin = RawOrigin::Signed(owner); AssetsPallet::::set_team(origin.into(), id.into(), issuer.into(), admin.into(), freezer.into()) }