From 436fa05eb0ca534bb293aa0dfe30605fc41ae1fa Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Wed, 12 Jul 2023 17:26:27 -0400 Subject: [PATCH 01/22] init Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/lib.rs | 110 ++++++++++++++++++++++++++---- pallets/asset-manager/src/mock.rs | 4 +- 2 files changed, 97 insertions(+), 17 deletions(-) diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index 2d0e78d2b..e123926ce 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -50,14 +50,18 @@ pub mod pallet { transactional, PalletId, }; use frame_system::pallet_prelude::*; - use manta_primitives::assets::{ - self, AssetConfig, AssetIdLocationMap, AssetIdLpMap, AssetIdType, AssetMetadata, - AssetRegistry, FungibleLedger, LocationType, + use manta_primitives::{ + assets::{ + self, AssetConfig, AssetIdLocationMap, AssetIdLpMap, AssetIdType, AssetMetadata, + AssetRegistry, FungibleLedger, LocationType, + }, + types::Balance, }; use orml_traits::GetByKey; use sp_runtime::{ traits::{ AccountIdConversion, AtLeast32BitUnsigned, CheckedAdd, MaybeSerializeDeserialize, One, + Zero, }, ArithmeticError, }; @@ -66,6 +70,9 @@ pub mod pallet { /// Storage Version pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); + /// Used to set the minimum balance for permissionless assets + pub const POSSIBLE_ACCOUNTS_PER_ASSET: Balance = 50_000_000_000; + /// Alias for the junction type `Parachain(#[codec(compact)] u32)` pub(crate) type ParaId = u32; @@ -86,9 +93,6 @@ pub mod pallet { + TypeInfo + Copy; - /// Balance Type - type Balance: Default + Member + Parameter + TypeInfo; - /// Location Type type Location: Default + Parameter @@ -100,7 +104,7 @@ pub mod pallet { type AssetConfig: AssetConfig< Self, AssetId = Self::AssetId, - Balance = Self::Balance, + Balance = Balance, Location = Self::Location, >; @@ -115,6 +119,9 @@ pub mod pallet { /// Weight information for the extrinsics in this pallet. type WeightInfo: crate::weights::WeightInfo; + + /// Permissionless + type PermissionlessStartId: Get; } /// Asset Manager Pallet @@ -275,7 +282,7 @@ pub mod pallet { beneficiary: T::AccountId, /// Amount Minted - amount: T::Balance, + amount: Balance, }, /// Updated the minimum XCM fee for an asset @@ -329,6 +336,9 @@ pub mod pallet { /// Two asset that used for generate LP asset should exist AssetIdNotExist, + + /// AssetIdOverflow + AssetIdOverflow, } /// [`AssetId`](AssetConfig::AssetId) to [`MultiLocation`] Map @@ -362,6 +372,11 @@ pub mod pallet { #[pallet::getter(fn next_asset_id)] pub type NextAssetId = StorageValue<_, T::AssetId, ValueQuery>; + /// The Next Available Permissionless [`AssetId`](AssetConfig::AssetId) + #[pallet::storage] + #[pallet::getter(fn next_permissionless_asset_id)] + pub type NextPermissionlessAssetId = StorageValue<_, T::AssetId, ValueQuery>; + /// XCM transfer cost for each [`AssetId`](AssetConfig::AssetId) #[pallet::storage] pub type UnitsPerSecond = StorageMap<_, Blake2_128Concat, T::AssetId, u128>; @@ -564,7 +579,7 @@ pub mod pallet { origin: OriginFor, #[pallet::compact] asset_id: T::AssetId, beneficiary: T::AccountId, - amount: T::Balance, + amount: Balance, ) -> DispatchResult { T::ModifierOrigin::ensure_origin(origin)?; ensure!( @@ -678,6 +693,47 @@ pub mod pallet { }); Ok(()) } + + #[pallet::call_index(8)] + #[pallet::weight(T::WeightInfo::register_asset())] + #[transactional] + pub fn permissionless_register_asset( + origin: OriginFor, + metadata: >::AssetRegistryMetadata, + total_supply: Balance, + ) -> DispatchResult { + let who = ensure_signed(origin.clone())?; + let location = >::NativeAssetLocation::get(); + + let asset_id = Self::next_permissionless_asset_id_and_increment()?; + let min_balance: Balance = total_supply + .checked_div(POSSIBLE_ACCOUNTS_PER_ASSET) + .ok_or(ArithmeticError::DivisionByZero)?; + + // create asset and mint total supply to creator + >::AssetRegistry::create_asset( + asset_id, + metadata.clone().into(), + min_balance, + true, + ) + .map_err(|_| Error::::ErrorCreatingAsset)?; + AssetIdMetadata::::insert(asset_id, &metadata); + >::FungibleLedger::deposit_minting_with_check( + asset_id, + &who, + total_supply, + true, + ) + .map_err(|_| Error::::MintError)?; + + Self::deposit_event(Event::::AssetRegistered { + asset_id, + location, + metadata, + }); + Ok(()) + } } impl Pallet @@ -711,15 +767,39 @@ pub mod pallet { Ok(asset_id) } - /// Returns and increments the [`NextAssetId`] by one. + /// Returns and increments the [`NextAssetId`] by one. Fails if it hits the upper limit of `PermissionlessStartId` #[inline] fn next_asset_id_and_increment() -> Result { NextAssetId::::try_mutate(|current| { - let id = *current; - *current = current - .checked_add(&One::one()) - .ok_or(ArithmeticError::Overflow)?; - Ok(id) + if *current >= T::PermissionlessStartId::get() { + Err(Error::::AssetIdOverflow.into()) + } else { + let id = *current; + *current = current + .checked_add(&One::one()) + .ok_or(ArithmeticError::Overflow)?; + Ok(id) + } + }) + } + + /// Returns and increments the [`NextPermssionlessAssetId`] by one. + #[inline] + fn next_permissionless_asset_id_and_increment() -> Result { + NextPermissionlessAssetId::::try_mutate(|current| { + if current.is_zero() { + let id = T::PermissionlessStartId::get(); + *current = id + .checked_add(&One::one()) + .ok_or(ArithmeticError::Overflow)?; + Ok(id) + } else { + let id = *current; + *current = current + .checked_add(&One::one()) + .ok_or(ArithmeticError::Overflow)?; + Ok(id) + } }) } diff --git a/pallets/asset-manager/src/mock.rs b/pallets/asset-manager/src/mock.rs index eadbcbdc5..a7b5e7e0e 100644 --- a/pallets/asset-manager/src/mock.rs +++ b/pallets/asset-manager/src/mock.rs @@ -25,7 +25,7 @@ use frame_support::{ construct_runtime, pallet_prelude::DispatchResult, parameter_types, - traits::{AsEnsureOriginWithArg, ConstU32}, + traits::{AsEnsureOriginWithArg, ConstU128, ConstU32}, PalletId, }; use frame_system as system; @@ -221,12 +221,12 @@ impl AssetConfig for MantaAssetConfig { impl pallet_asset_manager::Config for Runtime { type RuntimeEvent = RuntimeEvent; type AssetId = CalamariAssetId; - type Balance = Balance; type Location = AssetLocation; type AssetConfig = MantaAssetConfig; type ModifierOrigin = EnsureRoot; type SuspenderOrigin = EnsureRoot; type PalletId = AssetManagerPalletId; + type PermissionlessStartId = ConstU128<100>; type WeightInfo = (); } From d1e47f442fabb24273c326528ea30f55232279b2 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Wed, 12 Jul 2023 18:01:00 -0400 Subject: [PATCH 02/22] make metadata not generic Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/lib.rs | 30 +++++++++++++----------------- pallets/asset-manager/src/mock.rs | 2 -- pallets/asset-manager/src/tests.rs | 11 +++++++++++ primitives/manta/src/assets.rs | 11 ++--------- 4 files changed, 26 insertions(+), 28 deletions(-) diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index e123926ce..a6dd0be19 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -53,7 +53,7 @@ pub mod pallet { use manta_primitives::{ assets::{ self, AssetConfig, AssetIdLocationMap, AssetIdLpMap, AssetIdType, AssetMetadata, - AssetRegistry, FungibleLedger, LocationType, + AssetRegistry, AssetRegistryMetadata, FungibleLedger, LocationType, }, types::Balance, }; @@ -70,8 +70,8 @@ pub mod pallet { /// Storage Version pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); - /// Used to set the minimum balance for permissionless assets - pub const POSSIBLE_ACCOUNTS_PER_ASSET: Balance = 50_000_000_000; + /// Used to set the minimum balance for permissionless assets. + pub const POSSIBLE_ACCOUNTS_PER_ASSET: Balance = 10_000_000_000; /// Alias for the junction type `Parachain(#[codec(compact)] u32)` pub(crate) type ParaId = u32; @@ -228,7 +228,7 @@ pub mod pallet { location: T::Location, /// Metadata Registered to Asset Manager - metadata: >::AssetRegistryMetadata, + metadata: AssetRegistryMetadata, }, /// A LP asset was registered @@ -243,7 +243,7 @@ pub mod pallet { asset_id: T::AssetId, /// Metadata Registered to Asset Manager - metadata: >::AssetRegistryMetadata, + metadata: AssetRegistryMetadata, }, /// Updated the location of an asset @@ -261,7 +261,7 @@ pub mod pallet { asset_id: T::AssetId, /// Updated Metadata for the Asset - metadata: >::AssetRegistryMetadata, + metadata: AssetRegistryMetadata, }, /// Updated the units-per-second for an asset @@ -360,12 +360,8 @@ pub mod pallet { /// AssetId to AssetRegistry Map. #[pallet::storage] #[pallet::getter(fn asset_id_metadata)] - pub(super) type AssetIdMetadata = StorageMap< - _, - Blake2_128Concat, - T::AssetId, - >::AssetRegistryMetadata, - >; + pub(super) type AssetIdMetadata = + StorageMap<_, Blake2_128Concat, T::AssetId, AssetRegistryMetadata>; /// The Next Available [`AssetId`](AssetConfig::AssetId) #[pallet::storage] @@ -425,7 +421,7 @@ pub mod pallet { pub fn register_asset( origin: OriginFor, location: T::Location, - metadata: >::AssetRegistryMetadata, + metadata: AssetRegistryMetadata, ) -> DispatchResult { T::ModifierOrigin::ensure_origin(origin)?; @@ -520,7 +516,7 @@ pub mod pallet { pub fn update_asset_metadata( origin: OriginFor, asset_id: T::AssetId, - metadata: >::AssetRegistryMetadata, + metadata: AssetRegistryMetadata, ) -> DispatchResult { T::ModifierOrigin::ensure_origin(origin)?; ensure!( @@ -664,7 +660,7 @@ pub mod pallet { origin: OriginFor, asset_0: T::AssetId, asset_1: T::AssetId, - metadata: >::AssetRegistryMetadata, + metadata: AssetRegistryMetadata, ) -> DispatchResult { T::ModifierOrigin::ensure_origin(origin)?; ensure!(asset_0 != asset_1, Error::::AssetIdNotDifferent); @@ -699,7 +695,7 @@ pub mod pallet { #[transactional] pub fn permissionless_register_asset( origin: OriginFor, - metadata: >::AssetRegistryMetadata, + metadata: AssetRegistryMetadata, total_supply: Balance, ) -> DispatchResult { let who = ensure_signed(origin.clone())?; @@ -743,7 +739,7 @@ pub mod pallet { /// Register asset by providing optional location and metadata. pub fn do_register_asset( location: Option<&T::Location>, - metadata: &>::AssetRegistryMetadata, + metadata: &AssetRegistryMetadata, ) -> Result { if let Some(location) = location { ensure!( diff --git a/pallets/asset-manager/src/mock.rs b/pallets/asset-manager/src/mock.rs index a7b5e7e0e..b1f07aac0 100644 --- a/pallets/asset-manager/src/mock.rs +++ b/pallets/asset-manager/src/mock.rs @@ -210,10 +210,8 @@ impl BalanceType for MantaAssetConfig { impl AssetConfig for MantaAssetConfig { type StartNonNativeAssetId = StartNonNativeAssetId; type NativeAssetId = NativeAssetId; - type AssetRegistryMetadata = AssetRegistryMetadata; type NativeAssetLocation = NativeAssetLocation; type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; type AssetRegistry = MantaAssetRegistry; type FungibleLedger = NativeAndNonNative; } diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index c7311edd0..eac613b53 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -647,3 +647,14 @@ fn register_lp_asset_should_work() { ); }); } + +#[test] +fn permissionless_register_asset_works() { + new_test_ext().execute_with(|| { + assert_ok!(AssetManager::permissionless_register_asset( + RuntimeOrigin::signed(ALICE), + create_asset_metadata("dog token", "dog", 12, 1, false, false), + 1, + )); + }); +} diff --git a/primitives/manta/src/assets.rs b/primitives/manta/src/assets.rs index 0719c9b8b..dd96949fd 100644 --- a/primitives/manta/src/assets.rs +++ b/primitives/manta/src/assets.rs @@ -28,7 +28,6 @@ use frame_support::{ fungibles::{self, Mutate, Transfer}, DepositConsequence, ExistenceRequirement, WithdrawReasons, }, - Parameter, }; use frame_system::Config; use scale_info::TypeInfo; @@ -119,12 +118,6 @@ pub trait AssetConfig: AssetIdType + BalanceType + LocationType where C: Config, { - /// Metadata type that required in token storage: e.g. AssetMetadata in Pallet-Assets. - type StorageMetadata: From; - - /// The Asset Metadata type stored in this pallet. - type AssetRegistryMetadata: AssetMetadata + Parameter + TestingDefault; - /// The AssetId that the non-native asset starts from. /// /// A typical configuration is 8, so that asset 0 - 7 is reserved. @@ -137,7 +130,7 @@ where type NativeAssetLocation: Get; /// Native Asset Metadata - type NativeAssetMetadata: Get; + type NativeAssetMetadata: Get>; /// Asset Registry /// @@ -145,7 +138,7 @@ where type AssetRegistry: AssetRegistry< AssetId = Self::AssetId, Balance = Self::Balance, - Metadata = Self::StorageMetadata, + Metadata = AssetStorageMetadata, Error = DispatchError, >; From 33c7796e4da9a4cb76296b9febdfdea37a2e6dd1 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Wed, 12 Jul 2023 18:15:54 -0400 Subject: [PATCH 03/22] better parameters Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/lib.rs | 17 ++++++++++++----- pallets/asset-manager/src/tests.rs | 4 ++-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index a6dd0be19..53c814336 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -53,7 +53,8 @@ pub mod pallet { use manta_primitives::{ assets::{ self, AssetConfig, AssetIdLocationMap, AssetIdLpMap, AssetIdType, AssetMetadata, - AssetRegistry, AssetRegistryMetadata, FungibleLedger, LocationType, + AssetRegistry, AssetRegistryMetadata, AssetStorageMetadata, FungibleLedger, + LocationType, }, types::Balance, }; @@ -695,7 +696,7 @@ pub mod pallet { #[transactional] pub fn permissionless_register_asset( origin: OriginFor, - metadata: AssetRegistryMetadata, + metadata: AssetStorageMetadata, total_supply: Balance, ) -> DispatchResult { let who = ensure_signed(origin.clone())?; @@ -709,12 +710,18 @@ pub mod pallet { // create asset and mint total supply to creator >::AssetRegistry::create_asset( asset_id, - metadata.clone().into(), + metadata.clone(), min_balance, true, ) .map_err(|_| Error::::ErrorCreatingAsset)?; - AssetIdMetadata::::insert(asset_id, &metadata); + + let register_metadata = AssetRegistryMetadata:: { + metadata: metadata.clone(), + min_balance, + is_sufficient: true, + }; + AssetIdMetadata::::insert(asset_id, ®ister_metadata); >::FungibleLedger::deposit_minting_with_check( asset_id, &who, @@ -726,7 +733,7 @@ pub mod pallet { Self::deposit_event(Event::::AssetRegistered { asset_id, location, - metadata, + metadata: register_metadata, }); Ok(()) } diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index eac613b53..cd4dcec4d 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -653,8 +653,8 @@ fn permissionless_register_asset_works() { new_test_ext().execute_with(|| { assert_ok!(AssetManager::permissionless_register_asset( RuntimeOrigin::signed(ALICE), - create_asset_metadata("dog token", "dog", 12, 1, false, false), - 1, + create_asset_metadata("dog token", "dog", 12, 1, false, false).into(), + 1_000_000_000_000_000, )); }); } From 10479c2b9d1eeb6bacbb44d175f9d8cb99d84a12 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Thu, 13 Jul 2023 18:55:10 -0400 Subject: [PATCH 04/22] tests Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/lib.rs | 18 +++++++++++++-- pallets/asset-manager/src/mock.rs | 2 ++ pallets/asset-manager/src/tests.rs | 37 +++++++++++++++++++++++++++++- 3 files changed, 54 insertions(+), 3 deletions(-) diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index 53c814336..57e61a7b9 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -121,8 +121,14 @@ pub mod pallet { /// Weight information for the extrinsics in this pallet. type WeightInfo: crate::weights::WeightInfo; - /// Permissionless + /// AssetId where Permissionless Assets start is less than, the type PermissionlessStartId: Get; + + /// Max length of token name + type TokenNameMaxLen: Get; + + /// Max length of token symbol + type TokenSymbolMaxLen: Get; } /// Asset Manager Pallet @@ -696,7 +702,9 @@ pub mod pallet { #[transactional] pub fn permissionless_register_asset( origin: OriginFor, - metadata: AssetStorageMetadata, + name: BoundedVec, + symbol: BoundedVec, + decimals: u8, total_supply: Balance, ) -> DispatchResult { let who = ensure_signed(origin.clone())?; @@ -707,6 +715,12 @@ pub mod pallet { .checked_div(POSSIBLE_ACCOUNTS_PER_ASSET) .ok_or(ArithmeticError::DivisionByZero)?; + let metadata = AssetStorageMetadata { + name: name.into(), + symbol: symbol.into(), + decimals, + is_frozen: false, + }; // create asset and mint total supply to creator >::AssetRegistry::create_asset( asset_id, diff --git a/pallets/asset-manager/src/mock.rs b/pallets/asset-manager/src/mock.rs index b1f07aac0..f10d6bbff 100644 --- a/pallets/asset-manager/src/mock.rs +++ b/pallets/asset-manager/src/mock.rs @@ -225,6 +225,8 @@ impl pallet_asset_manager::Config for Runtime { type SuspenderOrigin = EnsureRoot; type PalletId = AssetManagerPalletId; type PermissionlessStartId = ConstU128<100>; + type TokenNameMaxLen = ConstU32<100>; + type TokenSymbolMaxLen = ConstU32<100>; type WeightInfo = (); } diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index cd4dcec4d..ce1032fff 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -648,13 +648,48 @@ fn register_lp_asset_should_work() { }); } +#[test] +fn permissionless_edge_cases() { + new_test_ext().execute_with(|| { + // cannot create asset with zero supply + assert_noop!( + AssetManager::permissionless_register_asset( + RuntimeOrigin::signed(ALICE), + "dog token".as_bytes().to_vec().try_into().unwrap(), + "dog".as_bytes().to_vec().try_into().unwrap(), + 12, + 0, + ), + Error::::ErrorCreatingAsset + ); + + // cannot create asset with total supply less than decimcals + assert_noop!( + AssetManager::permissionless_register_asset( + RuntimeOrigin::signed(ALICE), + "dog token".as_bytes().to_vec().try_into().unwrap(), + "dog".as_bytes().to_vec().try_into().unwrap(), + 12, + 1, + ), + Error::::ErrorCreatingAsset + ); + }); +} + #[test] fn permissionless_register_asset_works() { new_test_ext().execute_with(|| { assert_ok!(AssetManager::permissionless_register_asset( RuntimeOrigin::signed(ALICE), - create_asset_metadata("dog token", "dog", 12, 1, false, false).into(), + "dog token".as_bytes().to_vec().try_into().unwrap(), + "dog".as_bytes().to_vec().try_into().unwrap(), + 12, 1_000_000_000_000_000, )); + let asset_id = AssetManager::next_permissionless_asset_id(); + + // asset created gives alice the token + assert_eq!(Assets::balance(asset_id - 1, &ALICE), 1_000_000_000_000_000); }); } From f913999144ffb261223839639992452d0f7d2e8a Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Thu, 13 Jul 2023 19:47:03 -0400 Subject: [PATCH 05/22] need native token to create asset Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/lib.rs | 15 ++++++++++++++- pallets/asset-manager/src/mock.rs | 1 + pallets/asset-manager/src/tests.rs | 18 ++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index 57e61a7b9..1f90392fc 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -46,7 +46,7 @@ pub mod pallet { use crate::weights::WeightInfo; use frame_support::{ pallet_prelude::*, - traits::{Contains, StorageVersion}, + traits::{tokens::ExistenceRequirement, Contains, StorageVersion}, transactional, PalletId, }; use frame_system::pallet_prelude::*; @@ -129,6 +129,9 @@ pub mod pallet { /// Max length of token symbol type TokenSymbolMaxLen: Get; + + /// Cost of regersting a permissionless asset in native token + type PermissionlessAssetRegistryCost: Get; } /// Asset Manager Pallet @@ -710,6 +713,16 @@ pub mod pallet { let who = ensure_signed(origin.clone())?; let location = >::NativeAssetLocation::get(); + let native_asset_id = >::NativeAssetId::get(); + >::FungibleLedger::transfer( + native_asset_id, + &who, + &Self::account_id(), + T::PermissionlessAssetRegistryCost::get(), + ExistenceRequirement::AllowDeath, + ) + .map_err(|_| Error::::MintError)?; + let asset_id = Self::next_permissionless_asset_id_and_increment()?; let min_balance: Balance = total_supply .checked_div(POSSIBLE_ACCOUNTS_PER_ASSET) diff --git a/pallets/asset-manager/src/mock.rs b/pallets/asset-manager/src/mock.rs index f10d6bbff..ba1b78cbe 100644 --- a/pallets/asset-manager/src/mock.rs +++ b/pallets/asset-manager/src/mock.rs @@ -227,6 +227,7 @@ impl pallet_asset_manager::Config for Runtime { type PermissionlessStartId = ConstU128<100>; type TokenNameMaxLen = ConstU32<100>; type TokenSymbolMaxLen = ConstU32<100>; + type PermissionlessAssetRegistryCost = ConstU128<1000>; type WeightInfo = (); } diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index ce1032fff..35015f946 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -651,6 +651,15 @@ fn register_lp_asset_should_work() { #[test] fn permissionless_edge_cases() { new_test_ext().execute_with(|| { + let native_asset_id = >::NativeAssetId::get(); + assert_ok!( + >::FungibleLedger::deposit_minting( + native_asset_id, + &ALICE, + 1_000_000 + ) + ); + // cannot create asset with zero supply assert_noop!( AssetManager::permissionless_register_asset( @@ -680,6 +689,15 @@ fn permissionless_edge_cases() { #[test] fn permissionless_register_asset_works() { new_test_ext().execute_with(|| { + let native_asset_id = >::NativeAssetId::get(); + assert_ok!( + >::FungibleLedger::deposit_minting( + native_asset_id, + &ALICE, + 1_000_000 + ) + ); + assert_ok!(AssetManager::permissionless_register_asset( RuntimeOrigin::signed(ALICE), "dog token".as_bytes().to_vec().try_into().unwrap(), From ab562d5c837236e032b2a8af85835514a8925fb5 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Thu, 13 Jul 2023 20:45:36 -0400 Subject: [PATCH 06/22] handle edge cases: Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/lib.rs | 21 +++++++++-- pallets/asset-manager/src/tests.rs | 56 ++++++++++++++++++++++++++---- 2 files changed, 69 insertions(+), 8 deletions(-) diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index 1f90392fc..b4690d01a 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -349,6 +349,15 @@ pub mod pallet { /// AssetIdOverflow AssetIdOverflow, + + /// Account does not have enough native funds + NoNativeFunds, + + /// Total Supply is less than decimal value + TotalSupplyTooLow, + + /// Decimals cannot be set to zero + DecimalIsZero, } /// [`AssetId`](AssetConfig::AssetId) to [`MultiLocation`] Map @@ -712,6 +721,11 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin.clone())?; let location = >::NativeAssetLocation::get(); + let decimal_num = + u128::checked_pow(10, decimals.into()).ok_or(ArithmeticError::Overflow)?; + + ensure!(total_supply >= decimal_num, Error::::TotalSupplyTooLow); + ensure!(!decimals.is_zero(), Error::::DecimalIsZero); let native_asset_id = >::NativeAssetId::get(); >::FungibleLedger::transfer( @@ -721,12 +735,15 @@ pub mod pallet { T::PermissionlessAssetRegistryCost::get(), ExistenceRequirement::AllowDeath, ) - .map_err(|_| Error::::MintError)?; + .map_err(|_| Error::::NoNativeFunds)?; let asset_id = Self::next_permissionless_asset_id_and_increment()?; - let min_balance: Balance = total_supply + let mut min_balance: Balance = total_supply .checked_div(POSSIBLE_ACCOUNTS_PER_ASSET) .ok_or(ArithmeticError::DivisionByZero)?; + if min_balance.is_zero() { + min_balance = One::one(); + } let metadata = AssetStorageMetadata { name: name.into(), diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index 35015f946..23ecd9bd6 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -31,7 +31,7 @@ use manta_primitives::{ types::Balance, }; use orml_traits::GetByKey; -use sp_runtime::traits::BadOrigin; +use sp_runtime::{traits::BadOrigin, ArithmeticError}; use xcm::{latest::prelude::*, VersionedMultiLocation}; pub const ALICE: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([0u8; 32]); @@ -666,13 +666,49 @@ fn permissionless_edge_cases() { RuntimeOrigin::signed(ALICE), "dog token".as_bytes().to_vec().try_into().unwrap(), "dog".as_bytes().to_vec().try_into().unwrap(), - 12, - 0, + 0_u8, + 0_u128, + ), + Error::::TotalSupplyTooLow + ); + + // cannot create asset with zero supply + assert_noop!( + AssetManager::permissionless_register_asset( + RuntimeOrigin::signed(ALICE), + "dog token".as_bytes().to_vec().try_into().unwrap(), + "dog".as_bytes().to_vec().try_into().unwrap(), + 1_u8, + 0_u128, + ), + Error::::TotalSupplyTooLow + ); + + // cannot create asset with zero decimals + assert_noop!( + AssetManager::permissionless_register_asset( + RuntimeOrigin::signed(ALICE), + "dog token".as_bytes().to_vec().try_into().unwrap(), + "dog".as_bytes().to_vec().try_into().unwrap(), + 0_u8, + 1_u128, ), - Error::::ErrorCreatingAsset + Error::::DecimalIsZero ); - // cannot create asset with total supply less than decimcals + // cannot create asset with zero supply + assert_noop!( + AssetManager::permissionless_register_asset( + RuntimeOrigin::signed(ALICE), + "dog token".as_bytes().to_vec().try_into().unwrap(), + "dog".as_bytes().to_vec().try_into().unwrap(), + u8::MAX, + u128::MAX, + ), + ArithmeticError::Overflow + ); + + // cannot create asset with too small total supply assert_noop!( AssetManager::permissionless_register_asset( RuntimeOrigin::signed(ALICE), @@ -681,7 +717,7 @@ fn permissionless_edge_cases() { 12, 1, ), - Error::::ErrorCreatingAsset + Error::::TotalSupplyTooLow, ); }); } @@ -709,5 +745,13 @@ fn permissionless_register_asset_works() { // asset created gives alice the token assert_eq!(Assets::balance(asset_id - 1, &ALICE), 1_000_000_000_000_000); + + assert_ok!(AssetManager::permissionless_register_asset( + RuntimeOrigin::signed(ALICE), + "dog token".as_bytes().to_vec().try_into().unwrap(), + "dog".as_bytes().to_vec().try_into().unwrap(), + 6, + u128::MAX, + )); }); } From e441db2ba655d0b7e3d251ffc20cc5a1470d8976 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Thu, 13 Jul 2023 20:53:19 -0400 Subject: [PATCH 07/22] fix comments Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/lib.rs | 8 ++++---- pallets/asset-manager/src/tests.rs | 3 ++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index b4690d01a..a5c9d7e54 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -121,7 +121,7 @@ pub mod pallet { /// Weight information for the extrinsics in this pallet. type WeightInfo: crate::weights::WeightInfo; - /// AssetId where Permissionless Assets start is less than, the + /// AssetId where Permissionless Assets start, must be greater than `StartNonNativeAssetId` type PermissionlessStartId: Get; /// Max length of token name @@ -130,7 +130,7 @@ pub mod pallet { /// Max length of token symbol type TokenSymbolMaxLen: Get; - /// Cost of regersting a permissionless asset in native token + /// Cost of registering a permissionless asset in native token type PermissionlessAssetRegistryCost: Get; } @@ -351,7 +351,7 @@ pub mod pallet { AssetIdOverflow, /// Account does not have enough native funds - NoNativeFunds, + NotEnoughNativeFunds, /// Total Supply is less than decimal value TotalSupplyTooLow, @@ -735,7 +735,7 @@ pub mod pallet { T::PermissionlessAssetRegistryCost::get(), ExistenceRequirement::AllowDeath, ) - .map_err(|_| Error::::NoNativeFunds)?; + .map_err(|_| Error::::NotEnoughNativeFunds)?; let asset_id = Self::next_permissionless_asset_id_and_increment()?; let mut min_balance: Balance = total_supply diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index 23ecd9bd6..ebe260a43 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -696,7 +696,7 @@ fn permissionless_edge_cases() { Error::::DecimalIsZero ); - // cannot create asset with zero supply + // overflows when decimal is too high assert_noop!( AssetManager::permissionless_register_asset( RuntimeOrigin::signed(ALICE), @@ -746,6 +746,7 @@ fn permissionless_register_asset_works() { // asset created gives alice the token assert_eq!(Assets::balance(asset_id - 1, &ALICE), 1_000_000_000_000_000); + // Max balance works assert_ok!(AssetManager::permissionless_register_asset( RuntimeOrigin::signed(ALICE), "dog token".as_bytes().to_vec().try_into().unwrap(), From 8198ca36abc627854d669b51edf4d1357f4a17fb Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Thu, 13 Jul 2023 20:57:44 -0400 Subject: [PATCH 08/22] add sanity check Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/lib.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index a5c9d7e54..dc19f89a8 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -215,6 +215,11 @@ pub mod pallet { impl GenesisBuild for GenesisConfig { #[inline] fn build(&self) { + assert!( + T::PermissionlessStartId::get() + > >::StartNonNativeAssetId::get(), + "Permissionless start id must be greater than non native id start" + ); NextAssetId::::set(self.start_id); let asset_id = >::NativeAssetId::get(); let metadata = >::NativeAssetMetadata::get(); From 22af5aafca01808b799af3aa066e4eb3ae83be68 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Thu, 13 Jul 2023 23:06:26 -0400 Subject: [PATCH 09/22] add to runtimes and mocks Signed-off-by: Charles Ferrell --- pallets/farming/src/mock.rs | 9 +++++---- pallets/manta-pay/Cargo.toml | 3 ++- pallets/manta-pay/src/mock.rs | 9 +++++---- pallets/manta-sbt/src/mock.rs | 7 ++++--- runtime/calamari/src/assets_config.rs | 7 ++++--- runtime/integration-tests/src/xcm_mock/parachain.rs | 9 +++++---- runtime/manta/src/assets_config.rs | 7 ++++--- 7 files changed, 29 insertions(+), 22 deletions(-) diff --git a/pallets/farming/src/mock.rs b/pallets/farming/src/mock.rs index 6eaf9e9a2..db6562232 100644 --- a/pallets/farming/src/mock.rs +++ b/pallets/farming/src/mock.rs @@ -35,7 +35,7 @@ use manta_primitives::{ currencies::Currencies, types::CalamariAssetId, }; -use sp_core::{ConstU32, H256}; +use sp_core::{ConstU128, ConstU32, H256}; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, @@ -251,10 +251,8 @@ impl BalanceType for MantaAssetConfig { impl AssetConfig for MantaAssetConfig { type NativeAssetId = NativeAssetId; type StartNonNativeAssetId = StartNonNativeAssetId; - type AssetRegistryMetadata = AssetRegistryMetadata; type NativeAssetLocation = NativeAssetLocation; type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; type AssetRegistry = MantaAssetRegistry; type FungibleLedger = NativeAndNonNative; } @@ -262,13 +260,16 @@ impl AssetConfig for MantaAssetConfig { impl pallet_asset_manager::Config for Runtime { type RuntimeEvent = RuntimeEvent; type AssetId = CalamariAssetId; - type Balance = Balance; type Location = AssetLocation; type AssetConfig = MantaAssetConfig; type ModifierOrigin = EnsureRoot; type SuspenderOrigin = EnsureRoot; type PalletId = AssetManagerPalletId; type WeightInfo = (); + type PermissionlessStartId = ConstU128<100>; + type TokenNameMaxLen = ConstU32<100>; + type TokenSymbolMaxLen = ConstU32<100>; + type PermissionlessAssetRegistryCost = ConstU128<1000>; } parameter_types! { diff --git a/pallets/manta-pay/Cargo.toml b/pallets/manta-pay/Cargo.toml index 00dcdbb22..2d0750ba2 100644 --- a/pallets/manta-pay/Cargo.toml +++ b/pallets/manta-pay/Cargo.toml @@ -42,6 +42,7 @@ runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "manta-primitives/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", ] try-runtime = [ @@ -124,7 +125,7 @@ lazy_static = "1.4.0" manta-crypto = { git = "https://github.com/manta-network/manta-rs.git", tag = "v0.5.15", features = ["getrandom"] } manta-pay = { git = "https://github.com/manta-network/manta-rs.git", tag = "v0.5.15", features = ["groth16", "parameters", "scale", "download", "test"] } pallet-asset-manager = { path = "../asset-manager" } -pallet-assets = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.37", features = ["runtime-benchmarks"] } +pallet-assets = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.37" } pallet-balances = { git = 'https://github.com/paritytech/substrate.git', branch = "polkadot-v0.9.37" } pallet-tx-pause = { path = '../tx-pause' } sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.37" } diff --git a/pallets/manta-pay/src/mock.rs b/pallets/manta-pay/src/mock.rs index 5c2c7bce2..e7738302b 100644 --- a/pallets/manta-pay/src/mock.rs +++ b/pallets/manta-pay/src/mock.rs @@ -17,7 +17,7 @@ use frame_support::{ pallet_prelude::DispatchResult, parameter_types, - traits::{AsEnsureOriginWithArg, ConstU32, IsInVec}, + traits::{AsEnsureOriginWithArg, ConstU128, ConstU32, IsInVec}, PalletId, }; use frame_system::{EnsureNever, EnsureRoot}; @@ -239,10 +239,8 @@ impl BalanceType for MantaAssetConfig { impl AssetConfig for MantaAssetConfig { type NativeAssetId = NativeAssetId; type StartNonNativeAssetId = StartNonNativeAssetId; - type AssetRegistryMetadata = AssetRegistryMetadata; type NativeAssetLocation = NativeAssetLocation; type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; type AssetRegistry = MantaAssetRegistry; type FungibleLedger = NativeAndNonNative; } @@ -250,13 +248,16 @@ impl AssetConfig for MantaAssetConfig { impl pallet_asset_manager::Config for Test { type RuntimeEvent = RuntimeEvent; type AssetId = StandardAssetId; - type Balance = Balance; type Location = AssetLocation; type AssetConfig = MantaAssetConfig; type ModifierOrigin = EnsureRoot; type SuspenderOrigin = EnsureRoot; type PalletId = AssetManagerPalletId; type WeightInfo = (); + type PermissionlessStartId = ConstU128<100>; + type TokenNameMaxLen = ConstU32<100>; + type TokenSymbolMaxLen = ConstU32<100>; + type PermissionlessAssetRegistryCost = ConstU128<1000>; } parameter_types! { diff --git a/pallets/manta-sbt/src/mock.rs b/pallets/manta-sbt/src/mock.rs index f0536badb..ff59fbab8 100644 --- a/pallets/manta-sbt/src/mock.rs +++ b/pallets/manta-sbt/src/mock.rs @@ -267,24 +267,25 @@ impl BalanceType for MantaAssetConfig { } impl AssetConfig for MantaAssetConfig { type NativeAssetId = NativeAssetId; - type AssetRegistryMetadata = AssetRegistryMetadata; type StartNonNativeAssetId = StartNonNativeAssetId; type NativeAssetLocation = NativeAssetLocation; type NativeAssetMetadata = NativeAssetMetadata; type AssetRegistry = MantaAssetRegistry; - type StorageMetadata = AssetStorageMetadata; type FungibleLedger = NativeAndNonNative; } impl pallet_asset_manager::Config for Test { type RuntimeEvent = RuntimeEvent; type AssetId = StandardAssetId; - type Balance = Balance; type Location = AssetLocation; type AssetConfig = MantaAssetConfig; type ModifierOrigin = EnsureRoot; type SuspenderOrigin = EnsureRoot; type PalletId = AssetManagerPalletId; + type PermissionlessStartId = ConstU128<100>; + type TokenNameMaxLen = ConstU32<100>; + type TokenSymbolMaxLen = ConstU32<100>; + type PermissionlessAssetRegistryCost = ConstU128<1000>; type WeightInfo = (); } diff --git a/runtime/calamari/src/assets_config.rs b/runtime/calamari/src/assets_config.rs index bd243cba4..0a86c5dc3 100644 --- a/runtime/calamari/src/assets_config.rs +++ b/runtime/calamari/src/assets_config.rs @@ -163,18 +163,19 @@ impl AssetIdType for CalamariAssetConfig { impl AssetConfig for CalamariAssetConfig { type StartNonNativeAssetId = StartNonNativeAssetId; type NativeAssetId = NativeAssetId; - type AssetRegistryMetadata = AssetRegistryMetadata; type NativeAssetLocation = NativeAssetLocation; type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; type AssetRegistry = CalamariAssetRegistry; type FungibleLedger = CalamariConcreteFungibleLedger; } impl pallet_asset_manager::Config for Runtime { + type PermissionlessStartId = ConstU128<1_000_000_000>; + type TokenNameMaxLen = ConstU32<200>; + type TokenSymbolMaxLen = ConstU32<10>; + type PermissionlessAssetRegistryCost = ConstU128<{ 1_000 * KMA }>; type RuntimeEvent = RuntimeEvent; type AssetId = CalamariAssetId; - type Balance = Balance; type Location = AssetLocation; type AssetConfig = CalamariAssetConfig; type ModifierOrigin = EnsureRoot; diff --git a/runtime/integration-tests/src/xcm_mock/parachain.rs b/runtime/integration-tests/src/xcm_mock/parachain.rs index 9a2de5350..aca8676e1 100644 --- a/runtime/integration-tests/src/xcm_mock/parachain.rs +++ b/runtime/integration-tests/src/xcm_mock/parachain.rs @@ -24,7 +24,7 @@ use frame_support::{ assert_ok, construct_runtime, match_types, pallet_prelude::DispatchResult, parameter_types, - traits::{AsEnsureOriginWithArg, ConstU32, Contains, Currency, Everything, Nothing}, + traits::{AsEnsureOriginWithArg, ConstU128, ConstU32, Contains, Currency, Everything, Nothing}, weights::Weight, PalletId, }; @@ -620,10 +620,8 @@ impl BalanceType for ParachainAssetConfig { impl AssetConfig for ParachainAssetConfig { type StartNonNativeAssetId = StartNonNativeAssetId; type NativeAssetId = NativeAssetId; - type AssetRegistryMetadata = AssetRegistryMetadata; type NativeAssetLocation = NativeAssetLocation; type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; type AssetRegistry = CalamariAssetRegistry; type FungibleLedger = NativeAndNonNative; } @@ -631,13 +629,16 @@ impl AssetConfig for ParachainAssetConfig { impl pallet_asset_manager::Config for Runtime { type RuntimeEvent = RuntimeEvent; type AssetId = CalamariAssetId; - type Balance = Balance; type Location = AssetLocation; type AssetConfig = ParachainAssetConfig; type ModifierOrigin = EnsureRoot; type SuspenderOrigin = EnsureRoot; type PalletId = AssetManagerPalletId; type WeightInfo = (); + type PermissionlessStartId = ConstU128<1_000_000_000>; + type TokenNameMaxLen = ConstU32<100>; + type TokenSymbolMaxLen = ConstU32<100>; + type PermissionlessAssetRegistryCost = ConstU128<1000>; } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/runtime/manta/src/assets_config.rs b/runtime/manta/src/assets_config.rs index a9f2d9497..342eeb1d4 100644 --- a/runtime/manta/src/assets_config.rs +++ b/runtime/manta/src/assets_config.rs @@ -160,18 +160,19 @@ impl AssetIdType for MantaAssetConfig { impl AssetConfig for MantaAssetConfig { type StartNonNativeAssetId = StartNonNativeAssetId; type NativeAssetId = NativeAssetId; - type AssetRegistryMetadata = AssetRegistryMetadata; type NativeAssetLocation = NativeAssetLocation; type NativeAssetMetadata = NativeAssetMetadata; - type StorageMetadata = AssetStorageMetadata; type AssetRegistry = MantaAssetRegistry; type FungibleLedger = MantaConcreteFungibleLedger; } impl pallet_asset_manager::Config for Runtime { + type PermissionlessStartId = ConstU128<1_000_000_000>; + type TokenNameMaxLen = ConstU32<200>; + type TokenSymbolMaxLen = ConstU32<10>; + type PermissionlessAssetRegistryCost = ConstU128<{ 50 * MANTA }>; type RuntimeEvent = RuntimeEvent; type AssetId = MantaAssetId; - type Balance = Balance; type Location = AssetLocation; type AssetConfig = MantaAssetConfig; type ModifierOrigin = EnsureRoot; From 9b8d59b82d1f52f90d18b1166d0708994fd51b9e Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Fri, 14 Jul 2023 14:22:31 -0400 Subject: [PATCH 10/22] add benchmarks Signed-off-by: Charles Ferrell --- pallets/asset-manager/Cargo.toml | 1 + pallets/asset-manager/src/benchmarking.rs | 43 +++++++++++++---------- pallets/asset-manager/src/lib.rs | 12 +++++-- 3 files changed, 35 insertions(+), 21 deletions(-) diff --git a/pallets/asset-manager/Cargo.toml b/pallets/asset-manager/Cargo.toml index b57d3b878..78b3836c4 100644 --- a/pallets/asset-manager/Cargo.toml +++ b/pallets/asset-manager/Cargo.toml @@ -36,6 +36,7 @@ runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "manta-primitives/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", ] std = [ "codec/std", diff --git a/pallets/asset-manager/src/benchmarking.rs b/pallets/asset-manager/src/benchmarking.rs index c963ca728..41814d272 100644 --- a/pallets/asset-manager/src/benchmarking.rs +++ b/pallets/asset-manager/src/benchmarking.rs @@ -19,7 +19,10 @@ use crate::{Call, Config, Pallet}; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; use frame_system::{EventRecord, RawOrigin}; -use manta_primitives::assets::{AssetConfig, TestingDefault, UnitsPerSecond}; +use manta_primitives::{ + assets::{AssetConfig, AssetRegistryMetadata, TestingDefault, UnitsPerSecond}, + types::Balance, +}; use xcm::latest::prelude::*; fn assert_last_event(generic_event: ::RuntimeEvent) { @@ -30,11 +33,11 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { } benchmarks! { - where_clause { where T::Location: From, ::Balance: From, ::AssetId: From } + where_clause { where T::Location: From, ::AssetId: From } register_asset { let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); }: _(RawOrigin::Root, location.clone(), metadata) verify { assert_eq!(Pallet::::asset_id_location(crate::NextAssetId::::get() - 1.into()), Some(location)); @@ -45,13 +48,13 @@ benchmarks! { for i in 8..assets_count + 8 { let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); let location = T::Location::from(location.clone()); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; Pallet::::set_units_per_second(RawOrigin::Root.into(), ::AssetId::from(i), 0)?; } // does not really matter what we register, as long as it is different than the previous let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); let amount = 10; Pallet::::register_asset(RawOrigin::Root.into(), location, metadata)?; let some_valid_asset_id = ::AssetId::from(assets_count + 8); @@ -65,12 +68,12 @@ benchmarks! { for i in 0..assets_count { let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); let location = T::Location::from(location.clone()); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; } // does not really matter what we register, as long as it is different than the previous let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); Pallet::::register_asset(RawOrigin::Root.into(), location, metadata)?; let new_location = T::Location::from(MultiLocation::new(0, X1(Parachain(1000)))); let some_valid_asset_id = ::AssetId::from(assets_count); @@ -84,12 +87,12 @@ benchmarks! { for i in 0..assets_count { let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); let location = T::Location::from(location.clone()); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; } // does not really matter what we register, as long as it is different than the previous let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); Pallet::::register_asset(RawOrigin::Root.into(), location, metadata.clone())?; let some_valid_asset_id = ::AssetId::from(assets_count); }: _(RawOrigin::Root, some_valid_asset_id, metadata.clone()) @@ -101,19 +104,19 @@ benchmarks! { let assets_count = 1000; for i in 0..assets_count { let location = T::Location::from(MultiLocation::new(0, X1(Parachain(i)))); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; } let beneficiary: T::AccountId = whitelisted_caller(); let amount = 100; // does not really matter what we register, as long as it is different than the previous let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); Pallet::::register_asset(RawOrigin::Root.into(), location, metadata)?; let some_valid_asset_id = ::AssetId::from(assets_count); - }: _(RawOrigin::Root, ::AssetId::from(assets_count), beneficiary.clone(), ::Balance::from(amount) ) + }: _(RawOrigin::Root, ::AssetId::from(assets_count), beneficiary.clone(), amount ) verify { - assert_last_event::(crate::Event::AssetMinted { asset_id: some_valid_asset_id, beneficiary, amount: ::Balance::from(amount) }.into()); + assert_last_event::(crate::Event::AssetMinted { asset_id: some_valid_asset_id, beneficiary, amount }.into()); } set_min_xcm_fee { @@ -121,7 +124,7 @@ benchmarks! { for i in 8..assets_count + 8 { let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); let location = T::Location::from(location.clone()); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; Pallet::::set_units_per_second(RawOrigin::Root.into(), ::AssetId::from(i), 0)?; @@ -129,7 +132,7 @@ benchmarks! { // does not really matter what we register, as long as it is different than the previous let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); let min_xcm_fee = 10; Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata)?; @@ -143,7 +146,7 @@ benchmarks! { for i in 0..assets_count { let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); let location = T::Location::from(location.clone()); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; } let location: MultiLocation = MultiLocation::new(0, X1(Parachain(1))); @@ -158,15 +161,19 @@ benchmarks! { for i in 8..assets_count { let location: MultiLocation = MultiLocation::new(0, X1(Parachain(i))); let location = T::Location::from(location.clone()); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); Pallet::::register_asset(RawOrigin::Root.into(), location.clone(), metadata.clone())?; } - let lp_metadata = >::AssetRegistryMetadata::testing_default(); + let lp_metadata = AssetRegistryMetadata::::testing_default(); }: _(RawOrigin::Root, current_asset_id, current_asset_id + 1.into(), lp_metadata) verify { assert_eq!(Pallet::::asset_id_pair_to_lp((current_asset_id, current_asset_id + 1.into())), Some(current_asset_id + 2.into())); assert_eq!(Pallet::::lp_to_asset_id_pair(current_asset_id + 2.into()), Some((current_asset_id, current_asset_id + 1.into()))); } + + permissionless_register_asset { + let caller = whitelisted_caller(); + }: _(RawOrigin::Signed(caller), vec![].try_into().unwrap(), vec![].try_into().unwrap(), 12, 1_000_000_000_000_000) } impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Runtime); diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index dc19f89a8..e52929df0 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -320,6 +320,14 @@ pub mod pallet { /// The asset location which can be transferred out filtered_location: T::Location, }, + /// A new asset was registered + PermissionlessAssetRegistered { + /// Asset Id of new Asset + asset_id: T::AssetId, + + /// Metadata Registered to Asset Manager + metadata: AssetRegistryMetadata, + }, } /// Asset Manager Error @@ -725,7 +733,6 @@ pub mod pallet { total_supply: Balance, ) -> DispatchResult { let who = ensure_signed(origin.clone())?; - let location = >::NativeAssetLocation::get(); let decimal_num = u128::checked_pow(10, decimals.into()).ok_or(ArithmeticError::Overflow)?; @@ -779,9 +786,8 @@ pub mod pallet { ) .map_err(|_| Error::::MintError)?; - Self::deposit_event(Event::::AssetRegistered { + Self::deposit_event(Event::::PermissionlessAssetRegistered { asset_id, - location, metadata: register_metadata, }); Ok(()) From ccb31dcace24dbe87bcb88cb988ea5ae3737d206 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Fri, 14 Jul 2023 14:33:49 -0400 Subject: [PATCH 11/22] fix benchmarks Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/benchmarking.rs | 9 ++++++++- pallets/asset-manager/src/mock.rs | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/pallets/asset-manager/src/benchmarking.rs b/pallets/asset-manager/src/benchmarking.rs index 41814d272..7fbe9cab1 100644 --- a/pallets/asset-manager/src/benchmarking.rs +++ b/pallets/asset-manager/src/benchmarking.rs @@ -18,9 +18,10 @@ use crate::{Call, Config, Pallet}; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; +use frame_support::traits::Get; use frame_system::{EventRecord, RawOrigin}; use manta_primitives::{ - assets::{AssetConfig, AssetRegistryMetadata, TestingDefault, UnitsPerSecond}, + assets::{AssetConfig, AssetRegistryMetadata, FungibleLedger, TestingDefault, UnitsPerSecond}, types::Balance, }; use xcm::latest::prelude::*; @@ -173,6 +174,12 @@ benchmarks! { permissionless_register_asset { let caller = whitelisted_caller(); + let native_asset_id = >::NativeAssetId::get(); + let _ = >::FungibleLedger::deposit_minting( + native_asset_id, + &caller, + 1_000_000 + ); }: _(RawOrigin::Signed(caller), vec![].try_into().unwrap(), vec![].try_into().unwrap(), 12, 1_000_000_000_000_000) } diff --git a/pallets/asset-manager/src/mock.rs b/pallets/asset-manager/src/mock.rs index ba1b78cbe..ed2b4ec94 100644 --- a/pallets/asset-manager/src/mock.rs +++ b/pallets/asset-manager/src/mock.rs @@ -224,7 +224,7 @@ impl pallet_asset_manager::Config for Runtime { type ModifierOrigin = EnsureRoot; type SuspenderOrigin = EnsureRoot; type PalletId = AssetManagerPalletId; - type PermissionlessStartId = ConstU128<100>; + type PermissionlessStartId = ConstU128<1_000_000>; type TokenNameMaxLen = ConstU32<100>; type TokenSymbolMaxLen = ConstU32<100>; type PermissionlessAssetRegistryCost = ConstU128<1000>; From 43480590f44f5e6417af126b38a76259e617f04d Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Fri, 14 Jul 2023 14:44:20 -0400 Subject: [PATCH 12/22] fix farming benchmarks Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/benchmarking.rs | 2 +- pallets/farming/src/benchmarking.rs | 17 ++++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/pallets/asset-manager/src/benchmarking.rs b/pallets/asset-manager/src/benchmarking.rs index 7fbe9cab1..7f94a3758 100644 --- a/pallets/asset-manager/src/benchmarking.rs +++ b/pallets/asset-manager/src/benchmarking.rs @@ -17,7 +17,7 @@ #![cfg(feature = "runtime-benchmarks")] use crate::{Call, Config, Pallet}; -use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelisted_caller}; +use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, vec, whitelisted_caller}; use frame_support::traits::Get; use frame_system::{EventRecord, RawOrigin}; use manta_primitives::{ diff --git a/pallets/farming/src/benchmarking.rs b/pallets/farming/src/benchmarking.rs index db0360706..f9d1b8dda 100644 --- a/pallets/farming/src/benchmarking.rs +++ b/pallets/farming/src/benchmarking.rs @@ -21,13 +21,16 @@ use crate::{Pallet as Farming, *}; use frame_benchmarking::{benchmarks, vec, whitelisted_caller}; use frame_support::{assert_ok, sp_runtime::traits::UniqueSaturatedFrom}; use frame_system::{Pallet as System, RawOrigin}; -use manta_primitives::assets::{AssetConfig, FungibleLedger, TestingDefault}; +use manta_primitives::{ + assets::{AssetConfig, AssetRegistryMetadata, FungibleLedger, TestingDefault}, + types::Balance, +}; use pallet_asset_manager::Pallet as AssetManager; pub const INITIAL_VALUE: u128 = 1_000_000_000_000_000_000_000u128; benchmarks! { - where_clause { where T: pallet_assets::Config + pallet_asset_manager::Config, ::Balance: From, ::AssetId: From } + where_clause { where T: pallet_assets::Config + pallet_asset_manager::Config, ::AssetId: From } on_initialize {}:{Farming::::on_initialize(T::BlockNumber::from(10u32));} create_farming_pool { @@ -49,7 +52,7 @@ benchmarks! { charge { let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); AssetManager::::do_register_asset(Some(&location), &metadata)?; let ksm_asset_id = CurrencyIdOf::::unique_saturated_from(8u128); @@ -81,7 +84,7 @@ benchmarks! { deposit { let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); AssetManager::::do_register_asset(Some(&location), &metadata)?; let ksm_asset_id = CurrencyIdOf::::unique_saturated_from(8u128); @@ -114,7 +117,7 @@ benchmarks! { withdraw { let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); AssetManager::::do_register_asset(Some(&location), &metadata)?; let ksm_asset_id = CurrencyIdOf::::unique_saturated_from(8u128); @@ -147,7 +150,7 @@ benchmarks! { claim { let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); AssetManager::::do_register_asset(Some(&location), &metadata)?; let caller: T::AccountId = whitelisted_caller(); @@ -182,7 +185,7 @@ benchmarks! { gauge_withdraw { let location = T::Location::default(); - let metadata = >::AssetRegistryMetadata::testing_default(); + let metadata = AssetRegistryMetadata::::testing_default(); AssetManager::::do_register_asset(Some(&location), &metadata)?; let ksm_asset_id = CurrencyIdOf::::unique_saturated_from(8u128); From 6cb8ac7de87abb4b7248d734950cff09e6cf5dbd Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Fri, 14 Jul 2023 15:05:40 -0400 Subject: [PATCH 13/22] update benchmark weights Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/benchmarking.rs | 2 +- pallets/asset-manager/src/lib.rs | 2 +- pallets/asset-manager/src/weights.rs | 318 ++++++++++++---------- 3 files changed, 182 insertions(+), 140 deletions(-) diff --git a/pallets/asset-manager/src/benchmarking.rs b/pallets/asset-manager/src/benchmarking.rs index 7f94a3758..37107fe22 100644 --- a/pallets/asset-manager/src/benchmarking.rs +++ b/pallets/asset-manager/src/benchmarking.rs @@ -178,7 +178,7 @@ benchmarks! { let _ = >::FungibleLedger::deposit_minting( native_asset_id, &caller, - 1_000_000 + 1_000_000_000_000_000_000_000u128 ); }: _(RawOrigin::Signed(caller), vec![].try_into().unwrap(), vec![].try_into().unwrap(), 12, 1_000_000_000_000_000) } diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index e52929df0..f1ba37303 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -723,7 +723,7 @@ pub mod pallet { } #[pallet::call_index(8)] - #[pallet::weight(T::WeightInfo::register_asset())] + #[pallet::weight(T::WeightInfo::permissionless_register_asset())] #[transactional] pub fn permissionless_register_asset( origin: OriginFor, diff --git a/pallets/asset-manager/src/weights.rs b/pallets/asset-manager/src/weights.rs index 9ca76ba71..de5e6aec4 100644 --- a/pallets/asset-manager/src/weights.rs +++ b/pallets/asset-manager/src/weights.rs @@ -17,22 +17,22 @@ //! Autogenerated weights for pallet_asset_manager //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2022-10-08, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("calamari-dev"), DB CACHE: 1024 +//! DATE: 2023-07-14, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("manta-dev"), DB CACHE: 1024 // Executed Command: -// ./target/production/manta +// ./target/release/manta // benchmark // pallet -// --chain=calamari-dev -// --steps=50 -// --repeat=20 +// --chain=manta-dev // --pallet=pallet_asset_manager // --extrinsic=* // --execution=wasm // --wasm-execution=compiled +// --steps=50 +// --repeat=20 // --heap-pages=4096 -// --output=./scripts/benchmarking/frame-weights-output/pallet_asset_manager.rs +// --output=./pallets/asset-manager/src/weights.rs // --template=.github/resources/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -40,8 +40,9 @@ #![allow(unused_imports)] #![allow(clippy::unnecessary_cast)] -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData; +use manta_primitives::constants::RocksDbWeight; /// Weight functions needed for pallet_asset_manager. pub trait WeightInfo { @@ -53,143 +54,184 @@ pub trait WeightInfo { fn set_min_xcm_fee() -> Weight; fn update_outgoing_filtered_assets() -> Weight; fn register_lp_asset() -> Weight; + fn permissionless_register_asset() -> Weight; } /// Weights for pallet_asset_manager using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - // Storage: AssetManager LocationAssetId (r:1 w:1) - // Storage: AssetManager NextAssetId (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - // Storage: AssetManager AssetIdLocation (r:0 w:1) - fn register_asset() -> Weight { - Weight::from_ref_time(43_430_000) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: AssetManager UnitsPerSecond (r:0 w:1) - fn set_units_per_second() -> Weight { - Weight::from_ref_time(56_974_000) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:1) - // Storage: AssetManager LocationAssetId (r:1 w:2) - // Storage: AssetManager AllowedDestParaIds (r:1 w:1) - fn update_asset_location() -> Weight { - Weight::from_ref_time(72_974_000) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - fn update_asset_metadata() -> Weight { - Weight::from_ref_time(73_985_000) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint_asset() -> Weight { - Weight::from_ref_time(85_480_000) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } - // Storage: AssetManager MinXcmFee (r:0 w:1) - fn set_min_xcm_fee() -> Weight { - Weight::from_ref_time(49_509_000) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } - fn update_outgoing_filtered_assets() -> Weight { - Weight::from_ref_time(49_509_000) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - // Storage: AssetManager AssetIdLocation (r:2 w:0) - // Storage: AssetManager AssetIdPairToLp (r:1 w:1) - // Storage: AssetManager NextAssetId (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - // Storage: AssetManager LpToAssetIdPair (r:0 w:1) - fn register_lp_asset() -> Weight { - // Minimum execution time: 546_000 nanoseconds. - Weight::from_ref_time(546_000_000) - .saturating_add(T::DbWeight::get().reads(6)) - .saturating_add(T::DbWeight::get().writes(6)) - } + // Storage: AssetManager LocationAssetId (r:1 w:1) + // Storage: AssetManager NextAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + // Storage: AssetManager AssetIdLocation (r:0 w:1) + fn register_asset() -> Weight { + // Minimum execution time: 48_672 nanoseconds. + Weight::from_ref_time(49_599_000) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(6)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: AssetManager UnitsPerSecond (r:0 w:1) + fn set_units_per_second() -> Weight { + // Minimum execution time: 73_894 nanoseconds. + Weight::from_ref_time(77_860_000) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:1) + // Storage: AssetManager LocationAssetId (r:1 w:2) + // Storage: AssetManager AllowedDestParaIds (r:2 w:2) + fn update_asset_location() -> Weight { + // Minimum execution time: 87_842 nanoseconds. + Weight::from_ref_time(102_703_000) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(5)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn update_asset_metadata() -> Weight { + // Minimum execution time: 86_649 nanoseconds. + Weight::from_ref_time(93_473_000) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint_asset() -> Weight { + // Minimum execution time: 100_617 nanoseconds. + Weight::from_ref_time(106_195_000) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + // Storage: AssetManager MinXcmFee (r:0 w:1) + fn set_min_xcm_fee() -> Weight { + // Minimum execution time: 60_673 nanoseconds. + Weight::from_ref_time(61_758_000) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: AssetManager FilteredOutgoingAssetLocations (r:0 w:1) + fn update_outgoing_filtered_assets() -> Weight { + // Minimum execution time: 52_269 nanoseconds. + Weight::from_ref_time(55_555_000) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: AssetManager AssetIdLocation (r:2 w:0) + // Storage: AssetManager AssetIdPairToLp (r:1 w:1) + // Storage: AssetManager NextAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + // Storage: AssetManager LpToAssetIdPair (r:0 w:1) + fn register_lp_asset() -> Weight { + // Minimum execution time: 54_905 nanoseconds. + Weight::from_ref_time(56_256_000) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(6)) + } + // Storage: System Account (r:1 w:1) + // Storage: AssetManager NextPermissionlessAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn permissionless_register_asset() -> Weight { + // Minimum execution time: 81_474 nanoseconds. + Weight::from_ref_time(83_160_000) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(6)) + } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: AssetManager LocationAssetId (r:1 w:1) - // Storage: AssetManager NextAssetId (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - // Storage: AssetManager AssetIdLocation (r:0 w:1) - fn register_asset() -> Weight { - Weight::from_ref_time(43_430_000) - .saturating_add(RocksDbWeight::get().reads(4_u64)) - .saturating_add(RocksDbWeight::get().writes(6_u64)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: AssetManager UnitsPerSecond (r:0 w:1) - fn set_units_per_second() -> Weight { - Weight::from_ref_time(56_974_000) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:1) - // Storage: AssetManager LocationAssetId (r:1 w:2) - // Storage: AssetManager AllowedDestParaIds (r:1 w:1) - fn update_asset_location() -> Weight { - Weight::from_ref_time(72_974_000) - .saturating_add(RocksDbWeight::get().reads(3_u64)) - .saturating_add(RocksDbWeight::get().writes(4_u64)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:0) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - fn update_asset_metadata() -> Weight { - Weight::from_ref_time(73_985_000) - .saturating_add(RocksDbWeight::get().reads(3_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } - // Storage: AssetManager AssetIdLocation (r:1 w:0) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Account (r:1 w:1) - fn mint_asset() -> Weight { - Weight::from_ref_time(85_480_000) - .saturating_add(RocksDbWeight::get().reads(3_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } - // Storage: AssetManager MinXcmFee (r:0 w:1) - fn set_min_xcm_fee() -> Weight { - Weight::from_ref_time(49_509_000) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - fn update_outgoing_filtered_assets() -> Weight { - Weight::from_ref_time(49_509_000) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - // Storage: AssetManager AssetIdLocation (r:2 w:0) - // Storage: AssetManager AssetIdPairToLp (r:1 w:1) - // Storage: AssetManager NextAssetId (r:1 w:1) - // Storage: Assets Asset (r:1 w:1) - // Storage: Assets Metadata (r:1 w:1) - // Storage: AssetManager AssetIdMetadata (r:0 w:1) - // Storage: AssetManager LpToAssetIdPair (r:0 w:1) - fn register_lp_asset() -> Weight { - // Minimum execution time: 546_000 nanoseconds. - Weight::from_ref_time(546_000_000) - .saturating_add(RocksDbWeight::get().reads(6)) - .saturating_add(RocksDbWeight::get().writes(6)) - } + // Storage: AssetManager LocationAssetId (r:1 w:1) + // Storage: AssetManager NextAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + // Storage: AssetManager AssetIdLocation (r:0 w:1) + fn register_asset() -> Weight { + // Minimum execution time: 48_672 nanoseconds. + Weight::from_ref_time(49_599_000) + .saturating_add(RocksDbWeight::get().reads(4)) + .saturating_add(RocksDbWeight::get().writes(6)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: AssetManager UnitsPerSecond (r:0 w:1) + fn set_units_per_second() -> Weight { + // Minimum execution time: 73_894 nanoseconds. + Weight::from_ref_time(77_860_000) + .saturating_add(RocksDbWeight::get().reads(1)) + .saturating_add(RocksDbWeight::get().writes(1)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:1) + // Storage: AssetManager LocationAssetId (r:1 w:2) + // Storage: AssetManager AllowedDestParaIds (r:2 w:2) + fn update_asset_location() -> Weight { + // Minimum execution time: 87_842 nanoseconds. + Weight::from_ref_time(102_703_000) + .saturating_add(RocksDbWeight::get().reads(4)) + .saturating_add(RocksDbWeight::get().writes(5)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:0) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn update_asset_metadata() -> Weight { + // Minimum execution time: 86_649 nanoseconds. + Weight::from_ref_time(93_473_000) + .saturating_add(RocksDbWeight::get().reads(3)) + .saturating_add(RocksDbWeight::get().writes(2)) + } + // Storage: AssetManager AssetIdLocation (r:1 w:0) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + fn mint_asset() -> Weight { + // Minimum execution time: 100_617 nanoseconds. + Weight::from_ref_time(106_195_000) + .saturating_add(RocksDbWeight::get().reads(3)) + .saturating_add(RocksDbWeight::get().writes(2)) + } + // Storage: AssetManager MinXcmFee (r:0 w:1) + fn set_min_xcm_fee() -> Weight { + // Minimum execution time: 60_673 nanoseconds. + Weight::from_ref_time(61_758_000) + .saturating_add(RocksDbWeight::get().writes(1)) + } + // Storage: AssetManager FilteredOutgoingAssetLocations (r:0 w:1) + fn update_outgoing_filtered_assets() -> Weight { + // Minimum execution time: 52_269 nanoseconds. + Weight::from_ref_time(55_555_000) + .saturating_add(RocksDbWeight::get().writes(1)) + } + // Storage: AssetManager AssetIdLocation (r:2 w:0) + // Storage: AssetManager AssetIdPairToLp (r:1 w:1) + // Storage: AssetManager NextAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + // Storage: AssetManager LpToAssetIdPair (r:0 w:1) + fn register_lp_asset() -> Weight { + // Minimum execution time: 54_905 nanoseconds. + Weight::from_ref_time(56_256_000) + .saturating_add(RocksDbWeight::get().reads(6)) + .saturating_add(RocksDbWeight::get().writes(6)) + } + // Storage: System Account (r:1 w:1) + // Storage: AssetManager NextPermissionlessAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn permissionless_register_asset() -> Weight { + // Minimum execution time: 81_474 nanoseconds. + Weight::from_ref_time(83_160_000) + .saturating_add(RocksDbWeight::get().reads(5)) + .saturating_add(RocksDbWeight::get().writes(6)) + } } From a3523feb59d8006183666bd9509302fe4ec15e70 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Fri, 14 Jul 2023 15:12:21 -0400 Subject: [PATCH 14/22] weights in runtimes Signed-off-by: Charles Ferrell --- .../src/weights/pallet_asset_manager.rs | 25 +++++++++++++++++++ .../manta/src/weights/pallet_asset_manager.rs | 25 +++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/runtime/calamari/src/weights/pallet_asset_manager.rs b/runtime/calamari/src/weights/pallet_asset_manager.rs index f7ce7be66..7a974d5ac 100644 --- a/runtime/calamari/src/weights/pallet_asset_manager.rs +++ b/runtime/calamari/src/weights/pallet_asset_manager.rs @@ -54,6 +54,7 @@ pub trait WeightInfo { fn set_min_xcm_fee() -> Weight; fn update_outgoing_filtered_assets() -> Weight; fn register_lp_asset() -> Weight; + fn permissionless_register_asset() -> Weight; } /// Weights for pallet_asset_manager using the Substrate node and recommended hardware. @@ -132,6 +133,18 @@ impl pallet_asset_manager::WeightInfo for SubstrateWeig .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(6)) } + // Storage: System Account (r:1 w:1) + // Storage: AssetManager NextPermissionlessAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn permissionless_register_asset() -> Weight { + // Minimum execution time: 81_474 nanoseconds. + Weight::from_ref_time(83_160_000) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(6)) + } } // For backwards compatibility and tests @@ -209,4 +222,16 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(6)) .saturating_add(RocksDbWeight::get().writes(6)) } + // Storage: System Account (r:1 w:1) + // Storage: AssetManager NextPermissionlessAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn permissionless_register_asset() -> Weight { + // Minimum execution time: 81_474 nanoseconds. + Weight::from_ref_time(83_160_000) + .saturating_add(RocksDbWeight::get().reads(5)) + .saturating_add(RocksDbWeight::get().writes(6)) + } } diff --git a/runtime/manta/src/weights/pallet_asset_manager.rs b/runtime/manta/src/weights/pallet_asset_manager.rs index a6ca826b3..efae6db09 100644 --- a/runtime/manta/src/weights/pallet_asset_manager.rs +++ b/runtime/manta/src/weights/pallet_asset_manager.rs @@ -54,6 +54,7 @@ pub trait WeightInfo { fn set_min_xcm_fee() -> Weight; fn update_outgoing_filtered_assets() -> Weight; fn register_lp_asset() -> Weight; + fn permissionless_register_asset() -> Weight; } /// Weights for pallet_asset_manager using the Substrate node and recommended hardware. @@ -132,6 +133,18 @@ impl pallet_asset_manager::WeightInfo for SubstrateWeig .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(6)) } + // Storage: System Account (r:1 w:1) + // Storage: AssetManager NextPermissionlessAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn permissionless_register_asset() -> Weight { + // Minimum execution time: 81_474 nanoseconds. + Weight::from_ref_time(83_160_000) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(6)) + } } // For backwards compatibility and tests @@ -209,4 +222,16 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(6)) .saturating_add(RocksDbWeight::get().writes(6)) } + // Storage: System Account (r:1 w:1) + // Storage: AssetManager NextPermissionlessAssetId (r:1 w:1) + // Storage: Assets Asset (r:1 w:1) + // Storage: Assets Metadata (r:1 w:1) + // Storage: Assets Account (r:1 w:1) + // Storage: AssetManager AssetIdMetadata (r:0 w:1) + fn permissionless_register_asset() -> Weight { + // Minimum execution time: 81_474 nanoseconds. + Weight::from_ref_time(83_160_000) + .saturating_add(RocksDbWeight::get().reads(5)) + .saturating_add(RocksDbWeight::get().writes(6)) + } } From 8c02acd848b4c7d0620ffb2f3d875239e9618524 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Fri, 14 Jul 2023 19:45:36 -0400 Subject: [PATCH 15/22] add counter tests Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/lib.rs | 13 ++++++------ pallets/asset-manager/src/tests.rs | 34 +++++++++++++++++++++++++++--- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/pallets/asset-manager/src/lib.rs b/pallets/asset-manager/src/lib.rs index f1ba37303..d9edcd40d 100644 --- a/pallets/asset-manager/src/lib.rs +++ b/pallets/asset-manager/src/lib.rs @@ -225,7 +225,7 @@ pub mod pallet { let metadata = >::NativeAssetMetadata::get(); let location = >::NativeAssetLocation::get(); AssetIdLocation::::insert(asset_id, &location); - AssetIdMetadata::::insert(asset_id, &metadata); + AssetIdMetadata::::insert(asset_id, metadata); LocationAssetId::::insert(&location, asset_id); } } @@ -617,7 +617,7 @@ pub mod pallet { >::FungibleLedger::deposit_minting_with_check( asset_id, &beneficiary, - amount.clone(), + amount, true, ) .map_err(|_| Error::::MintError)?; @@ -773,7 +773,7 @@ pub mod pallet { .map_err(|_| Error::::ErrorCreatingAsset)?; let register_metadata = AssetRegistryMetadata:: { - metadata: metadata.clone(), + metadata, min_balance, is_sufficient: true, }; @@ -813,7 +813,7 @@ pub mod pallet { >::AssetRegistry::create_asset( asset_id, metadata.clone().into(), - metadata.min_balance().clone(), + *metadata.min_balance(), metadata.is_sufficient(), ) .map_err(|_| Error::::ErrorCreatingAsset)?; @@ -827,7 +827,7 @@ pub mod pallet { /// Returns and increments the [`NextAssetId`] by one. Fails if it hits the upper limit of `PermissionlessStartId` #[inline] - fn next_asset_id_and_increment() -> Result { + pub(super) fn next_asset_id_and_increment() -> Result { NextAssetId::::try_mutate(|current| { if *current >= T::PermissionlessStartId::get() { Err(Error::::AssetIdOverflow.into()) @@ -843,7 +843,8 @@ pub mod pallet { /// Returns and increments the [`NextPermssionlessAssetId`] by one. #[inline] - fn next_permissionless_asset_id_and_increment() -> Result { + pub(super) fn next_permissionless_asset_id_and_increment( + ) -> Result { NextPermissionlessAssetId::::try_mutate(|current| { if current.is_zero() { let id = T::PermissionlessStartId::get(); diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index ebe260a43..9e4b40e87 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -17,10 +17,9 @@ //! unit tests for asset-manager use crate::{ - self as asset_manager, AssetIdLocation, AssetIdMetadata, AssetIdPairToLp, Error, - LocationAssetId, LpToAssetIdPair, UnitsPerSecond, + mock::*, AssetIdLocation, AssetIdMetadata, AssetIdPairToLp, Error, LocationAssetId, + LpToAssetIdPair, NextAssetId, UnitsPerSecond, }; -use asset_manager::mock::*; use frame_support::{ assert_noop, assert_ok, traits::{fungibles::InspectMetadata, Contains}, @@ -31,6 +30,7 @@ use manta_primitives::{ types::Balance, }; use orml_traits::GetByKey; +use sp_core::Get; use sp_runtime::{traits::BadOrigin, ArithmeticError}; use xcm::{latest::prelude::*, VersionedMultiLocation}; @@ -756,3 +756,31 @@ fn permissionless_register_asset_works() { )); }); } + +#[test] +fn counters_test() { + new_test_ext().execute_with(|| { + let last_id: Balance = ::PermissionlessStartId::get(); + let last_id_minus_one = last_id - 1; + let last_id_plus_one = last_id + 1; + NextAssetId::::put(last_id_minus_one); + + assert_eq!( + AssetManager::next_asset_id_and_increment().unwrap(), + last_id_minus_one + ); + assert_noop!( + AssetManager::next_asset_id_and_increment(), + Error::::AssetIdOverflow + ); + + assert_eq!( + AssetManager::next_permissionless_asset_id_and_increment().unwrap(), + last_id + ); + assert_eq!( + AssetManager::next_permissionless_asset_id_and_increment().unwrap(), + last_id_plus_one + ); + }); +} From a8f3883fa956a53f3b8b189618da762c6517bc95 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Fri, 14 Jul 2023 20:07:30 -0400 Subject: [PATCH 16/22] add more tests Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/tests.rs | 32 +++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index 9e4b40e87..bb2ee0df6 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -719,21 +719,38 @@ fn permissionless_edge_cases() { ), Error::::TotalSupplyTooLow, ); + + // really small total supply is one + let asset_id: u128 = ::PermissionlessStartId::get(); + assert_ok!(AssetManager::permissionless_register_asset( + RuntimeOrigin::signed(ALICE), + "dog token".as_bytes().to_vec().try_into().unwrap(), + "dog".as_bytes().to_vec().try_into().unwrap(), + 1, + 1_000, + )); + + let metadata = AssetIdMetadata::::get(asset_id).unwrap(); + assert_eq!(metadata.min_balance, 1); }); } #[test] fn permissionless_register_asset_works() { new_test_ext().execute_with(|| { + let amount = 1_000_000; + let registry_cost: Balance = + ::PermissionlessAssetRegistryCost::get(); let native_asset_id = >::NativeAssetId::get(); assert_ok!( >::FungibleLedger::deposit_minting( native_asset_id, &ALICE, - 1_000_000 + amount, ) ); + let asset_id = ::PermissionlessStartId::get(); assert_ok!(AssetManager::permissionless_register_asset( RuntimeOrigin::signed(ALICE), "dog token".as_bytes().to_vec().try_into().unwrap(), @@ -741,10 +758,19 @@ fn permissionless_register_asset_works() { 12, 1_000_000_000_000_000, )); - let asset_id = AssetManager::next_permissionless_asset_id(); // asset created gives alice the token - assert_eq!(Assets::balance(asset_id - 1, &ALICE), 1_000_000_000_000_000); + assert_eq!(Assets::balance(asset_id, &ALICE), 1_000_000_000_000_000); + // cost native token + assert_eq!(Balances::free_balance(&ALICE), amount - registry_cost); + + let metadata = AssetIdMetadata::::get(asset_id).unwrap(); + assert_eq!(metadata.is_sufficient, true); + assert_eq!(metadata.min_balance, 100_000); + assert_eq!(metadata.metadata.is_frozen, false); + assert_eq!(metadata.metadata.decimals, 12); + assert_eq!(metadata.metadata.name, "dog token".as_bytes().to_vec()); + assert_eq!(metadata.metadata.symbol, "dog".as_bytes().to_vec()); // Max balance works assert_ok!(AssetManager::permissionless_register_asset( From 65cc718643e1b841d60b081a39d88ea7138b80ee Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Fri, 14 Jul 2023 21:10:16 -0400 Subject: [PATCH 17/22] fix clippy Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/tests.rs | 4 ++-- pallets/farming/src/benchmarking.rs | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index bb2ee0df6..d91b00948 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -765,9 +765,9 @@ fn permissionless_register_asset_works() { assert_eq!(Balances::free_balance(&ALICE), amount - registry_cost); let metadata = AssetIdMetadata::::get(asset_id).unwrap(); - assert_eq!(metadata.is_sufficient, true); + assert!(metadata.is_sufficient); assert_eq!(metadata.min_balance, 100_000); - assert_eq!(metadata.metadata.is_frozen, false); + assert!(!metadata.metadata.is_frozen); assert_eq!(metadata.metadata.decimals, 12); assert_eq!(metadata.metadata.name, "dog token".as_bytes().to_vec()); assert_eq!(metadata.metadata.symbol, "dog".as_bytes().to_vec()); diff --git a/pallets/farming/src/benchmarking.rs b/pallets/farming/src/benchmarking.rs index f9d1b8dda..f8bada838 100644 --- a/pallets/farming/src/benchmarking.rs +++ b/pallets/farming/src/benchmarking.rs @@ -77,7 +77,7 @@ benchmarks! { let _ = >::FungibleLedger::deposit_minting( 8.into(), &caller, - INITIAL_VALUE.try_into().unwrap(), + INITIAL_VALUE, ); // assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards)); }: _(RawOrigin::Signed(caller.clone()), 0, charge_rewards) @@ -110,7 +110,7 @@ benchmarks! { let _ = >::FungibleLedger::deposit_minting( 8.into(), &caller, - INITIAL_VALUE.try_into().unwrap(), + INITIAL_VALUE, ); assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards)); }: _(RawOrigin::Signed(caller.clone()), 0, token_amount, None) @@ -141,7 +141,7 @@ benchmarks! { let _ = >::FungibleLedger::deposit_minting( 8.into(), &caller, - INITIAL_VALUE.try_into().unwrap(), + INITIAL_VALUE, ); let charge_rewards = vec![(ksm_asset_id,BalanceOf::::unique_saturated_from(300000u128))]; assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards)); @@ -174,7 +174,7 @@ benchmarks! { let _ = >::FungibleLedger::deposit_minting( 8.into(), &caller, - INITIAL_VALUE.try_into().unwrap(), + INITIAL_VALUE, ); let charge_rewards = vec![(ksm_asset_id,BalanceOf::::unique_saturated_from(300000u128))]; assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards)); @@ -209,7 +209,7 @@ benchmarks! { let _ = >::FungibleLedger::deposit_minting( 8.into(), &caller, - INITIAL_VALUE.try_into().unwrap(), + INITIAL_VALUE, ); let charge_rewards = vec![(ksm_asset_id,BalanceOf::::unique_saturated_from(300000u128))]; assert_ok!(Farming::::charge(RawOrigin::Signed(caller.clone()).into(), 0, charge_rewards)); From 3619a9ae2b916d17c7b28af14895c10297c1b9e0 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Fri, 14 Jul 2023 21:37:34 -0400 Subject: [PATCH 18/22] add integration test Signed-off-by: Charles Ferrell --- .../src/integrations_mock/mod.rs | 4 +- .../src/integrations_mock/test_common.rs | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/runtime/integration-tests/src/integrations_mock/mod.rs b/runtime/integration-tests/src/integrations_mock/mod.rs index 5d1c71a23..972850585 100644 --- a/runtime/integration-tests/src/integrations_mock/mod.rs +++ b/runtime/integration-tests/src/integrations_mock/mod.rs @@ -43,7 +43,7 @@ cfg_if::cfg_if! { InflationInfo, LaunchPeriod, LeaveDelayRounds, NativeTokenExistentialDeposit, RuntimeOrigin, ParachainStaking, PolkadotXcm, Range, Runtime, Scheduler, Session, System, TechnicalCommittee, Timestamp, TransactionPause, TransactionPayment, Treasury, - VotingPeriod, Preimage, NonPausablePallets, AllPalletsWithSystem + VotingPeriod, Preimage, NonPausablePallets, AllPalletsWithSystem, MantaPay, }; type RuntimeAssetConfig = calamari_runtime::assets_config::CalamariAssetConfig; type RuntimeConcreteFungibleLedger = @@ -61,7 +61,7 @@ cfg_if::cfg_if! { DefaultBlocksPerRound, RuntimeEvent, InflationInfo, LeaveDelayRounds, NativeTokenExistentialDeposit, RuntimeOrigin, ParachainStaking, PolkadotXcm, Range, Runtime, Session, System, Timestamp, TransactionPause, TransactionPayment, Treasury, Utility, TechnicalCommittee, Council, EnactmentPeriod, VotingPeriod, - LaunchPeriod, Preimage, Democracy, Scheduler, Aura, Multisig, ParachainSystem, ParachainInfo, + LaunchPeriod, Preimage, Democracy, Scheduler, Aura, Multisig, ParachainSystem, ParachainInfo, MantaPay, XTokens, DmpQueue, CumulusXcm, XcmpQueue, AuraAuthorFilter, NonPausablePallets, AllPalletsWithSystem }; type RuntimeAssetConfig = manta_runtime::assets_config::MantaAssetConfig; diff --git a/runtime/integration-tests/src/integrations_mock/test_common.rs b/runtime/integration-tests/src/integrations_mock/test_common.rs index e801ffa68..ad2fb31bf 100644 --- a/runtime/integration-tests/src/integrations_mock/test_common.rs +++ b/runtime/integration-tests/src/integrations_mock/test_common.rs @@ -39,6 +39,7 @@ use manta_primitives::{ constants::time::{DAYS, HOURS}, types::{AccountId, Balance, CalamariAssetId}, }; +use manta_support::manta_pay::{asset_value_encode, field_from_id, Asset}; use session_key_primitives::util::unchecked_account_id; use xcm::{ opaque::latest::{ @@ -399,6 +400,55 @@ fn balances_operations_should_work() { }); } +#[test] +fn asset_manager_permissionless_manta_pay() { + ExtBuilder::default() + .with_balances(vec![(ALICE.clone(), INITIAL_BALANCE)]) + .build() + .execute_with(|| { + let asset_id = ::PermissionlessStartId::get(); + let init_supply = 1_000_000_000_000_000_000_u128; + assert_ok!(AssetManager::permissionless_register_asset( + RuntimeOrigin::signed(ALICE.clone()), + "dog token".as_bytes().to_vec().try_into().unwrap(), + "dog".as_bytes().to_vec().try_into().unwrap(), + 12, + init_supply, + )); + // asset created gives alice the token + assert_eq!(Assets::balance(asset_id, ALICE.clone()), init_supply); + + let amount = 1_000_000_000_000; + let dog_token = Asset { + id: field_from_id(asset_id), + value: asset_value_encode(amount), + }; + let under_ed = Asset { + id: field_from_id(asset_id), + value: asset_value_encode(1), + }; + + assert_noop!( + MantaPay::public_transfer( + RuntimeOrigin::signed(ALICE.clone()), + under_ed, + BOB.clone(), + ), + pallet_manta_pay::Error::::PublicUpdateInvalidTransfer + ); + assert_ok!(MantaPay::public_transfer( + RuntimeOrigin::signed(ALICE.clone()), + dog_token, + BOB.clone(), + )); + + assert_eq!( + Assets::balance(asset_id, ALICE.clone()), + init_supply - amount + ); + }) +} + #[test] fn root_can_change_default_xcm_vers() { ExtBuilder::default().build().execute_with(|| { From cb065630464e6a12709dfa3bec89d0e7c3d7c100 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Tue, 18 Jul 2023 18:28:58 -0400 Subject: [PATCH 19/22] use number instead of max Signed-off-by: Charles Ferrell --- pallets/asset-manager/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/asset-manager/src/tests.rs b/pallets/asset-manager/src/tests.rs index d91b00948..901086c41 100644 --- a/pallets/asset-manager/src/tests.rs +++ b/pallets/asset-manager/src/tests.rs @@ -703,7 +703,7 @@ fn permissionless_edge_cases() { "dog token".as_bytes().to_vec().try_into().unwrap(), "dog".as_bytes().to_vec().try_into().unwrap(), u8::MAX, - u128::MAX, + 1_000_000_000_000_000_000_u128, ), ArithmeticError::Overflow ); From ed1abefbcd7a6e471b7dec070039e23a46fe9457 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Wed, 19 Jul 2023 11:13:30 -0400 Subject: [PATCH 20/22] unify string limit param Signed-off-by: Charles Ferrell --- runtime/calamari/src/assets_config.rs | 6 ++++-- runtime/manta/src/assets_config.rs | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/runtime/calamari/src/assets_config.rs b/runtime/calamari/src/assets_config.rs index 0a86c5dc3..37dacd9f2 100644 --- a/runtime/calamari/src/assets_config.rs +++ b/runtime/calamari/src/assets_config.rs @@ -51,6 +51,8 @@ parameter_types! { pub const MetadataDepositPerByte: Balance = 0; } +type StringLimit = ConstU32<50>; + impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; @@ -62,7 +64,7 @@ impl pallet_assets::Config for Runtime { type MetadataDepositBase = MetadataDepositBase; type MetadataDepositPerByte = MetadataDepositPerByte; type ApprovalDeposit = ApprovalDeposit; - type StringLimit = ConstU32<50>; + type StringLimit = StringLimit; type Freezer = (); type Extra = (); type WeightInfo = weights::pallet_assets::SubstrateWeight; @@ -171,7 +173,7 @@ impl AssetConfig for CalamariAssetConfig { impl pallet_asset_manager::Config for Runtime { type PermissionlessStartId = ConstU128<1_000_000_000>; - type TokenNameMaxLen = ConstU32<200>; + type TokenNameMaxLen = StringLimit; type TokenSymbolMaxLen = ConstU32<10>; type PermissionlessAssetRegistryCost = ConstU128<{ 1_000 * KMA }>; type RuntimeEvent = RuntimeEvent; diff --git a/runtime/manta/src/assets_config.rs b/runtime/manta/src/assets_config.rs index 342eeb1d4..a2498b943 100644 --- a/runtime/manta/src/assets_config.rs +++ b/runtime/manta/src/assets_config.rs @@ -48,6 +48,8 @@ parameter_types! { pub const MetadataDepositPerByte: Balance = 0; } +type StringLimit = ConstU32<50>; + impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; @@ -59,7 +61,7 @@ impl pallet_assets::Config for Runtime { type MetadataDepositBase = MetadataDepositBase; type MetadataDepositPerByte = MetadataDepositPerByte; type ApprovalDeposit = ApprovalDeposit; - type StringLimit = ConstU32<50>; + type StringLimit = StringLimit; type Freezer = (); type Extra = (); type WeightInfo = weights::pallet_assets::SubstrateWeight; @@ -168,7 +170,7 @@ impl AssetConfig for MantaAssetConfig { impl pallet_asset_manager::Config for Runtime { type PermissionlessStartId = ConstU128<1_000_000_000>; - type TokenNameMaxLen = ConstU32<200>; + type TokenNameMaxLen = StringLimit; type TokenSymbolMaxLen = ConstU32<10>; type PermissionlessAssetRegistryCost = ConstU128<{ 50 * MANTA }>; type RuntimeEvent = RuntimeEvent; From 60c51d41c1c5f7a14d3ee86ee1650974c2073728 Mon Sep 17 00:00:00 2001 From: Charles Ferrell Date: Wed, 19 Jul 2023 23:04:48 -0400 Subject: [PATCH 21/22] add tx diff Signed-off-by: Charles Ferrell --- runtime/calamari/src/diff_tx_fees.rs | 19 ++++++++++++++++++- runtime/calamari/tx-fees-data/README.md | 3 +-- runtime/manta/src/diff_tx_fees.rs | 19 ++++++++++++++++++- runtime/manta/tx-fees-data/README.md | 3 +-- 4 files changed, 38 insertions(+), 6 deletions(-) diff --git a/runtime/calamari/src/diff_tx_fees.rs b/runtime/calamari/src/diff_tx_fees.rs index 73a02a05d..dce808f50 100644 --- a/runtime/calamari/src/diff_tx_fees.rs +++ b/runtime/calamari/src/diff_tx_fees.rs @@ -1177,7 +1177,7 @@ fn calculate_all_current_extrinsic_tx_fee() -> ( { assert_eq!( crate::RuntimeCall::get_call_names("AssetManager").len(), - 8, + 9, "Please update new extrinsic here." ); // register_asset @@ -1291,6 +1291,23 @@ fn calculate_all_current_extrinsic_tx_fee() -> ( dispatch_info, call_len, )); + + // permissionless_register_asset + let call = crate::RuntimeCall::AssetManager( + pallet_asset_manager::Call::permissionless_register_asset { + name: vec![].try_into().unwrap(), + symbol: vec![].try_into().unwrap(), + decimals: 12, + total_supply: 1_000_000_000_000_000, + }, + ); + let (dispatch_info, call_len) = get_call_details(&call); + calamari_runtime_calls.push(( + "pallet_asset_manager", + "permissionless_register_asset", + dispatch_info, + call_len, + )); } // pallet_assets diff --git a/runtime/calamari/tx-fees-data/README.md b/runtime/calamari/tx-fees-data/README.md index 50115519a..0768f592a 100644 --- a/runtime/calamari/tx-fees-data/README.md +++ b/runtime/calamari/tx-fees-data/README.md @@ -8,9 +8,8 @@ Run the command. ```sh -cargo t generate_all_current_extrinsics_tx_fee_to_csv +cargo t generate_all_current_extrinsics_tx_fee_to_csv -- --ignored ``` -> Before you run this test case, please disable this line of code: `#[ignore]`. It will generate a csv file located at `tx-fees-data/{crate-version}-tx-fees.csv`. diff --git a/runtime/manta/src/diff_tx_fees.rs b/runtime/manta/src/diff_tx_fees.rs index 9f0312458..1b428c29e 100644 --- a/runtime/manta/src/diff_tx_fees.rs +++ b/runtime/manta/src/diff_tx_fees.rs @@ -1164,7 +1164,7 @@ fn calculate_all_current_extrinsic_tx_fee() -> ( { assert_eq!( crate::RuntimeCall::get_call_names("AssetManager").len(), - 8, + 9, "Please update new extrinsic here." ); // register_asset @@ -1278,6 +1278,23 @@ fn calculate_all_current_extrinsic_tx_fee() -> ( dispatch_info, call_len, )); + + // permissionless_register_asset + let call = crate::RuntimeCall::AssetManager( + pallet_asset_manager::Call::permissionless_register_asset { + name: vec![].try_into().unwrap(), + symbol: vec![].try_into().unwrap(), + decimals: 12, + total_supply: 1_000_000_000_000_000, + }, + ); + let (dispatch_info, call_len) = get_call_details(&call); + calamari_runtime_calls.push(( + "pallet_asset_manager", + "permissionless_register_asset", + dispatch_info, + call_len, + )); } // pallet_assets diff --git a/runtime/manta/tx-fees-data/README.md b/runtime/manta/tx-fees-data/README.md index 50115519a..0768f592a 100644 --- a/runtime/manta/tx-fees-data/README.md +++ b/runtime/manta/tx-fees-data/README.md @@ -8,9 +8,8 @@ Run the command. ```sh -cargo t generate_all_current_extrinsics_tx_fee_to_csv +cargo t generate_all_current_extrinsics_tx_fee_to_csv -- --ignored ``` -> Before you run this test case, please disable this line of code: `#[ignore]`. It will generate a csv file located at `tx-fees-data/{crate-version}-tx-fees.csv`. From d687f5b702f44932b2ca4cc9675b531a1c38c633 Mon Sep 17 00:00:00 2001 From: Dengjianping Date: Thu, 20 Jul 2023 15:16:44 +0800 Subject: [PATCH 22/22] Do not panic when diff new extrinsic tx fee Signed-off-by: Dengjianping --- runtime/calamari/src/diff_tx_fees.rs | 2 +- runtime/manta/src/diff_tx_fees.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/calamari/src/diff_tx_fees.rs b/runtime/calamari/src/diff_tx_fees.rs index dce808f50..ecfd8794d 100644 --- a/runtime/calamari/src/diff_tx_fees.rs +++ b/runtime/calamari/src/diff_tx_fees.rs @@ -132,7 +132,7 @@ fn diff_tx_fees() { let _multiplier = found.fee_multiplier; assert!(fluctuation <= TX_FEE_FLUCTUATION, "The tx fee fluctuation for the extrinsic {extrinsic_name} is {fluctuation:?}, bigger than {TX_FEE_FLUCTUATION:?} with multiplier {_multiplier}."); } - None => panic!("The extrinsic {pallet_name}.{extrinsic_name} is missing from current tx fees list, please add it to latest csv file."), + None => println!("The extrinsic {pallet_name}.{extrinsic_name} is missing from current tx fees list, please add it to latest csv file."), } } }); diff --git a/runtime/manta/src/diff_tx_fees.rs b/runtime/manta/src/diff_tx_fees.rs index 1b428c29e..dcf596c0a 100644 --- a/runtime/manta/src/diff_tx_fees.rs +++ b/runtime/manta/src/diff_tx_fees.rs @@ -132,7 +132,7 @@ fn diff_tx_fees() { let _multiplier = found.fee_multiplier; assert!(fluctuation <= TX_FEE_FLUCTUATION, "The tx fee fluctuation for the extrinsic {extrinsic_name} is {fluctuation:?}, bigger than {TX_FEE_FLUCTUATION:?} with multiplier {_multiplier}."); } - None => panic!("The extrinsic {pallet_name}.{extrinsic_name} is missing from current tx fees list, please add it to latest csv file."), + None => println!("The extrinsic {pallet_name}.{extrinsic_name} is missing from current tx fees list, please add it to latest csv file."), } } });