From 48fed67879d8a90ed29d21f463fc7a4e6c862a5e Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 15 Aug 2023 15:51:06 +0200 Subject: [PATCH 01/93] asset-reg: wip merge metadata with details and make name optional --- pallets/asset-registry/src/lib.rs | 182 +++++++++++++++++----------- pallets/asset-registry/src/types.rs | 10 +- traits/src/registry.rs | 4 +- 3 files changed, 123 insertions(+), 73 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 464e9b7b2..e250be203 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -33,7 +33,8 @@ mod mock; mod tests; mod benchmarking; -pub mod migration; +//TODO +//pub mod migration; mod types; pub mod weights; @@ -162,16 +163,10 @@ pub mod pallet { pub type LocationAssets = StorageMap<_, Blake2_128Concat, T::AssetNativeLocation, T::AssetId, OptionQuery>; - #[pallet::storage] - #[pallet::getter(fn asset_metadata)] - /// Metadata of an asset. - pub type AssetMetadataMap = - StorageMap<_, Twox64Concat, T::AssetId, AssetMetadata>, OptionQuery>; - #[allow(clippy::type_complexity)] #[pallet::genesis_config] pub struct GenesisConfig { - pub registered_assets: Vec<(Vec, T::Balance, Option)>, + pub registered_assets: Vec<(Option>, T::Balance, Option)>, pub native_asset_name: Vec, pub native_existential_deposit: T::Balance, } @@ -197,20 +192,27 @@ pub mod pallet { AssetIds::::insert(&native_asset_name, T::NativeAssetId::get()); let details = AssetDetails { - name: native_asset_name, + name: Some(native_asset_name), asset_type: AssetType::Token, existential_deposit: self.native_existential_deposit, xcm_rate_limit: None, + metadata: None, }; Assets::::insert(T::NativeAssetId::get(), details); self.registered_assets.iter().for_each(|(name, ed, id)| { - let bounded_name = Pallet::::to_bounded_name(name.to_vec()) - .map_err(|_| panic!("Invalid asset name!")) - .unwrap(); - let _ = Pallet::::register_asset(bounded_name, AssetType::Token, *ed, *id, None) + let bounded_name = if let Some(name) = name { + Some( + Pallet::::to_bounded_name(name.to_vec()) + .map_err(|_| panic!("Invalid asset name!")) + .unwrap(), + ) + } else { + None + }; + let _ = Pallet::::register_asset(bounded_name, AssetType::Token, *ed, *id, None, None) .map_err(|_| panic!("Failed to register asset")); }) } @@ -222,14 +224,14 @@ pub mod pallet { /// Asset was registered. Registered { asset_id: T::AssetId, - asset_name: BoundedVec, + asset_name: Option>, asset_type: AssetType, }, /// Asset was updated. Updated { asset_id: T::AssetId, - asset_name: BoundedVec, + asset_name: Option>, asset_type: AssetType, existential_deposit: T::Balance, xcm_rate_limit: Option, @@ -265,7 +267,7 @@ pub mod pallet { #[pallet::weight(::WeightInfo::register())] pub fn register( origin: OriginFor, - name: Vec, + name: Option>, asset_type: AssetType, existential_deposit: T::Balance, asset_id: Option, @@ -275,30 +277,43 @@ pub mod pallet { ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; - let bounded_name = Self::to_bounded_name(name)?; - - ensure!( - Self::asset_ids(&bounded_name).is_none(), - Error::::AssetAlreadyRegistered - ); + let bounded_name = if let Some(n) = name { + let bounded_name = Self::to_bounded_name(n)?; + ensure!( + Self::asset_ids(&bounded_name).is_none(), + Error::::AssetAlreadyRegistered + ); - let asset_id = - Self::register_asset(bounded_name, asset_type, existential_deposit, asset_id, xcm_rate_limit)?; + Some(bounded_name) + } else { + None + }; - if let Some(meta) = metadata { - let symbol = Self::to_bounded_name(meta.symbol)?; - AssetMetadataMap::::insert( - asset_id, - AssetMetadata { + let meta = match metadata { + Some(m) => { + let symbol = Self::to_bounded_name(m.symbol)?; + Some(AssetMetadata { symbol: symbol.clone(), - decimals: meta.decimals, - }, - ); + decimals: m.decimals, + }) + } + None => None, + }; + let asset_id = Self::register_asset( + bounded_name, + asset_type, + existential_deposit, + asset_id, + xcm_rate_limit, + meta.clone(), + )?; + + if let Some(m) = meta { Self::deposit_event(Event::MetadataSet { asset_id, - symbol, - decimals: meta.decimals, + symbol: m.symbol, + decimals: m.decimals, }); } @@ -332,7 +347,7 @@ pub mod pallet { pub fn update( origin: OriginFor, asset_id: T::AssetId, - name: Vec, + name: Option>, asset_type: AssetType, existential_deposit: Option, xcm_rate_limit: Option, @@ -342,28 +357,34 @@ pub mod pallet { Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { let mut detail = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; - let bounded_name = Self::to_bounded_name(name)?; - - if bounded_name != detail.name { - // Make sure that there is no such name already registered - ensure!( - Self::asset_ids(&bounded_name).is_none(), - Error::::AssetAlreadyRegistered - ); - - // update also name map - remove old one first - AssetIds::::remove(&detail.name); - AssetIds::::insert(&bounded_name, asset_id); - } + let new_bounded_name = if let Some(name) = name { + let new_bounded_name = Self::to_bounded_name(name)?; + + if Some(new_bounded_name.clone()) != detail.name { + ensure!( + Self::asset_ids(&new_bounded_name).is_none(), + Error::::AssetAlreadyRegistered + ); + // update also name map - remove old one first + if let Some(old_name) = &detail.name { + AssetIds::::remove(old_name); + } + AssetIds::::insert(&new_bounded_name, asset_id); + } + + Some(new_bounded_name) + } else { + None + }; - detail.name = bounded_name.clone(); + detail.name = new_bounded_name.clone(); detail.asset_type = asset_type; detail.existential_deposit = existential_deposit.unwrap_or(detail.existential_deposit); detail.xcm_rate_limit = xcm_rate_limit; Self::deposit_event(Event::Updated { asset_id, - asset_name: bounded_name, + asset_name: new_bounded_name, asset_type, existential_deposit: detail.existential_deposit, xcm_rate_limit: detail.xcm_rate_limit, @@ -390,24 +411,25 @@ pub mod pallet { ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; - ensure!(Self::assets(asset_id).is_some(), Error::::AssetNotFound); - - let b_symbol = Self::to_bounded_name(symbol)?; + Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { + let mut detail = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; + let b_symbol = Self::to_bounded_name(symbol)?; - let metadata = AssetMetadata::> { - symbol: b_symbol.clone(), - decimals, - }; + let metadata = AssetMetadata::> { + symbol: b_symbol.clone(), + decimals, + }; - AssetMetadataMap::::insert(asset_id, metadata); + detail.metadata = Some(metadata); - Self::deposit_event(Event::MetadataSet { - asset_id, - symbol: b_symbol, - decimals, - }); + Self::deposit_event(Event::MetadataSet { + asset_id, + symbol: b_symbol, + decimals, + }); - Ok(()) + Ok(()) + }) } /// Set asset native location. @@ -460,11 +482,12 @@ impl Pallet { /// /// Does not perform any check whether an asset for given name already exists. This has to be prior to calling this function. pub fn register_asset( - name: BoundedVec, + name: Option>, asset_type: AssetType, existential_deposit: T::Balance, selected_asset_id: Option, xcm_rate_limit: Option, + metadata: Option>>, ) -> Result { let asset_id = if let Some(selected_id) = selected_asset_id { ensure!( @@ -501,13 +524,16 @@ impl Pallet { })? }; - AssetIds::::insert(&name, asset_id); + if let Some(n) = name.clone() { + AssetIds::::insert(&n, asset_id); + } let details = AssetDetails { name: name.clone(), asset_type, existential_deposit, xcm_rate_limit, + metadata, }; // Store the details @@ -536,7 +562,14 @@ impl Pallet { if let Some(asset_id) = AssetIds::::get(&bounded_name) { Ok(asset_id) } else { - Self::register_asset(bounded_name, asset_type, existential_deposit, asset_id, None) + Self::register_asset( + Some(bounded_name), + asset_type, + existential_deposit, + asset_id, + None, + None, + ) } } @@ -624,8 +657,17 @@ impl GetByKey> for XcmRateLimitsInRegi impl CreateRegistry for Pallet { type Error = DispatchError; - fn create_asset(name: &[u8], kind: AssetKind, existential_deposit: T::Balance) -> Result { - let bounded_name: BoundedVec = Self::to_bounded_name(name.to_vec())?; - Pallet::::register_asset(bounded_name, kind.into(), existential_deposit, None, None) + fn create_asset( + name: Option<&[u8]>, + kind: AssetKind, + existential_deposit: T::Balance, + ) -> Result { + let bounded_name = if let Some(name) = name { + Some(Self::to_bounded_name(name.to_vec())?) + } else { + None + }; + + Pallet::::register_asset(bounded_name, kind.into(), existential_deposit, None, None, None) } } diff --git a/pallets/asset-registry/src/types.rs b/pallets/asset-registry/src/types.rs index 9f496c22e..157544e8f 100644 --- a/pallets/asset-registry/src/types.rs +++ b/pallets/asset-registry/src/types.rs @@ -31,6 +31,7 @@ pub enum AssetType { XYK, StableSwap, Bond, + External, } impl From for AssetType { @@ -40,6 +41,7 @@ impl From for AssetType { AssetKind::XYK => Self::XYK, AssetKind::StableSwap => Self::StableSwap, AssetKind::Bond => Self::Bond, + AssetKind::External => Self::External, } } } @@ -52,6 +54,7 @@ impl From> for AssetKind { AssetType::XYK => Self::XYK, AssetType::StableSwap => Self::StableSwap, AssetType::Bond => Self::Bond, + AssetType::External => Self::External, } } } @@ -60,16 +63,19 @@ impl From> for AssetKind { #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct AssetDetails { /// The name of this asset. Limited in length by `StringLimit`. - pub name: BoundedString, + pub name: Option, pub asset_type: AssetType, pub existential_deposit: Balance, pub xcm_rate_limit: Option, + + pub metadata: Option>, } -#[derive(Clone, Encode, Decode, Eq, PartialEq, Default, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[derive(Clone, Encode, Decode, Eq, PartialEq, Default, RuntimeDebug, TypeInfo, MaxEncodedLen, Copy)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct AssetMetadata { /// The ticker symbol for this asset. Limited in length by `StringLimit`. pub(super) symbol: BoundedString, diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 8a88ef25b..af9ba807a 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -47,11 +47,13 @@ pub enum AssetKind { XYK, StableSwap, Bond, + External, } pub trait CreateRegistry { type Error; - fn create_asset(name: &[u8], kind: AssetKind, existential_deposit: Balance) -> Result; + fn create_asset(name: Option<&[u8]>, kind: AssetKind, existential_deposit: Balance) + -> Result; } // Deprecated. From b5a4fad39c507c82a3a4d028217bc719db938edb Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 15 Aug 2023 15:53:28 +0200 Subject: [PATCH 02/93] asset-reg: updated bonds asset registration --- pallets/bonds/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/bonds/src/lib.rs b/pallets/bonds/src/lib.rs index 4f111b9d8..ea3c94339 100644 --- a/pallets/bonds/src/lib.rs +++ b/pallets/bonds/src/lib.rs @@ -245,7 +245,7 @@ pub mod pallet { let ed = T::ExistentialDeposits::get(&asset_id); let bond_id = >::create_asset( - &[], + None, AssetKind::Bond, ed, )?; From 4639f8b9f69c02bed9455339838a685d07bc9866 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 23 Aug 2023 12:17:32 +0200 Subject: [PATCH 03/93] asset-registry: WIP make params optional + tests --- Cargo.lock | 1 + pallets/asset-registry/Cargo.toml | 1 + pallets/asset-registry/src/lib.rs | 104 +-- pallets/asset-registry/src/tests.rs | 865 ------------------ .../asset-registry/src/{ => tests}/mock.rs | 48 +- pallets/asset-registry/src/tests/mod.rs | 19 + pallets/asset-registry/src/tests/register.rs | 611 +++++++++++++ pallets/asset-registry/src/tests/update.rs | 0 pallets/asset-registry/src/types.rs | 8 +- traits/src/registry.rs | 2 +- 10 files changed, 699 insertions(+), 960 deletions(-) delete mode 100644 pallets/asset-registry/src/tests.rs rename pallets/asset-registry/src/{ => tests}/mock.rs (74%) create mode 100644 pallets/asset-registry/src/tests/mod.rs create mode 100644 pallets/asset-registry/src/tests/register.rs create mode 100644 pallets/asset-registry/src/tests/update.rs diff --git a/Cargo.lock b/Cargo.lock index 1829ee919..0a0b57ef9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6210,6 +6210,7 @@ dependencies = [ "hydradx-traits", "orml-traits", "parity-scale-codec", + "pretty_assertions", "primitive-types", "scale-info", "serde", diff --git a/pallets/asset-registry/Cargo.toml b/pallets/asset-registry/Cargo.toml index 864d3cbf4..4dc2f5383 100644 --- a/pallets/asset-registry/Cargo.toml +++ b/pallets/asset-registry/Cargo.toml @@ -42,6 +42,7 @@ sp-api = { workspace = true, optional = true } sp-io = { workspace = true } polkadot-xcm = { workspace = true } test-utils = { workspace = true } +pretty_assertions = "1.2.1" [features] default = ["std"] diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index e250be203..4ad292c5f 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -26,9 +26,6 @@ use sp_arithmetic::traits::BaseArithmetic; use sp_std::convert::TryInto; use sp_std::vec::Vec; -#[cfg(test)] -mod mock; - #[cfg(test)] mod tests; @@ -45,14 +42,13 @@ pub use types::AssetType; // Re-export pallet items so that they can be accessed from the crate namespace. pub use pallet::*; -pub use crate::types::{AssetDetails, AssetMetadata}; +pub use crate::types::{AssetDetails, AssetMetadata, Metadata}; use frame_support::BoundedVec; use hydradx_traits::{AssetKind, CreateRegistry, Registry, ShareTokenRegistry}; #[frame_support::pallet] pub mod pallet { use super::*; - use crate::types::Metadata; use frame_support::sp_runtime::traits::AtLeast32BitUnsigned; pub type AssetDetailsT = @@ -176,7 +172,7 @@ pub mod pallet { fn default() -> Self { GenesisConfig:: { registered_assets: vec![], - native_asset_name: b"BSX".to_vec(), + native_asset_name: b"HDX".to_vec(), native_existential_deposit: Default::default(), } } @@ -226,6 +222,8 @@ pub mod pallet { asset_id: T::AssetId, asset_name: Option>, asset_type: AssetType, + existential_deposit: T::Balance, + xcm_rate_limit: Option, }, /// Asset was updated. @@ -240,8 +238,7 @@ pub mod pallet { /// Metadata set for an asset. MetadataSet { asset_id: T::AssetId, - symbol: BoundedVec, - decimals: u8, + metadata: Option, }, /// Native location set for an asset. @@ -289,15 +286,11 @@ pub mod pallet { None }; - let meta = match metadata { - Some(m) => { - let symbol = Self::to_bounded_name(m.symbol)?; - Some(AssetMetadata { - symbol: symbol.clone(), - decimals: m.decimals, - }) - } - None => None, + let meta = if let Some(m) = metadata.as_ref() { + let symbol = Self::to_bounded_name(m.symbol.clone())?; + Some(AssetMetadata::new(symbol, m.decimals)) + } else { + None }; let asset_id = Self::register_asset( @@ -306,15 +299,11 @@ pub mod pallet { existential_deposit, asset_id, xcm_rate_limit, - meta.clone(), + meta, )?; - if let Some(m) = meta { - Self::deposit_event(Event::MetadataSet { - asset_id, - symbol: m.symbol, - decimals: m.decimals, - }); + if metadata.is_some() { + Self::deposit_event(Event::MetadataSet { asset_id, metadata }); } if let Some(loc) = location { @@ -351,32 +340,30 @@ pub mod pallet { asset_type: AssetType, existential_deposit: Option, xcm_rate_limit: Option, + metadata: Option, ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { let mut detail = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; - let new_bounded_name = if let Some(name) = name { - let new_bounded_name = Self::to_bounded_name(name)?; - - if Some(new_bounded_name.clone()) != detail.name { - ensure!( - Self::asset_ids(&new_bounded_name).is_none(), - Error::::AssetAlreadyRegistered - ); - // update also name map - remove old one first - if let Some(old_name) = &detail.name { - AssetIds::::remove(old_name); - } - AssetIds::::insert(&new_bounded_name, asset_id); + let new_bounded_name = if let Some(n) = name { + let new_name = Self::to_bounded_name(n)?; + ensure!(Self::asset_ids(&new_name).is_none(), Error::::AssetAlreadyRegistered); + + if Some(new_name.clone()) != detail.name { + AssetIds::::insert(&new_name, asset_id); } - Some(new_bounded_name) + Some(new_name) } else { None }; + if let Some(old_name) = &detail.name { + AssetIds::::remove(old_name); + } + detail.name = new_bounded_name.clone(); detail.asset_type = asset_type; detail.existential_deposit = existential_deposit.unwrap_or(detail.existential_deposit); @@ -390,6 +377,13 @@ pub mod pallet { xcm_rate_limit: detail.xcm_rate_limit, }); + if let Some(meta) = metadata.as_ref() { + let symbol = Self::to_bounded_name(meta.symbol.clone())?; + detail.metadata = Some(AssetMetadata::new(symbol, meta.decimals)); + + Self::deposit_event(Event::MetadataSet { asset_id, metadata }); + } + Ok(()) }) } @@ -403,30 +397,22 @@ pub mod pallet { /// Emits `MetadataSet` event when successful. #[pallet::call_index(2)] #[pallet::weight(::WeightInfo::set_metadata())] - pub fn set_metadata( - origin: OriginFor, - asset_id: T::AssetId, - symbol: Vec, - decimals: u8, - ) -> DispatchResult { + pub fn set_metadata(origin: OriginFor, asset_id: T::AssetId, metadata: Option) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { let mut detail = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; - let b_symbol = Self::to_bounded_name(symbol)?; - let metadata = AssetMetadata::> { - symbol: b_symbol.clone(), - decimals, + let meta = if let Some(m) = metadata.as_ref() { + let symbol = Self::to_bounded_name(m.symbol.clone())?; + Some(AssetMetadata::new(symbol, m.decimals)) + } else { + None }; - detail.metadata = Some(metadata); + detail.metadata = meta; - Self::deposit_event(Event::MetadataSet { - asset_id, - symbol: b_symbol, - decimals, - }); + Self::deposit_event(Event::MetadataSet { asset_id, metadata }); Ok(()) }) @@ -469,10 +455,6 @@ pub mod pallet { } impl Pallet { - pub fn next_asset_id() -> Option { - NextAssetId::::get().checked_add(&T::SequentialIdStartAt::get()) - } - /// Convert Vec to BoundedVec so it respects the max set limit, otherwise return TooLong error pub fn to_bounded_name(name: Vec) -> Result, Error> { name.try_into().map_err(|_| Error::::TooLong) @@ -495,11 +477,13 @@ impl Pallet { Error::::NotInReservedRange ); + println!("--> sem"); ensure!( !Assets::::contains_key(selected_id), Error::::AssetAlreadyRegistered ); + println!("--> sem2"); selected_id } else { NextAssetId::::mutate(|value| -> Result { @@ -539,12 +523,12 @@ impl Pallet { // Store the details Assets::::insert(asset_id, details); - // Increase asset id to be assigned for following asset. - Self::deposit_event(Event::Registered { asset_id, asset_name: name, asset_type, + existential_deposit, + xcm_rate_limit, }); Ok(asset_id) diff --git a/pallets/asset-registry/src/tests.rs b/pallets/asset-registry/src/tests.rs deleted file mode 100644 index 967d62378..000000000 --- a/pallets/asset-registry/src/tests.rs +++ /dev/null @@ -1,865 +0,0 @@ -// This file is part of pallet-asset-registry. - -// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use super::Error; -use crate::mock::AssetId as RegistryAssetId; -use crate::types::{AssetDetails, AssetMetadata, AssetType, Metadata}; -use crate::Event; -use crate::{mock::*, XcmRateLimitsInRegistry}; -use codec::Encode; -use frame_support::{assert_noop, assert_ok, BoundedVec}; -use orml_traits::GetByKey; -use polkadot_xcm::v3::prelude::*; -use sp_std::convert::TryInto; - -#[test] -fn register_asset_works() { - new_test_ext().execute_with(|| { - let too_long = [1u8; ::StringLimit::get() as usize + 1]; - - let ed = 1_000_000u128; - - assert_noop!( - AssetRegistryPallet::register( - RuntimeOrigin::root(), - too_long.to_vec(), - AssetType::Token, - ed, - None, - None, - None, - None - ), - Error::::TooLong - ); - - let name: Vec = b"HDX".to_vec(); - - assert_ok!(AssetRegistryPallet::register( - RuntimeOrigin::root(), - name.clone(), - AssetType::Token, - ed, - None, - None, - None, - None - )); - - let bn = AssetRegistryPallet::to_bounded_name(name.clone()).unwrap(); - - expect_events(vec![Event::Registered { - asset_id: 1 + SequentialIdStart::get(), - asset_name: bn.clone(), - asset_type: AssetType::Token, - } - .into()]); - - assert_eq!( - AssetRegistryPallet::asset_ids(&bn).unwrap(), - 1u32 + SequentialIdStart::get() - ); - assert_eq!( - AssetRegistryPallet::assets(1u32 + SequentialIdStart::get()).unwrap(), - AssetDetails { - name: bn, - asset_type: AssetType::Token, - existential_deposit: ed, - xcm_rate_limit: None, - } - ); - - assert_noop!( - AssetRegistryPallet::register( - RuntimeOrigin::root(), - name, - AssetType::Token, - ed, - None, - None, - None, - None - ), - Error::::AssetAlreadyRegistered - ); - }); -} - -#[test] -fn create_asset() { - new_test_ext().execute_with(|| { - let ed = 1_000_000u128; - - assert_ok!(AssetRegistryPallet::get_or_create_asset( - b"HDX".to_vec(), - AssetType::Token, - ed, - None, - )); - - let dot_asset = AssetRegistryPallet::get_or_create_asset(b"DOT".to_vec(), AssetType::Token, ed, None); - assert_ok!(dot_asset); - let dot_asset_id = dot_asset.ok().unwrap(); - - assert_ok!(AssetRegistryPallet::get_or_create_asset( - b"BTC".to_vec(), - AssetType::Token, - ed, - None, - )); - - let current_asset_id = AssetRegistryPallet::next_asset_id().unwrap(); - - // Existing asset should return previously created one. - assert_ok!( - AssetRegistryPallet::get_or_create_asset(b"DOT".to_vec(), AssetType::Token, ed, None), - dot_asset_id - ); - - // Retrieving existing asset should not increased the next asset id counter. - assert_eq!(AssetRegistryPallet::next_asset_id().unwrap(), current_asset_id); - - let dot: BoundedVec::StringLimit> = b"DOT".to_vec().try_into().unwrap(); - let aaa: BoundedVec::StringLimit> = b"AAA".to_vec().try_into().unwrap(); - - assert_eq!( - AssetRegistryPallet::asset_ids(dot).unwrap(), - 2u32 + SequentialIdStart::get() - ); - assert!(AssetRegistryPallet::asset_ids(aaa).is_none()); - }); -} - -#[test] -fn location_mapping_works() { - new_test_ext().execute_with(|| { - let bn = AssetRegistryPallet::to_bounded_name(b"HDX".to_vec()).unwrap(); - - let ed = 1_000_000u128; - - assert_ok!(AssetRegistryPallet::get_or_create_asset( - b"HDX".to_vec(), - AssetType::Token, - ed, - None, - )); - let asset_id: RegistryAssetId = - AssetRegistryPallet::get_or_create_asset(b"HDX".to_vec(), AssetType::Token, ed, None).unwrap(); - - crate::Assets::::insert( - asset_id, - AssetDetails::> { - name: bn, - asset_type: AssetType::Token, - existential_deposit: ed, - xcm_rate_limit: None, - }, - ); - - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - - assert_ok!(AssetRegistryPallet::set_location( - RuntimeOrigin::root(), - asset_id, - asset_location.clone() - )); - - expect_events(vec![Event::LocationSet { - asset_id: 1 + SequentialIdStart::get(), - location: asset_location.clone(), - } - .into()]); - - assert_eq!( - AssetRegistryPallet::location_to_asset(asset_location.clone()), - Some(asset_id) - ); - assert_eq!( - AssetRegistryPallet::asset_to_location(asset_id), - Some(asset_location.clone()) - ); - - // asset location for the native asset cannot be changed - assert_noop!( - AssetRegistryPallet::set_location( - RuntimeOrigin::root(), - ::NativeAssetId::get(), - asset_location - ), - Error::::CannotUpdateLocation - ); - }); -} - -#[test] -fn genesis_config_works() { - ExtBuilder::default() - .with_native_asset_name(b"NATIVE".to_vec()) - .build() - .execute_with(|| { - let native: BoundedVec::StringLimit> = b"NATIVE".to_vec().try_into().unwrap(); - assert_eq!(AssetRegistryPallet::asset_ids(native).unwrap(), 0u32); - }); - - let one = b"ONE".to_vec(); - let life = b"LIFE".to_vec(); - - ExtBuilder::default() - .with_assets(vec![ - (one.clone(), 1_000u128, None), - (life.clone(), 1_000u128, Some(42)), - ]) - .build() - .execute_with(|| { - let native: BoundedVec::StringLimit> = b"NATIVE".to_vec().try_into().unwrap(); - assert_eq!(AssetRegistryPallet::asset_ids(native), None); - - let bsx: BoundedVec::StringLimit> = b"BSX".to_vec().try_into().unwrap(); - assert_eq!(AssetRegistryPallet::asset_ids(bsx).unwrap(), 0u32); - - let one: BoundedVec::StringLimit> = one.try_into().unwrap(); - assert_eq!( - AssetRegistryPallet::asset_ids(one.clone()).unwrap(), - 1u32 + SequentialIdStart::get() - ); - assert_eq!( - AssetRegistryPallet::assets(1u32 + SequentialIdStart::get()).unwrap(), - AssetDetails { - name: one, - asset_type: AssetType::Token, - existential_deposit: 1_000u128, - xcm_rate_limit: None, - } - ); - - let life: BoundedVec::StringLimit> = life.try_into().unwrap(); - assert_eq!(AssetRegistryPallet::asset_ids(life.clone()).unwrap(), 42u32); - assert_eq!( - AssetRegistryPallet::assets(42u32).unwrap(), - AssetDetails { - name: life, - asset_type: AssetType::Token, - existential_deposit: 1_000u128, - xcm_rate_limit: None, - } - ); - }); -} - -#[test] -fn set_metadata_works() { - ExtBuilder::default() - .with_assets(vec![(b"DOT".to_vec(), 1_000u128, None)]) - .build() - .execute_with(|| { - System::set_block_number(1); //TO have the ement emitted - - let dot: BoundedVec::StringLimit> = b"DOT".to_vec().try_into().unwrap(); - let dot_id = AssetRegistryPallet::asset_ids(dot).unwrap(); - let b_symbol: BoundedVec::StringLimit> = b"xDOT".to_vec().try_into().unwrap(); - - assert_ok!(AssetRegistryPallet::set_metadata( - RuntimeOrigin::root(), - dot_id, - b"xDOT".to_vec(), - 12u8 - )); - - expect_events(vec![Event::MetadataSet { - asset_id: dot_id, - symbol: b_symbol.clone(), - decimals: 12u8, - } - .into()]); - - assert_eq!( - AssetRegistryPallet::asset_metadata(dot_id).unwrap(), - AssetMetadata { - decimals: 12u8, - symbol: b_symbol.clone(), - } - ); - - assert_ok!(AssetRegistryPallet::set_metadata( - RuntimeOrigin::root(), - dot_id, - b"xDOT".to_vec(), - 30u8 - )); - - assert_eq!( - AssetRegistryPallet::asset_metadata(dot_id).unwrap(), - AssetMetadata { - decimals: 30u8, - symbol: b_symbol, - } - ); - - assert_noop!( - AssetRegistryPallet::set_metadata(RuntimeOrigin::root(), dot_id, b"JUST_TOO_LONG".to_vec(), 30u8), - Error::::TooLong - ); - - assert_noop!( - AssetRegistryPallet::set_metadata(RuntimeOrigin::root(), 100, b"NONE".to_vec(), 30u8), - Error::::AssetNotFound - ); - }); -} - -#[test] -fn update_asset() { - new_test_ext().execute_with(|| { - let ed = 1_000_000u128; - - let btc_asset_id: RegistryAssetId = - AssetRegistryPallet::get_or_create_asset(b"BTC".to_vec(), AssetType::Token, ed, None).unwrap(); - let usd_asset_id: RegistryAssetId = - AssetRegistryPallet::get_or_create_asset(b"USD".to_vec(), AssetType::Token, ed, None).unwrap(); - - let next_asset_id = AssetRegistryPallet::next_asset_id().unwrap(); - - // set a new name and type for an existing asset - assert_ok!(AssetRegistryPallet::update( - RuntimeOrigin::root(), - btc_asset_id, - b"superBTC".to_vec(), - AssetType::Token, - None, - None, - )); - let bn = AssetRegistryPallet::to_bounded_name(b"superBTC".to_vec()).unwrap(); - - expect_events(vec![Event::Updated { - asset_id: btc_asset_id, - asset_name: bn.clone(), - asset_type: AssetType::Token, - existential_deposit: 1_000_000, - xcm_rate_limit: None, - } - .into()]); - - assert_eq!( - AssetRegistryPallet::assets(btc_asset_id).unwrap(), - AssetDetails { - name: bn, - asset_type: AssetType::Token, - existential_deposit: ed, - xcm_rate_limit: None, - } - ); - - let new_btc_name: BoundedVec::StringLimit> = - b"superBTC".to_vec().try_into().unwrap(); - assert_eq!( - AssetRegistryPallet::asset_ids(new_btc_name).unwrap(), - 1u32 + SequentialIdStart::get() - ); - - // cannot set existing name for an existing asset - assert_noop!( - (AssetRegistryPallet::update( - RuntimeOrigin::root(), - usd_asset_id, - b"superBTC".to_vec(), - AssetType::Token, - None, - None, - )), - Error::::AssetAlreadyRegistered - ); - - // cannot set a new name for a non-existent asset - assert_noop!( - (AssetRegistryPallet::update( - RuntimeOrigin::root(), - next_asset_id, - b"VOID".to_vec(), - AssetType::Token, - None, - None, - )), - Error::::AssetNotFound - ); - - // corner case: change the name and also the type for an existing asset (token -> pool share) - assert_ok!(AssetRegistryPallet::update( - RuntimeOrigin::root(), - btc_asset_id, - b"BTCUSD".to_vec(), - AssetType::PoolShare(btc_asset_id, usd_asset_id), - None, - None, - )); - - // Update ED - assert_ok!(AssetRegistryPallet::update( - RuntimeOrigin::root(), - btc_asset_id, - b"BTCUSD".to_vec(), - AssetType::PoolShare(btc_asset_id, usd_asset_id), - Some(1_234_567u128), - None, - )); - - let btcusd = AssetRegistryPallet::to_bounded_name(b"BTCUSD".to_vec()).unwrap(); - - assert_eq!( - AssetRegistryPallet::assets(btc_asset_id).unwrap(), - AssetDetails { - name: btcusd, - asset_type: AssetType::PoolShare(btc_asset_id, usd_asset_id), - existential_deposit: 1_234_567u128, - xcm_rate_limit: None, - } - ); - - // corner case: change the name and also the type for an existing asset (pool share -> token) - assert_ok!(AssetRegistryPallet::update( - RuntimeOrigin::root(), - btc_asset_id, - b"superBTC".to_vec(), - AssetType::Token, - None, - None, - )); - - let superbtc_name: BoundedVec::StringLimit> = - b"superBTC".to_vec().try_into().unwrap(); - - assert_eq!( - AssetRegistryPallet::assets(1u32 + SequentialIdStart::get()).unwrap(), - AssetDetails { - name: superbtc_name, - asset_type: AssetType::Token, - existential_deposit: 1_234_567u128, - xcm_rate_limit: None, - } - ); - }); -} - -#[test] -fn update_should_update_xcm_rate_limit() { - new_test_ext().execute_with(|| { - let ed = 1_000_000u128; - - let btc_asset_id: RegistryAssetId = - AssetRegistryPallet::get_or_create_asset(b"BTC".to_vec(), AssetType::Token, ed, None).unwrap(); - - assert_ok!(AssetRegistryPallet::update( - RuntimeOrigin::root(), - btc_asset_id, - b"superBTC".to_vec(), - AssetType::Token, - None, - Some(1000 * UNIT) - )); - - let bn = AssetRegistryPallet::to_bounded_name(b"superBTC".to_vec()).unwrap(); - - assert_eq!( - AssetRegistryPallet::assets(btc_asset_id).unwrap(), - AssetDetails { - name: bn.clone(), - asset_type: AssetType::Token, - existential_deposit: ed, - xcm_rate_limit: Some(1000 * UNIT), - } - ); - - assert_eq!(XcmRateLimitsInRegistry::::get(&btc_asset_id), Some(1000 * UNIT)); - - expect_events(vec![Event::Updated { - asset_id: btc_asset_id, - asset_name: bn, - asset_type: AssetType::Token, - existential_deposit: ed, - xcm_rate_limit: Some(1000 * UNIT), - } - .into()]); - }); -} - -#[test] -fn get_ed_by_key_works() { - ExtBuilder::default() - .with_native_asset_name(b"NATIVE".to_vec()) - .with_assets(vec![ - (b"ONE".to_vec(), 1_000u128, None), - (b"TWO".to_vec(), 2_000u128, None), - ]) - .build() - .execute_with(|| { - assert_eq!(AssetRegistryPallet::get(&(1u32 + SequentialIdStart::get())), 1_000u128); - assert_eq!(AssetRegistryPallet::get(&(2u32 + SequentialIdStart::get())), 2_000u128); - assert_eq!(AssetRegistryPallet::get(&0u32), 1_000_000u128); - assert_eq!( - AssetRegistryPallet::get(&(1_000u32 + SequentialIdStart::get())), - Balance::MAX - ); // Non-existing assets are not supported - }); -} - -#[test] -fn register_asset_should_work_when_asset_is_provided() { - ExtBuilder::default() - .with_native_asset_name(b"NATIVE".to_vec()) - .build() - .execute_with(|| { - assert_ok!(AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id".to_vec(), - AssetType::Token, - 1_000_000, - Some(1u32), - None, - None, - None - ),); - - let bn = AssetRegistryPallet::to_bounded_name(b"asset_id".to_vec()).unwrap(); - assert_eq!( - AssetRegistryPallet::assets(1u32).unwrap(), - AssetDetails { - name: bn, - asset_type: AssetType::Token, - existential_deposit: 1_000_000, - xcm_rate_limit: None, - } - ); - }); -} - -#[test] -fn register_asset_should_fail_when_provided_asset_is_native_asset() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id".to_vec(), - AssetType::Token, - 1_000_000, - Some(NativeAssetId::get()), - None, - None, - None - ), - Error::::AssetAlreadyRegistered - ); - }); -} - -#[test] -fn register_asset_should_fail_when_provided_asset_is_already_registered() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!(AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id".to_vec(), - AssetType::Token, - 1_000_000, - Some(10), - None, - None, - None - )); - assert_noop!( - AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id_2".to_vec(), - AssetType::Token, - 1_000_000, - Some(10), - None, - None, - None - ), - Error::::AssetAlreadyRegistered - ); - }); -} - -#[test] -fn register_asset_should_fail_when_provided_asset_is_outside_reserved_range() { - ExtBuilder::default() - .with_native_asset_name(b"NATIVE".to_vec()) - .build() - .execute_with(|| { - assert_noop!( - AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id".to_vec(), - AssetType::Token, - 1_000_000, - Some(SequentialIdStart::get()), - None, - None, - None - ), - Error::::NotInReservedRange - ); - - assert_noop!( - AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id".to_vec(), - AssetType::Token, - 1_000_000, - Some(SequentialIdStart::get() + 100), - None, - None, - None - ), - Error::::NotInReservedRange - ); - }); -} - -#[test] -fn register_asset_should_work_when_metadata_is_provided() { - new_test_ext().execute_with(|| { - let asset_id: RegistryAssetId = 10; - let decimals = 18; - let symbol = b"SYM".to_vec(); - let asset_name = b"asset_name".to_vec(); - let b_symbol = AssetRegistryPallet::to_bounded_name(symbol.clone()).unwrap(); - let b_asset_name = AssetRegistryPallet::to_bounded_name(asset_name.clone()).unwrap(); - - assert_ok!(AssetRegistryPallet::register( - RuntimeOrigin::root(), - asset_name, - AssetType::Token, - 1_000_000, - Some(asset_id), - Some(Metadata { symbol, decimals }), - None, - None, - )); - - expect_events(vec![ - Event::Registered { - asset_id, - asset_name: b_asset_name.clone(), - asset_type: AssetType::Token, - } - .into(), - Event::MetadataSet { - asset_id, - symbol: b_symbol.clone(), - decimals, - } - .into(), - ]); - - assert_eq!( - AssetRegistryPallet::assets(asset_id).unwrap(), - AssetDetails { - name: b_asset_name, - asset_type: AssetType::Token, - existential_deposit: 1_000_000, - xcm_rate_limit: None, - } - ); - - assert_eq!( - AssetRegistryPallet::asset_metadata(asset_id).unwrap(), - AssetMetadata { - decimals: 18u8, - symbol: b_symbol, - } - ); - }); -} - -#[test] -fn register_asset_should_work_when_location_is_provided() { - ExtBuilder::default().build().execute_with(|| { - let asset_id: RegistryAssetId = 10; - - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - - assert_ok!(AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id".to_vec(), - AssetType::Token, - 1_000_000, - Some(asset_id), - None, - Some(asset_location.clone()), - None - ),); - - let bn = AssetRegistryPallet::to_bounded_name(b"asset_id".to_vec()).unwrap(); - assert_eq!( - AssetRegistryPallet::assets(asset_id).unwrap(), - AssetDetails { - name: bn, - asset_type: AssetType::Token, - existential_deposit: 1_000_000, - xcm_rate_limit: None, - } - ); - assert_eq!( - AssetRegistryPallet::location_to_asset(asset_location.clone()), - Some(asset_id) - ); - assert_eq!(AssetRegistryPallet::asset_to_location(asset_id), Some(asset_location)); - - assert!(AssetRegistryPallet::asset_metadata(asset_id).is_none(),); - }); -} - -#[test] -fn register_asset_should_fail_when_location_is_already_registered() { - ExtBuilder::default().build().execute_with(|| { - // Arrange - let asset_id: RegistryAssetId = 10; - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(2021), key))); - assert_ok!(AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id".to_vec(), - AssetType::Token, - 1_000_000, - Some(asset_id), - None, - Some(asset_location.clone()), - None - ),); - - // Act & Assert - assert_noop!( - AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id_2".to_vec(), - AssetType::Token, - 1_000_000, - Some(asset_id + 1), - None, - Some(asset_location), - None - ), - Error::::LocationAlreadyRegistered - ); - }); -} - -#[test] -fn set_location_should_fail_when_location_is_already_registered() { - ExtBuilder::default().build().execute_with(|| { - // Arrange - let asset_id: RegistryAssetId = 10; - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(2021), key))); - assert_ok!(AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id".to_vec(), - AssetType::Token, - 1_000_000, - Some(asset_id), - None, - Some(asset_location.clone()), - None - ),); - - // Act & Assert - assert_noop!( - AssetRegistryPallet::set_location(RuntimeOrigin::root(), asset_id, asset_location), - Error::::LocationAlreadyRegistered - ); - }); -} - -#[test] -fn set_location_should_remove_old_location() { - ExtBuilder::default().build().execute_with(|| { - // Arrange - let asset_id: RegistryAssetId = 10; - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let old_asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(2021), key))); - assert_ok!(AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id".to_vec(), - AssetType::Token, - 1_000_000, - Some(asset_id), - None, - Some(old_asset_location.clone()), - None - ),); - - // Act - assert_ok!(AssetRegistryPallet::set_location( - RuntimeOrigin::root(), - asset_id, - AssetLocation(MultiLocation::new(0, X2(Parachain(2022), key))) - )); - - // Assert - assert_eq!(AssetRegistryPallet::location_to_asset(old_asset_location), None); - }); -} - -#[test] -fn register_asset_should_work_when_all_optional_are_provided() { - ExtBuilder::default().build().execute_with(|| { - let asset_id: RegistryAssetId = 10; - - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - - assert_ok!(AssetRegistryPallet::register( - RuntimeOrigin::root(), - b"asset_id".to_vec(), - AssetType::Token, - 1_000_000, - Some(asset_id), - Some(Metadata { - symbol: b"SYM".to_vec(), - decimals: 18 - }), - Some(asset_location.clone()), - Some(1000 * UNIT) - ),); - - let bn = AssetRegistryPallet::to_bounded_name(b"asset_id".to_vec()).unwrap(); - assert_eq!( - AssetRegistryPallet::assets(asset_id).unwrap(), - AssetDetails { - name: bn, - asset_type: AssetType::Token, - existential_deposit: 1_000_000, - xcm_rate_limit: Some(1000 * UNIT), - } - ); - assert_eq!( - AssetRegistryPallet::location_to_asset(asset_location.clone()), - Some(asset_id) - ); - assert_eq!(AssetRegistryPallet::asset_to_location(asset_id), Some(asset_location)); - let b_symbol: BoundedVec::StringLimit> = b"SYM".to_vec().try_into().unwrap(); - assert_eq!( - AssetRegistryPallet::asset_metadata(asset_id).unwrap(), - AssetMetadata { - decimals: 18u8, - symbol: b_symbol, - } - ); - }); -} diff --git a/pallets/asset-registry/src/mock.rs b/pallets/asset-registry/src/tests/mock.rs similarity index 74% rename from pallets/asset-registry/src/mock.rs rename to pallets/asset-registry/src/tests/mock.rs index f338ef277..0c2fc488b 100644 --- a/pallets/asset-registry/src/mock.rs +++ b/pallets/asset-registry/src/tests/mock.rs @@ -29,12 +29,13 @@ use frame_support::traits::{Everything, GenesisBuild}; use polkadot_xcm::v3::MultiLocation; -use crate::{self as asset_registry, Config}; +use crate as pallet_asset_registry; pub type AssetId = u32; pub type Balance = u128; pub const UNIT: Balance = 1_000_000_000_000; +pub const ALICE: u64 = 1_000; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -46,7 +47,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event}, - Registry: asset_registry::{Pallet, Call, Storage, Event}, + Registry: pallet_asset_registry::{Pallet, Call, Storage, Event}, } ); @@ -92,7 +93,7 @@ use scale_info::TypeInfo; #[derive(Debug, Default, Encode, Decode, Clone, PartialEq, Eq, TypeInfo, MaxEncodedLen)] pub struct AssetLocation(pub MultiLocation); -impl Config for Test { +impl pallet_asset_registry::Config for Test { type RuntimeEvent = RuntimeEvent; type RegistryOrigin = frame_system::EnsureRoot; type AssetId = u32; @@ -103,52 +104,33 @@ impl Config for Test { type NativeAssetId = NativeAssetId; type WeightInfo = (); } -pub type AssetRegistryPallet = crate::Pallet; #[derive(Default)] pub struct ExtBuilder { - registered_assets: Vec<(Vec, Balance, Option)>, - native_asset_name: Option>, + registered_assets: Vec<(Option>, Balance, Option)>, } impl ExtBuilder { - pub fn with_assets(mut self, asset_ids: Vec<(Vec, Balance, Option)>) -> Self { + pub fn with_assets(mut self, asset_ids: Vec<(Option>, Balance, Option)>) -> Self { self.registered_assets = asset_ids; self } - pub fn with_native_asset_name(mut self, name: Vec) -> Self { - self.native_asset_name = Some(name); - self - } - pub fn build(self) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - if let Some(name) = self.native_asset_name { - crate::GenesisConfig:: { - registered_assets: self.registered_assets, - native_asset_name: name, - native_existential_deposit: 1_000_000u128, - } - } else { - crate::GenesisConfig:: { - registered_assets: self.registered_assets, - ..Default::default() - } + crate::GenesisConfig:: { + registered_assets: self.registered_assets, + ..Default::default() } .assimilate_storage(&mut t) .unwrap(); - t.into() - } -} -pub fn new_test_ext() -> sp_io::TestExternalities { - let mut ext = ExtBuilder::default().build(); - ext.execute_with(|| System::set_block_number(1)); - ext -} + let mut r: sp_io::TestExternalities = t.into(); + r.execute_with(|| { + System::set_block_number(1); + }); -pub fn expect_events(e: Vec) { - test_utils::expect_events::(e); + r + } } diff --git a/pallets/asset-registry/src/tests/mod.rs b/pallets/asset-registry/src/tests/mod.rs new file mode 100644 index 000000000..f85c48bcb --- /dev/null +++ b/pallets/asset-registry/src/tests/mod.rs @@ -0,0 +1,19 @@ +use mock::*; + +use crate::*; +use frame_support::{assert_noop, assert_ok}; + +pub(crate) mod mock; +mod register; +mod update; + +#[macro_export] +macro_rules! assert_last_event { + ( $x:expr ) => {{ + pretty_assertions::assert_eq!(System::events().last().expect("events expected").event, $x); + }}; +} + +pub fn has_event(event: mock::RuntimeEvent) -> bool { + System::events().iter().any(|record| record.event == event) +} diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs new file mode 100644 index 000000000..7b6d15776 --- /dev/null +++ b/pallets/asset-registry/src/tests/register.rs @@ -0,0 +1,611 @@ +use super::*; + +use crate::types::{AssetType, Metadata}; +use mock::Registry; +use polkadot_xcm::v3::{ + Junction::{self, Parachain}, + Junctions::X2, + MultiLocation, +}; +use pretty_assertions::assert_eq; + +#[test] +fn register_should_work_when_all_params_are_provided() { + ExtBuilder::default().build().execute_with(|| { + let asset_id = 1; + let name = b"Test asset".to_vec(); + let metadata = Metadata { + symbol: b"TKN".to_vec(), + decimals: 12, + }; + let xcm_rate_limit = 1_000; + let existential_deposit = 10_000; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!(Registry::register( + RuntimeOrigin::root(), + Some(name.clone()), + AssetType::Token, + existential_deposit, + Some(asset_id), + Some(metadata.clone()), + Some(asset_location.clone()), + Some(xcm_rate_limit) + )); + + //Assert + let bounded_name = Pallet::::to_bounded_name(name).unwrap(); + assert_eq!( + Registry::assets(asset_id), + Some(AssetDetails { + name: Some(bounded_name.clone()), + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: Some(xcm_rate_limit), + metadata: Some(AssetMetadata { + symbol: Registry::to_bounded_name(metadata.symbol.clone()).unwrap(), + decimals: metadata.decimals + }) + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone()), Some(asset_id)); + + assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id, + asset_name: Some(bounded_name), + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: Some(xcm_rate_limit) + } + .into() + )); + + assert!(has_event( + Event::::MetadataSet { + asset_id, + metadata: Some(metadata) + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id, + location: asset_location + } + .into() + )); + }); +} + +#[test] +fn register_should_work_when_asset_id_is_non_provided() { + ExtBuilder::default().build().execute_with(|| { + let name = b"Test asset".to_vec(); + let metadata = Metadata { + symbol: b"TKN".to_vec(), + decimals: 12, + }; + let xcm_rate_limit = 1_000; + let existential_deposit = 1 * UNIT; + + let expected_asset_id = crate::NextAssetId::::get() + ::SequentialIdStartAt::get() + 1; + let key = Junction::from(BoundedVec::try_from(expected_asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!(Registry::register( + RuntimeOrigin::root(), + Some(name.clone()), + AssetType::Token, + existential_deposit, + None, + Some(metadata.clone()), + Some(asset_location.clone()), + Some(xcm_rate_limit) + )); + + //Assert + let bounded_name = Pallet::::to_bounded_name(name).unwrap(); + assert_eq!( + Registry::assets(expected_asset_id), + Some(AssetDetails { + name: Some(bounded_name.clone()), + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: Some(xcm_rate_limit), + metadata: Some(AssetMetadata { + symbol: Registry::to_bounded_name(metadata.symbol.clone()).unwrap(), + decimals: metadata.decimals + }) + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone()), Some(expected_asset_id)); + + assert_eq!( + Registry::location_assets(asset_location.clone()), + Some(expected_asset_id) + ); + assert_eq!(Registry::locations(expected_asset_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id: expected_asset_id, + asset_name: Some(bounded_name), + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: Some(xcm_rate_limit) + } + .into() + )); + + assert!(has_event( + Event::::MetadataSet { + asset_id: expected_asset_id, + metadata: Some(metadata) + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id: expected_asset_id, + location: asset_location + } + .into() + )); + }); +} + +#[test] +fn register_should_work_when_metadata_is_not_provided() { + ExtBuilder::default().build().execute_with(|| { + let name = b"Test asset".to_vec(); + let xcm_rate_limit = 1_000; + let existential_deposit = 1 * UNIT; + + let expected_asset_id = crate::NextAssetId::::get() + ::SequentialIdStartAt::get() + 1; + let key = Junction::from(BoundedVec::try_from(expected_asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!(Registry::register( + RuntimeOrigin::root(), + Some(name.clone()), + AssetType::Token, + existential_deposit, + None, + None, + Some(asset_location.clone()), + Some(xcm_rate_limit) + )); + + //Assert + let bounded_name = Pallet::::to_bounded_name(name).unwrap(); + assert_eq!( + Registry::assets(expected_asset_id), + Some(AssetDetails { + name: Some(bounded_name.clone()), + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: Some(xcm_rate_limit), + metadata: None, + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone()), Some(expected_asset_id)); + + assert_eq!( + Registry::location_assets(asset_location.clone()), + Some(expected_asset_id) + ); + assert_eq!(Registry::locations(expected_asset_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id: expected_asset_id, + asset_name: Some(bounded_name), + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: Some(xcm_rate_limit) + } + .into() + )); + + assert!(!has_event( + Event::::MetadataSet { + asset_id: expected_asset_id, + metadata: None + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id: expected_asset_id, + location: asset_location + } + .into() + )); + }); +} + +#[test] +fn register_should_work_when_location_is_not_provided() { + ExtBuilder::default().build().execute_with(|| { + let asset_id = 1; + let name = b"Test asset".to_vec(); + let metadata = Metadata { + symbol: b"TKN".to_vec(), + decimals: 12, + }; + let xcm_rate_limit = 1_000; + let existential_deposit = 10_000; + + //Act + assert_ok!(Registry::register( + RuntimeOrigin::root(), + Some(name.clone()), + AssetType::Token, + existential_deposit, + Some(asset_id), + Some(metadata.clone()), + None, + Some(xcm_rate_limit) + )); + + //Assert + let bounded_name = Pallet::::to_bounded_name(name).unwrap(); + assert_eq!( + Registry::assets(asset_id), + Some(AssetDetails { + name: Some(bounded_name.clone()), + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: Some(xcm_rate_limit), + metadata: Some(AssetMetadata { + symbol: Registry::to_bounded_name(metadata.symbol.clone()).unwrap(), + decimals: metadata.decimals + }) + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone()), Some(asset_id)); + + assert_eq!(Registry::locations(asset_id), None); + + assert!(has_event( + Event::::Registered { + asset_id, + asset_name: Some(bounded_name), + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: Some(xcm_rate_limit) + } + .into() + )); + + assert!(has_event( + Event::::MetadataSet { + asset_id, + metadata: Some(metadata) + } + .into() + )); + }); +} + +#[test] +fn register_should_work_when_xmc_rate_limit_is_not_provided() { + ExtBuilder::default().build().execute_with(|| { + let asset_id = 1; + let name = b"Test asset".to_vec(); + let metadata = Metadata { + symbol: b"TKN".to_vec(), + decimals: 12, + }; + let existential_deposit = 10_000; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!(Registry::register( + RuntimeOrigin::root(), + Some(name.clone()), + AssetType::Token, + existential_deposit, + Some(asset_id), + Some(metadata.clone()), + Some(asset_location.clone()), + None + )); + + //Assert + let bounded_name = Pallet::::to_bounded_name(name).unwrap(); + assert_eq!( + Registry::assets(asset_id), + Some(AssetDetails { + name: Some(bounded_name.clone()), + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: None, + metadata: Some(AssetMetadata { + symbol: Registry::to_bounded_name(metadata.symbol.clone()).unwrap(), + decimals: metadata.decimals + }) + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone()), Some(asset_id)); + + assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id, + asset_name: Some(bounded_name), + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: None + } + .into() + )); + + assert!(has_event( + Event::::MetadataSet { + asset_id, + metadata: Some(metadata) + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id, + location: asset_location + } + .into() + )); + }); +} + +#[test] +fn register_should_fail_when_asset_name_is_already_used() { + ExtBuilder::default() + .with_assets(vec![(Some(b"Test asset".to_vec()), 1 * UNIT, Some(2))]) + .build() + .execute_with(|| { + let asset_id = 1; + let name = b"Test asset".to_vec(); + let metadata = Metadata { + symbol: b"TKN".to_vec(), + decimals: 12, + }; + let xcm_rate_limit = 1_000; + let existential_deposit = 10_000; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act & assert + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(name.clone()), + AssetType::Token, + existential_deposit, + Some(asset_id), + Some(metadata.clone()), + Some(asset_location.clone()), + Some(xcm_rate_limit) + ), + Error::::AssetAlreadyRegistered + ); + }); +} + +#[test] +fn register_should_fail_when_asset_id_is_already_used() { + ExtBuilder::default() + .with_assets(vec![(Some(b"Test".to_vec()), 1 * UNIT, Some(2))]) + .build() + .execute_with(|| { + let asset_id = 2; + let name = b"Test asset".to_vec(); + let metadata = Metadata { + symbol: b"TKN".to_vec(), + decimals: 12, + }; + let xcm_rate_limit = 1_000; + let existential_deposit = 10_000; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act & assert + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(name.clone()), + AssetType::Token, + existential_deposit, + Some(asset_id), + Some(metadata.clone()), + Some(asset_location.clone()), + Some(xcm_rate_limit) + ), + Error::::AssetAlreadyRegistered + ); + }); +} + +#[test] +fn register_should_fail_when_origin_is_not_allowed() { + ExtBuilder::default().build().execute_with(|| { + let asset_id = 1; + let name = b"Test asset".to_vec(); + let metadata = Metadata { + symbol: b"TKN".to_vec(), + decimals: 12, + }; + let xcm_rate_limit = 1_000; + let existential_deposit = 10_000; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_noop!(Registry::register( + RuntimeOrigin::signed(ALICE), + Some(name.clone()), + AssetType::Token, + existential_deposit, + Some(asset_id), + Some(metadata.clone()), + Some(asset_location.clone()), + Some(xcm_rate_limit) + ), DispatchError::BadOrigin); + }); +} + +#[test] +fn register_should_fail_when_origin_is_none() { + ExtBuilder::default().build().execute_with(|| { + let asset_id = 1; + let name = b"Test asset".to_vec(); + let metadata = Metadata { + symbol: b"TKN".to_vec(), + decimals: 12, + }; + let xcm_rate_limit = 1_000; + let existential_deposit = 10_000; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_noop!(Registry::register( + RuntimeOrigin::none(), + Some(name.clone()), + AssetType::Token, + existential_deposit, + Some(asset_id), + Some(metadata.clone()), + Some(asset_location.clone()), + Some(xcm_rate_limit) + ), DispatchError::BadOrigin); + }); +} + +#[test] +fn register_should_fail_when_provided_asset_id_is_not_from_reserved_range() { + ExtBuilder::default().build().execute_with(|| { + let asset_id = ::SequentialIdStartAt::get(); + let name = b"Test asset".to_vec(); + let metadata = Metadata { + symbol: b"TKN".to_vec(), + decimals: 12, + }; + let xcm_rate_limit = 1_000; + let existential_deposit = 10_000; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_noop!(Registry::register( + RuntimeOrigin::root(), + Some(name.clone()), + AssetType::Token, + existential_deposit, + Some(asset_id), + Some(metadata.clone()), + Some(asset_location.clone()), + Some(xcm_rate_limit) + ), Error::::NotInReservedRange); + }); +} + +#[test] +fn register_should_fail_when_asset_name_is_too_long() { + ExtBuilder::default().build().execute_with(|| { + let asset_id = 1; + let name = b"Too long asset name".to_vec(); + let metadata = Metadata { + symbol: b"TKN".to_vec(), + decimals: 12, + }; + let xcm_rate_limit = 1_000; + let existential_deposit = 10_000; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_noop!(Registry::register( + RuntimeOrigin::root(), + Some(name.clone()), + AssetType::Token, + existential_deposit, + Some(asset_id), + Some(metadata.clone()), + Some(asset_location.clone()), + Some(xcm_rate_limit) + ), Error::::TooLong); + }); +} + +#[test] +fn register_should_work_when_only_required_params_are_provided() { + ExtBuilder::default().build().execute_with(|| { + let existential_deposit = 10_000; + let expected_asset_id = crate::NextAssetId::::get() + ::SequentialIdStartAt::get() + 1; + + //Act + assert_ok!(Registry::register( + RuntimeOrigin::root(), + None, + AssetType::Token, + existential_deposit, + None, + None, + None, + None)); + + //Assert + assert_eq!( + Registry::assets(expected_asset_id), + Some(AssetDetails { + name: None, + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: None, + metadata: None, + }) + ); + + assert_eq!(Registry::locations(expected_asset_id), None); + + assert!(has_event( + Event::::Registered { + asset_id: expected_asset_id, + asset_name: None, + asset_type: AssetType::Token, + existential_deposit, + xcm_rate_limit: None + } + .into() + )); + }); +} diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs new file mode 100644 index 000000000..e69de29bb diff --git a/pallets/asset-registry/src/types.rs b/pallets/asset-registry/src/types.rs index 157544e8f..e99fa0e10 100644 --- a/pallets/asset-registry/src/types.rs +++ b/pallets/asset-registry/src/types.rs @@ -31,7 +31,7 @@ pub enum AssetType { XYK, StableSwap, Bond, - External, + External, } impl From for AssetType { @@ -83,6 +83,12 @@ pub struct AssetMetadata { pub(super) decimals: u8, } +impl AssetMetadata { + pub fn new(symbol: BoundedString, decimals: u8) -> Self { + Self { symbol, decimals } + } +} + #[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct Metadata { diff --git a/traits/src/registry.rs b/traits/src/registry.rs index af9ba807a..734ead69a 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -47,7 +47,7 @@ pub enum AssetKind { XYK, StableSwap, Bond, - External, + External, } pub trait CreateRegistry { From 43880b8914908080ba39220e0f6bf90b7869165d Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 23 Aug 2023 13:07:09 +0200 Subject: [PATCH 04/93] asset-registry: remove debug println --- pallets/asset-registry/src/lib.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 4ad292c5f..e165fd7d4 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -329,8 +329,6 @@ pub mod pallet { /// Updates also mapping between name and asset id if provided name is different than currently registered. /// /// Emits `Updated` event when successful. - - // TODO: No tests #[pallet::call_index(1)] #[pallet::weight(::WeightInfo::update())] pub fn update( @@ -477,13 +475,11 @@ impl Pallet { Error::::NotInReservedRange ); - println!("--> sem"); ensure!( !Assets::::contains_key(selected_id), Error::::AssetAlreadyRegistered ); - println!("--> sem2"); selected_id } else { NextAssetId::::mutate(|value| -> Result { From c2f505106563c571a30b6c8c512720e99efb15a4 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 24 Aug 2023 15:29:04 +0200 Subject: [PATCH 05/93] asset-registry: WIP pallet refactor --- pallets/asset-registry/src/lib.rs | 466 ++++++++++++++-------------- pallets/asset-registry/src/types.rs | 51 +-- traits/src/registry.rs | 22 +- 3 files changed, 276 insertions(+), 263 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index e165fd7d4..773d06193 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -42,17 +42,19 @@ pub use types::AssetType; // Re-export pallet items so that they can be accessed from the crate namespace. pub use pallet::*; -pub use crate::types::{AssetDetails, AssetMetadata, Metadata}; +pub use crate::types::{AssetDetails, Balance}; use frame_support::BoundedVec; use hydradx_traits::{AssetKind, CreateRegistry, Registry, ShareTokenRegistry}; +/// Default value of existential deposit. This value is used if existential deposit wasn't +/// provided. +pub const DEFAULT_ED: Balance = 1; + #[frame_support::pallet] pub mod pallet { use super::*; - use frame_support::sp_runtime::traits::AtLeast32BitUnsigned; - pub type AssetDetailsT = - AssetDetails<::AssetId, ::Balance, BoundedVec::StringLimit>>; + pub type AssetDetailsT = AssetDetails<::AssetId, BoundedVec::StringLimit>>; #[pallet::config] pub trait Config: frame_system::Config { @@ -61,6 +63,9 @@ pub mod pallet { /// The origin which can work with asset-registry. type RegistryOrigin: EnsureOrigin; + /// The origin which can update assets' detail. + type UpdateOrigin: EnsureOrigin; + /// Asset type type AssetId: Parameter + Member @@ -71,15 +76,6 @@ pub mod pallet { + MaxEncodedLen + TypeInfo; - /// Balance type - type Balance: Parameter - + Member - + AtLeast32BitUnsigned - + Default - + Copy - + MaybeSerializeDeserialize - + MaxEncodedLen; - /// Asset location type type AssetNativeLocation: Parameter + Member + Default + MaxEncodedLen; @@ -131,6 +127,13 @@ pub mod pallet { /// Location already registered with different asset LocationAlreadyRegistered, + + Forbidden, + } + + #[pallet::type_value] + pub fn DefaultNextAssetId() -> T::AssetId { + 1.into() } #[pallet::storage] @@ -139,8 +142,9 @@ pub mod pallet { pub type Assets = StorageMap<_, Twox64Concat, T::AssetId, AssetDetailsT, OptionQuery>; #[pallet::storage] + #[pallet::getter(fn next_asset_id)] /// Next available asset id. This is sequential id assigned for each new registered asset. - pub type NextAssetId = StorageValue<_, T::AssetId, ValueQuery>; + pub type NextAssetId = StorageValue<_, T::AssetId, ValueQuery, DefaultNextAssetId>; #[pallet::storage] #[pallet::getter(fn asset_ids)] @@ -162,9 +166,19 @@ pub mod pallet { #[allow(clippy::type_complexity)] #[pallet::genesis_config] pub struct GenesisConfig { - pub registered_assets: Vec<(Option>, T::Balance, Option)>, + //asset_id, name, existential deposit, symbol, decimals, is_sufficient + pub registered_assets: Vec<( + Option, + Option>, + Balance, + Option>, + Option, + bool, + )>, pub native_asset_name: Vec, - pub native_existential_deposit: T::Balance, + pub native_existential_deposit: Balance, + pub native_symbol: Vec, + pub native_decimals: u8, } #[cfg(feature = "std")] @@ -174,6 +188,8 @@ pub mod pallet { registered_assets: vec![], native_asset_name: b"HDX".to_vec(), native_existential_deposit: Default::default(), + native_symbol: b"HDX".to_vec(), + native_decimals: 12, } } } @@ -186,31 +202,57 @@ pub mod pallet { .map_err(|_| panic!("Invalid native asset name!")) .unwrap(); + let native_symbol = Pallet::::to_bounded_name(self.native_symbol.to_vec()) + .map_err(|_| panic!("Invalid native asset symbol!")) + .unwrap(); + AssetIds::::insert(&native_asset_name, T::NativeAssetId::get()); let details = AssetDetails { name: Some(native_asset_name), asset_type: AssetType::Token, existential_deposit: self.native_existential_deposit, - xcm_rate_limit: None, - metadata: None, + symbol: Some(native_symbol), + decimals: Some(self.native_decimals), + is_sufficient: true, }; Assets::::insert(T::NativeAssetId::get(), details); - self.registered_assets.iter().for_each(|(name, ed, id)| { - let bounded_name = if let Some(name) = name { - Some( - Pallet::::to_bounded_name(name.to_vec()) - .map_err(|_| panic!("Invalid asset name!")) - .unwrap(), - ) - } else { - None - }; - let _ = Pallet::::register_asset(bounded_name, AssetType::Token, *ed, *id, None, None) - .map_err(|_| panic!("Failed to register asset")); - }) + self.registered_assets + .iter() + .for_each(|(id, name, ed, symbol, decimals, is_sufficient)| { + let bounded_name = if let Some(name) = name { + Some( + Pallet::::to_bounded_name(name.to_vec()) + .map_err(|_| panic!("Invalid asset name!")) + .unwrap(), + ) + } else { + None + }; + let bounded_symbol = if let Some(symbol) = symbol { + Some( + Pallet::::to_bounded_name(symbol.to_vec()) + .map_err(|_| panic!("Invalid symbol!")) + .unwrap(), + ) + } else { + None + }; + + let details = AssetDetails { + name: bounded_name, + asset_type: AssetType::Token, + existential_deposit: *ed, + xcm_rate_limit: None, + symbol: bounded_symbol, + decimals: *decimals, + is_sufficient: *is_sufficient, + }; + let _ = Pallet::::do_register_asset(*id, details, None) + .map_err(|_| panic!("Failed to register asset")); + }) } } @@ -222,8 +264,10 @@ pub mod pallet { asset_id: T::AssetId, asset_name: Option>, asset_type: AssetType, - existential_deposit: T::Balance, - xcm_rate_limit: Option, + existential_deposit: Balance, + xcm_rate_limit: Option, + symbol: Option>, + decimals: Option, }, /// Asset was updated. @@ -231,14 +275,10 @@ pub mod pallet { asset_id: T::AssetId, asset_name: Option>, asset_type: AssetType, - existential_deposit: T::Balance, - xcm_rate_limit: Option, - }, - - /// Metadata set for an asset. - MetadataSet { - asset_id: T::AssetId, - metadata: Option, + existential_deposit: Balance, + xcm_rate_limit: Option, + symbol: Option>, + decimals: Option, }, /// Native location set for an asset. @@ -264,63 +304,42 @@ pub mod pallet { #[pallet::weight(::WeightInfo::register())] pub fn register( origin: OriginFor, + asset_id: Option, name: Option>, asset_type: AssetType, - existential_deposit: T::Balance, - asset_id: Option, - metadata: Option, + existential_deposit: Option, + symbol: Option>, + decimals: Option, location: Option, - xcm_rate_limit: Option, + xcm_rate_limit: Option, + is_sufficient: bool, ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; - let bounded_name = if let Some(n) = name { - let bounded_name = Self::to_bounded_name(n)?; - ensure!( - Self::asset_ids(&bounded_name).is_none(), - Error::::AssetAlreadyRegistered - ); - + let bounded_name = if let Some(name) = name { + let bounded_name = Self::to_bounded_name(name)?; Some(bounded_name) } else { None }; - let meta = if let Some(m) = metadata.as_ref() { - let symbol = Self::to_bounded_name(m.symbol.clone())?; - Some(AssetMetadata::new(symbol, m.decimals)) + let bounded_symbol = if let Some(symbol) = symbol { + Some(Self::to_bounded_name(symbol)?) } else { None }; - let asset_id = Self::register_asset( + let details = AssetDetails::new( bounded_name, asset_type, - existential_deposit, - asset_id, + existential_deposit.unwrap_or(DEFAULT_ED), + bounded_symbol, + decimals, xcm_rate_limit, - meta, - )?; - - if metadata.is_some() { - Self::deposit_event(Event::MetadataSet { asset_id, metadata }); - } - - if let Some(loc) = location { - ensure!(asset_id != T::NativeAssetId::get(), Error::::CannotUpdateLocation); - ensure!( - Self::location_assets(&loc).is_none(), - Error::::LocationAlreadyRegistered - ); - AssetLocations::::insert(asset_id, &loc); - LocationAssets::::insert(&loc, asset_id); - - Self::deposit_event(Event::LocationSet { - asset_id, - location: loc, - }); - } + is_sufficient, + ); + Self::do_register_asset(asset_id, details, location)?; Ok(()) } @@ -335,21 +354,36 @@ pub mod pallet { origin: OriginFor, asset_id: T::AssetId, name: Option>, - asset_type: AssetType, - existential_deposit: Option, - xcm_rate_limit: Option, - metadata: Option, + asset_type: Option>, + existential_deposit: Option, + xcm_rate_limit: Option, + is_sufficient: Option, + symbol: Option>, + decimals: Option, ) -> DispatchResult { - T::RegistryOrigin::ensure_origin(origin)?; + T::UpdateOrigin::ensure_origin(origin.clone())?; + + // let is_registry_origing = match T::UpdateOrigin::ensure_origin(origin.clone()) { + // Ok(_) => false, + // Err(e) => { + // T::RegistryOrigin::ensure_origin(origin)? + // + // true + // } + // } Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { - let mut detail = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; + let mut details = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; let new_bounded_name = if let Some(n) = name { let new_name = Self::to_bounded_name(n)?; ensure!(Self::asset_ids(&new_name).is_none(), Error::::AssetAlreadyRegistered); - if Some(new_name.clone()) != detail.name { + if let Some(old_name) = &details.name { + AssetIds::::remove(old_name); + } + + if Some(new_name.clone()) != details.name { AssetIds::::insert(&new_name, asset_id); } @@ -358,97 +392,42 @@ pub mod pallet { None }; - if let Some(old_name) = &detail.name { - AssetIds::::remove(old_name); - } - - detail.name = new_bounded_name.clone(); - detail.asset_type = asset_type; - detail.existential_deposit = existential_deposit.unwrap_or(detail.existential_deposit); - detail.xcm_rate_limit = xcm_rate_limit; - - Self::deposit_event(Event::Updated { - asset_id, - asset_name: new_bounded_name, - asset_type, - existential_deposit: detail.existential_deposit, - xcm_rate_limit: detail.xcm_rate_limit, - }); - - if let Some(meta) = metadata.as_ref() { - let symbol = Self::to_bounded_name(meta.symbol.clone())?; - detail.metadata = Some(AssetMetadata::new(symbol, meta.decimals)); - - Self::deposit_event(Event::MetadataSet { asset_id, metadata }); - } - - Ok(()) - }) - } - - /// Set metadata for an asset. - /// - /// - `asset_id`: Asset identifier. - /// - `symbol`: The exchange symbol for this asset. Limited in length by `StringLimit`. - /// - `decimals`: The number of decimals this asset uses to represent one unit. - /// - /// Emits `MetadataSet` event when successful. - #[pallet::call_index(2)] - #[pallet::weight(::WeightInfo::set_metadata())] - pub fn set_metadata(origin: OriginFor, asset_id: T::AssetId, metadata: Option) -> DispatchResult { - T::RegistryOrigin::ensure_origin(origin)?; - - Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { - let mut detail = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; - - let meta = if let Some(m) = metadata.as_ref() { - let symbol = Self::to_bounded_name(m.symbol.clone())?; - Some(AssetMetadata::new(symbol, m.decimals)) + let bounded_symbol = if let Some(s) = symbol { + Some(Self::to_bounded_name(s)?) } else { None }; - detail.metadata = meta; + details.name = new_bounded_name.or(details.name.clone()); + details.asset_type = asset_type.unwrap_or(details.asset_type); + details.existential_deposit = existential_deposit.unwrap_or(details.existential_deposit); + details.xcm_rate_limit = details.xcm_rate_limit.or(xcm_rate_limit); + details.is_sufficient = is_sufficient.unwrap_or(details.is_sufficient); + details.symbol = bounded_symbol.or(details.symbol.clone()); + + if decimals.is_some() { + if details.decimals.is_none() { + details.decimals = decimals; + } else { + //Only highest origin can change decimal if it was set previously. + ensure!(T::RegistryOrigin::ensure_origin(origin).is_ok(), Error::::Forbidden); + details.decimals = decimals; + }; + } - Self::deposit_event(Event::MetadataSet { asset_id, metadata }); + Self::deposit_event(Event::Updated { + asset_id, + asset_name: details.name.clone(), + asset_type: details.asset_type, + existential_deposit: details.existential_deposit, + xcm_rate_limit: details.xcm_rate_limit, + symbol: details.symbol.clone(), + decimals: details.decimals, + }); Ok(()) }) } - - /// Set asset native location. - /// - /// Adds mapping between native location and local asset id and vice versa. - /// - /// Mainly used in XCM. - /// - /// Emits `LocationSet` event when successful. - #[pallet::call_index(3)] - #[pallet::weight(::WeightInfo::set_location())] - pub fn set_location( - origin: OriginFor, - asset_id: T::AssetId, - location: T::AssetNativeLocation, - ) -> DispatchResult { - T::RegistryOrigin::ensure_origin(origin)?; - - ensure!(asset_id != T::NativeAssetId::get(), Error::::CannotUpdateLocation); - ensure!(Self::assets(asset_id).is_some(), Error::::AssetNotRegistered); - ensure!( - Self::location_assets(&location).is_none(), - Error::::LocationAlreadyRegistered - ); - - if let Some(old_location) = AssetLocations::::take(asset_id) { - LocationAssets::::remove(&old_location); - } - AssetLocations::::insert(asset_id, &location); - LocationAssets::::insert(&location, asset_id); - - Self::deposit_event(Event::LocationSet { asset_id, location }); - - Ok(()) - } } } @@ -458,42 +437,37 @@ impl Pallet { name.try_into().map_err(|_| Error::::TooLong) } + fn do_set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { + ensure!( + Self::location_assets(&location).is_none(), + Error::::LocationAlreadyRegistered + ); + + AssetLocations::::insert(asset_id, &location); + LocationAssets::::insert(&location, asset_id); + + Self::deposit_event(Event::LocationSet { asset_id, location }); + + Ok(()) + } + /// Register new asset. /// - /// Does not perform any check whether an asset for given name already exists. This has to be prior to calling this function. - pub fn register_asset( - name: Option>, - asset_type: AssetType, - existential_deposit: T::Balance, + /// This function checks if asset name is already used. + fn do_register_asset( selected_asset_id: Option, - xcm_rate_limit: Option, - metadata: Option>>, + details: AssetDetails>, + location: Option, ) -> Result { - let asset_id = if let Some(selected_id) = selected_asset_id { - ensure!( - selected_id < T::SequentialIdStartAt::get(), - Error::::NotInReservedRange - ); + let asset_id = if let Some(id) = selected_asset_id { + ensure!(id < T::SequentialIdStartAt::get(), Error::::NotInReservedRange); - ensure!( - !Assets::::contains_key(selected_id), - Error::::AssetAlreadyRegistered - ); + ensure!(!Assets::::contains_key(id), Error::::AssetAlreadyRegistered); - selected_id + id } else { NextAssetId::::mutate(|value| -> Result { - // Check if current id does not clash with CORE ASSET ID. - // If yes, just skip it and use next one, otherwise use it. - // Note: this way we prevent accidental clashes with native asset id, so no need to set next asset id to be > next asset id - let next_asset_id = if *value == T::NativeAssetId::get() { - value - .checked_add(&T::AssetId::from(1)) - .ok_or(Error::::NoIdAvailable)? - } else { - *value - }; - + let next_asset_id = *value; *value = next_asset_id .checked_add(&T::AssetId::from(1)) .ok_or(Error::::NoIdAvailable)?; @@ -504,29 +478,26 @@ impl Pallet { })? }; - if let Some(n) = name.clone() { - AssetIds::::insert(&n, asset_id); + Assets::::insert(asset_id, &details); + if let Some(name) = details.name.as_ref() { + ensure!(!AssetIds::::contains_key(name), Error::::AssetAlreadyRegistered); + AssetIds::::insert(name, asset_id); } - let details = AssetDetails { - name: name.clone(), - asset_type, - existential_deposit, - xcm_rate_limit, - metadata, - }; - - // Store the details - Assets::::insert(asset_id, details); - Self::deposit_event(Event::Registered { asset_id, - asset_name: name, - asset_type, - existential_deposit, - xcm_rate_limit, + asset_name: details.name, + asset_type: details.asset_type, + existential_deposit: details.existential_deposit, + xcm_rate_limit: details.xcm_rate_limit, + symbol: details.symbol, + decimals: details.decimals, }); + if let Some(loc) = location { + Self::do_set_location(asset_id, loc)?; + } + Ok(asset_id) } @@ -534,20 +505,26 @@ impl Pallet { pub fn get_or_create_asset( name: Vec, asset_type: AssetType, - existential_deposit: T::Balance, + existential_deposit: Balance, asset_id: Option, + is_sufficient: bool, ) -> Result { let bounded_name: BoundedVec = Self::to_bounded_name(name)?; if let Some(asset_id) = AssetIds::::get(&bounded_name) { Ok(asset_id) } else { - Self::register_asset( - Some(bounded_name), - asset_type, - existential_deposit, + Self::do_register_asset( asset_id, - None, + AssetDetails::new( + Some(bounded_name), + asset_type, + existential_deposit, + None, + None, + None, + is_sufficient, + ), None, ) } @@ -564,7 +541,7 @@ impl Pallet { } } -impl Registry, T::Balance, DispatchError> for Pallet { +impl Registry, Balance, DispatchError> for Pallet { fn exists(asset_id: T::AssetId) -> bool { Assets::::contains_key(asset_id) } @@ -584,12 +561,16 @@ impl Registry, T::Balance, DispatchError> for Pal Ok(asset_details.asset_type.into()) } - fn create_asset(name: &Vec, existential_deposit: T::Balance) -> Result { - Self::get_or_create_asset(name.clone(), AssetType::Token, existential_deposit, None) + fn create_asset( + name: &Vec, + existential_deposit: Balance, + is_sufficient: bool, + ) -> Result { + Self::get_or_create_asset(name.clone(), AssetType::Token, existential_deposit, None, is_sufficient) } } -impl ShareTokenRegistry, T::Balance, DispatchError> for Pallet { +impl ShareTokenRegistry, Balance, DispatchError> for Pallet { fn retrieve_shared_asset(name: &Vec, _assets: &[T::AssetId]) -> Result { Self::retrieve_asset(name) } @@ -597,7 +578,8 @@ impl ShareTokenRegistry, T::Balance, DispatchErro fn create_shared_asset( name: &Vec, assets: &[T::AssetId], - existential_deposit: T::Balance, + existential_deposit: Balance, + is_sufficient: bool, ) -> Result { ensure!(assets.len() == 2, Error::::InvalidSharedAssetLen); Self::get_or_create_asset( @@ -605,21 +587,21 @@ impl ShareTokenRegistry, T::Balance, DispatchErro AssetType::PoolShare(assets[0], assets[1]), existential_deposit, None, + is_sufficient, ) } } use orml_traits::GetByKey; -use sp_arithmetic::traits::Bounded; // Return Existential deposit of an asset -impl GetByKey for Pallet { - fn get(k: &T::AssetId) -> T::Balance { +impl GetByKey for Pallet { + fn get(k: &T::AssetId) -> Balance { if let Some(details) = Self::assets(k) { details.existential_deposit } else { // Asset does not exist - not supported - T::Balance::max_value() + Balance::max_value() } } } @@ -628,26 +610,40 @@ impl GetByKey for Pallet { pub struct XcmRateLimitsInRegistry(PhantomData); /// Allows querying the XCM rate limit for an asset by its id. /// Both a unknown asset and an unset rate limit will return `None`. -impl GetByKey> for XcmRateLimitsInRegistry { - fn get(k: &T::AssetId) -> Option { +impl GetByKey> for XcmRateLimitsInRegistry { + fn get(k: &T::AssetId) -> Option { Pallet::::assets(k).and_then(|details| details.xcm_rate_limit) } } -impl CreateRegistry for Pallet { +impl CreateRegistry for Pallet { type Error = DispatchError; fn create_asset( name: Option<&[u8]>, kind: AssetKind, - existential_deposit: T::Balance, + existential_deposit: Balance, + is_sufficient: bool, + //TODO: add location ) -> Result { - let bounded_name = if let Some(name) = name { - Some(Self::to_bounded_name(name.to_vec())?) + let bounded_name = if let Some(n) = name { + Some(Self::to_bounded_name(n.to_vec())?) } else { None }; - Pallet::::register_asset(bounded_name, kind.into(), existential_deposit, None, None, None) + Pallet::::do_register_asset( + None, + AssetDetails::new( + bounded_name, + kind.into(), + existential_deposit, + None, + None, + None, + is_sufficient, + ), + None, + ) } } diff --git a/pallets/asset-registry/src/types.rs b/pallets/asset-registry/src/types.rs index e99fa0e10..31fda8675 100644 --- a/pallets/asset-registry/src/types.rs +++ b/pallets/asset-registry/src/types.rs @@ -17,7 +17,8 @@ use frame_support::pallet_prelude::*; use scale_info::TypeInfo; -use sp_std::vec::Vec; + +pub type Balance = u128; use hydradx_traits::AssetKind; #[cfg(feature = "std")] @@ -61,7 +62,7 @@ impl From> for AssetKind { #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct AssetDetails { +pub struct AssetDetails { /// The name of this asset. Limited in length by `StringLimit`. pub name: Option, @@ -69,29 +70,35 @@ pub struct AssetDetails { pub existential_deposit: Balance, - pub xcm_rate_limit: Option, - - pub metadata: Option>, -} - -#[derive(Clone, Encode, Decode, Eq, PartialEq, Default, RuntimeDebug, TypeInfo, MaxEncodedLen, Copy)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct AssetMetadata { /// The ticker symbol for this asset. Limited in length by `StringLimit`. - pub(super) symbol: BoundedString, + pub symbol: Option, + /// The number of decimals this asset uses to represent one unit. - pub(super) decimals: u8, -} + pub decimals: Option, -impl AssetMetadata { - pub fn new(symbol: BoundedString, decimals: u8) -> Self { - Self { symbol, decimals } - } + pub xcm_rate_limit: Option, + + pub is_sufficient: bool, } -#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct Metadata { - pub(super) symbol: Vec, - pub(super) decimals: u8, +impl AssetDetails { + pub fn new( + name: Option, + asset_type: AssetType, + existential_deposit: Balance, + symbol: Option, + decimals: Option, + xcm_rate_limit: Option, + is_sufficient: bool, + ) -> Self { + Self { + name, + asset_type, + existential_deposit, + symbol, + decimals, + xcm_rate_limit, + is_sufficient, + } + } } diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 734ead69a..896b5ec35 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -7,13 +7,17 @@ pub trait Registry { fn retrieve_asset_type(asset_id: AssetId) -> Result; - fn create_asset(name: &AssetName, existential_deposit: Balance) -> Result; + fn create_asset(name: &AssetName, existential_deposit: Balance, is_sufficient: bool) -> Result; - fn get_or_create_asset(name: AssetName, existential_deposit: Balance) -> Result { + fn get_or_create_asset( + name: AssetName, + existential_deposit: Balance, + is_sufficient: bool, + ) -> Result { if let Ok(asset_id) = Self::retrieve_asset(&name) { Ok(asset_id) } else { - Self::create_asset(&name, existential_deposit) + Self::create_asset(&name, existential_deposit, is_sufficient) } } } @@ -26,17 +30,19 @@ pub trait ShareTokenRegistry: Registry Result; fn get_or_create_shared_asset( name: AssetName, assets: Vec, existential_deposit: Balance, + is_sufficient: bool, ) -> Result { if let Ok(asset_id) = Self::retrieve_shared_asset(&name, &assets) { Ok(asset_id) } else { - Self::create_shared_asset(&name, &assets, existential_deposit) + Self::create_shared_asset(&name, &assets, existential_deposit, is_sufficient) } } } @@ -52,8 +58,12 @@ pub enum AssetKind { pub trait CreateRegistry { type Error; - fn create_asset(name: Option<&[u8]>, kind: AssetKind, existential_deposit: Balance) - -> Result; + fn create_asset( + name: Option<&[u8]>, + kind: AssetKind, + existential_deposit: Balance, + is_sufficient: bool, + ) -> Result; } // Deprecated. From f557c86b529249f309c627fe82061691a1889d39 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 28 Aug 2023 14:28:40 +0200 Subject: [PATCH 06/93] asset-registry: added tests for update and minor fixes --- pallets/asset-registry/src/lib.rs | 30 +- pallets/asset-registry/src/tests/mock.rs | 25 +- pallets/asset-registry/src/tests/mod.rs | 2 +- pallets/asset-registry/src/tests/update.rs | 354 +++++++++++++++++++++ 4 files changed, 394 insertions(+), 17 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 773d06193..01361cc62 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -142,7 +142,6 @@ pub mod pallet { pub type Assets = StorageMap<_, Twox64Concat, T::AssetId, AssetDetailsT, OptionQuery>; #[pallet::storage] - #[pallet::getter(fn next_asset_id)] /// Next available asset id. This is sequential id assigned for each new registered asset. pub type NextAssetId = StorageValue<_, T::AssetId, ValueQuery, DefaultNextAssetId>; @@ -268,6 +267,7 @@ pub mod pallet { xcm_rate_limit: Option, symbol: Option>, decimals: Option, + is_sufficient: bool, }, /// Asset was updated. @@ -279,6 +279,7 @@ pub mod pallet { xcm_rate_limit: Option, symbol: Option>, decimals: Option, + is_sufficient: bool, }, /// Native location set for an asset. @@ -361,16 +362,14 @@ pub mod pallet { symbol: Option>, decimals: Option, ) -> DispatchResult { - T::UpdateOrigin::ensure_origin(origin.clone())?; + let is_registry_origing = match T::UpdateOrigin::ensure_origin(origin.clone()) { + Ok(_) => false, + Err(_) => { + T::RegistryOrigin::ensure_origin(origin)?; - // let is_registry_origing = match T::UpdateOrigin::ensure_origin(origin.clone()) { - // Ok(_) => false, - // Err(e) => { - // T::RegistryOrigin::ensure_origin(origin)? - // - // true - // } - // } + true + } + }; Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { let mut details = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; @@ -410,7 +409,7 @@ pub mod pallet { details.decimals = decimals; } else { //Only highest origin can change decimal if it was set previously. - ensure!(T::RegistryOrigin::ensure_origin(origin).is_ok(), Error::::Forbidden); + ensure!(is_registry_origing, Error::::Forbidden); details.decimals = decimals; }; } @@ -423,6 +422,7 @@ pub mod pallet { xcm_rate_limit: details.xcm_rate_limit, symbol: details.symbol.clone(), decimals: details.decimals, + is_sufficient: details.is_sufficient, }); Ok(()) @@ -432,12 +432,17 @@ pub mod pallet { } impl Pallet { + pub fn next_asset_id() -> Option { + NextAssetId::::get().checked_add(&T::SequentialIdStartAt::get()) + } + /// Convert Vec to BoundedVec so it respects the max set limit, otherwise return TooLong error pub fn to_bounded_name(name: Vec) -> Result, Error> { name.try_into().map_err(|_| Error::::TooLong) } - fn do_set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { + //Note: this is used in the tests. + pub(crate) fn do_set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { ensure!( Self::location_assets(&location).is_none(), Error::::LocationAlreadyRegistered @@ -492,6 +497,7 @@ impl Pallet { xcm_rate_limit: details.xcm_rate_limit, symbol: details.symbol, decimals: details.decimals, + is_sufficient: details.is_sufficient, }); if let Some(loc) = location { diff --git a/pallets/asset-registry/src/tests/mock.rs b/pallets/asset-registry/src/tests/mock.rs index 0c2fc488b..f3c46d5bb 100644 --- a/pallets/asset-registry/src/tests/mock.rs +++ b/pallets/asset-registry/src/tests/mock.rs @@ -96,8 +96,8 @@ pub struct AssetLocation(pub MultiLocation); impl pallet_asset_registry::Config for Test { type RuntimeEvent = RuntimeEvent; type RegistryOrigin = frame_system::EnsureRoot; + type UpdateOrigin = frame_system::EnsureSigned; type AssetId = u32; - type Balance = Balance; type AssetNativeLocation = AssetLocation; type StringLimit = RegistryStringLimit; type SequentialIdStartAt = SequentialIdStart; @@ -107,12 +107,29 @@ impl pallet_asset_registry::Config for Test { #[derive(Default)] pub struct ExtBuilder { - registered_assets: Vec<(Option>, Balance, Option)>, + registered_assets: Vec<( + Option, + Option>, + Balance, + Option>, + Option, + bool, + )>, } impl ExtBuilder { - pub fn with_assets(mut self, asset_ids: Vec<(Option>, Balance, Option)>) -> Self { - self.registered_assets = asset_ids; + pub fn with_assets( + mut self, + assets: Vec<( + Option, + Option>, + Balance, + Option>, + Option, + bool, + )>, + ) -> Self { + self.registered_assets = assets; self } diff --git a/pallets/asset-registry/src/tests/mod.rs b/pallets/asset-registry/src/tests/mod.rs index f85c48bcb..279bdd371 100644 --- a/pallets/asset-registry/src/tests/mod.rs +++ b/pallets/asset-registry/src/tests/mod.rs @@ -4,7 +4,7 @@ use crate::*; use frame_support::{assert_noop, assert_ok}; pub(crate) mod mock; -mod register; +//mod register; mod update; #[macro_export] diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index e69de29bb..c72e6c7ae 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -0,0 +1,354 @@ +use super::*; + +use crate::types::AssetType; +use mock::Registry; +use polkadot_xcm::v3::{ + Junction::{self, Parachain}, + Junctions::X2, + MultiLocation, +}; +use pretty_assertions::assert_eq; + +#[test] +fn update_should_work_when_asset_exists() { + let old_asset_name = b"Tkn2".to_vec(); + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(old_asset_name.clone()), 1 * UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + let name = b"New Tkn 2".to_vec(); + let ed = 10_000 * UNIT; + let xcm_rate_limit = 463; + let symbol = b"nTkn2".to_vec(); + let decimals = 23; + let is_sufficient = false; + + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + + //Act + assert_ok!(Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + )); + + //Assert + let bounded_name = Pallet::::to_bounded_name(name).unwrap(); + let bounded_symbol = Pallet::::to_bounded_name(symbol).unwrap(); + assert_eq!( + Registry::assets(asset_id), + Some(AssetDetails { + name: Some(bounded_name.clone()), + asset_type: AssetType::External, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: Some(bounded_symbol.clone()), + decimals: Some(decimals), + is_sufficient: false + }) + ); + + //NOTE: location should't change + assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); + + let old_bounded_name = Pallet::::to_bounded_name(old_asset_name).unwrap(); + assert_eq!(Registry::asset_ids(bounded_name.clone()).unwrap(), asset_id); + assert!(Registry::asset_ids(old_bounded_name).is_none()); + + assert_last_event!(Event::::Updated { + asset_id, + asset_name: Some(bounded_name), + asset_type: AssetType::External, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + decimals: Some(decimals), + symbol: Some(bounded_symbol), + is_sufficient, + } + .into()); + }); +} + +#[test] +fn update_should_not_change_values_when_param_is_none() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + + let details_0 = Registry::assets(asset_id).unwrap(); + + //Act + assert_ok!(Registry::update( + RuntimeOrigin::root(), + asset_id, + None, + None, + None, + None, + None, + None, + None, + )); + + //Assert + assert_eq!(Registry::assets(asset_id).unwrap(), details_0); + + let old_bounded_name = Pallet::::to_bounded_name(b"Tkn2".to_vec()).unwrap(); + assert_eq!(Registry::asset_ids(old_bounded_name.clone()).unwrap(), asset_id); + + //NOTE: location should't change + assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); + + assert_last_event!(Event::::Updated { + asset_id, + asset_name: details_0.name, + asset_type: details_0.asset_type, + existential_deposit: details_0.existential_deposit, + xcm_rate_limit: details_0.xcm_rate_limit, + decimals: details_0.decimals, + symbol: details_0.symbol, + is_sufficient: details_0.is_sufficient, + } + .into()); + }); +} + +#[test] +fn update_origin_should_set_decimals_if_its_none() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + let decimals = 52; + + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + + let details_0 = Registry::assets(asset_id).unwrap(); + + //NOTE: update origin is ste to ensure_signed + //Act + assert_ok!(Registry::update( + RuntimeOrigin::signed(ALICE), + asset_id, + None, + None, + None, + None, + None, + None, + Some(decimals), + )); + + //Assert + assert_eq!( + Registry::assets(asset_id), + Some(AssetDetails { + name: details_0.name.clone(), + asset_type: details_0.asset_type, + existential_deposit: details_0.existential_deposit, + xcm_rate_limit: details_0.xcm_rate_limit, + symbol: details_0.symbol.clone(), + decimals: Some(decimals), + is_sufficient: details_0.is_sufficient + }) + ); + + assert_last_event!(Event::::Updated { + asset_id, + asset_name: details_0.name, + asset_type: details_0.asset_type, + existential_deposit: details_0.existential_deposit, + xcm_rate_limit: details_0.xcm_rate_limit, + decimals: Some(decimals), + symbol: details_0.symbol, + is_sufficient: details_0.is_sufficient, + } + .into()); + }); +} + +#[test] +fn update_origin_should_not_chane_decimals_if_its_some() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, Some(3), true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + let decimals = 52; + + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + + //NOTE: update origin is ste to ensure_signed + //Act & assert + assert_noop!( + Registry::update( + RuntimeOrigin::signed(ALICE), + asset_id, + None, + None, + None, + None, + None, + None, + Some(decimals), + ), + Error::::Forbidden + ); + }); +} + +#[test] +fn create_origin_should_always_set_decimals() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, Some(3), true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + let decimals = 52; + + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + + let details_0 = Registry::assets(asset_id).unwrap(); + + //NOTE: update origin is ste to ensure_signed + //Act + assert_ok!(Registry::update( + RuntimeOrigin::root(), + asset_id, + None, + None, + None, + None, + None, + None, + Some(decimals), + )); + + assert_ok!(Registry::update( + RuntimeOrigin::root(), + asset_id, + None, + None, + None, + None, + None, + None, + Some(u8::max_value()), + )); + + + //Assert + assert_eq!( + Registry::assets(asset_id), + Some(AssetDetails { + name: details_0.name.clone(), + asset_type: details_0.asset_type, + existential_deposit: details_0.existential_deposit, + xcm_rate_limit: details_0.xcm_rate_limit, + symbol: details_0.symbol.clone(), + decimals: Some(u8::max_value()), + is_sufficient: details_0.is_sufficient + }) + ); + + assert_last_event!(Event::::Updated { + asset_id, + asset_name: details_0.name, + asset_type: details_0.asset_type, + existential_deposit: details_0.existential_deposit, + xcm_rate_limit: details_0.xcm_rate_limit, + decimals: Some(u8::max_value()), + symbol: details_0.symbol, + is_sufficient: details_0.is_sufficient, + } + .into()); + }); +} + +#[test] +fn update_should_fail_when_name_is_already_used() { + let old_asset_name = b"Tkn2".to_vec(); + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(old_asset_name.clone()), 1 * UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + let name = b"Tkn3".to_vec(); + let ed = 10_000 * UNIT; + let xcm_rate_limit = 463; + let symbol = b"nTkn2".to_vec(); + let decimals = 23; + let is_sufficient = false; + + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + + //Act + assert_noop!(Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + ),Error::::AssetAlreadyRegistered); + }); +} From 9aec80023e5af31ee0c94f7a754f88b965ec01d2 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 28 Aug 2023 15:23:08 +0200 Subject: [PATCH 07/93] asset-registry: added register() tests --- pallets/asset-registry/src/lib.rs | 2 +- pallets/asset-registry/src/tests/mod.rs | 2 +- pallets/asset-registry/src/tests/register.rs | 657 ++++++------------- pallets/asset-registry/src/tests/update.rs | 28 +- 4 files changed, 227 insertions(+), 462 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 01361cc62..b36a99c08 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -441,7 +441,7 @@ impl Pallet { name.try_into().map_err(|_| Error::::TooLong) } - //Note: this is used in the tests. + //Note: this is used in the tests. pub(crate) fn do_set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { ensure!( Self::location_assets(&location).is_none(), diff --git a/pallets/asset-registry/src/tests/mod.rs b/pallets/asset-registry/src/tests/mod.rs index 279bdd371..f85c48bcb 100644 --- a/pallets/asset-registry/src/tests/mod.rs +++ b/pallets/asset-registry/src/tests/mod.rs @@ -4,7 +4,7 @@ use crate::*; use frame_support::{assert_noop, assert_ok}; pub(crate) mod mock; -//mod register; +mod register; mod update; #[macro_export] diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index 7b6d15776..d7776083e 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -1,7 +1,8 @@ use super::*; -use crate::types::{AssetType, Metadata}; -use mock::Registry; +use crate::types::AssetType; +use frame_support::error::BadOrigin; +use mock::{AssetId, Registry}; use polkadot_xcm::v3::{ Junction::{self, Parachain}, Junctions::X2, @@ -14,12 +15,11 @@ fn register_should_work_when_all_params_are_provided() { ExtBuilder::default().build().execute_with(|| { let asset_id = 1; let name = b"Test asset".to_vec(); - let metadata = Metadata { - symbol: b"TKN".to_vec(), - decimals: 12, - }; + let symbol = b"TKN".to_vec(); + let decimals = 12; let xcm_rate_limit = 1_000; - let existential_deposit = 10_000; + let ed = 10_000; + let is_sufficient = true; let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); @@ -27,28 +27,30 @@ fn register_should_work_when_all_params_are_provided() { //Act assert_ok!(Registry::register( RuntimeOrigin::root(), + Some(asset_id), Some(name.clone()), AssetType::Token, - existential_deposit, - Some(asset_id), - Some(metadata.clone()), + Some(ed), + Some(symbol.clone()), + Some(decimals), Some(asset_location.clone()), - Some(xcm_rate_limit) + Some(xcm_rate_limit), + is_sufficient )); //Assert let bounded_name = Pallet::::to_bounded_name(name).unwrap(); + let bounded_symbol = Pallet::::to_bounded_name(symbol).unwrap(); assert_eq!( Registry::assets(asset_id), Some(AssetDetails { name: Some(bounded_name.clone()), asset_type: AssetType::Token, - existential_deposit, + existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - metadata: Some(AssetMetadata { - symbol: Registry::to_bounded_name(metadata.symbol.clone()).unwrap(), - decimals: metadata.decimals - }) + symbol: Some(bounded_symbol.clone()), + decimals: Some(decimals), + is_sufficient }) ); @@ -62,16 +64,11 @@ fn register_should_work_when_all_params_are_provided() { asset_id, asset_name: Some(bounded_name), asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: Some(xcm_rate_limit) - } - .into() - )); - - assert!(has_event( - Event::::MetadataSet { - asset_id, - metadata: Some(metadata) + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: Some(bounded_symbol), + decimals: Some(decimals), + is_sufficient } .into() )); @@ -87,217 +84,49 @@ fn register_should_work_when_all_params_are_provided() { } #[test] -fn register_should_work_when_asset_id_is_non_provided() { +fn register_should_work_when_only_required_params_were_provided() { ExtBuilder::default().build().execute_with(|| { - let name = b"Test asset".to_vec(); - let metadata = Metadata { - symbol: b"TKN".to_vec(), - decimals: 12, - }; - let xcm_rate_limit = 1_000; - let existential_deposit = 1 * UNIT; - - let expected_asset_id = crate::NextAssetId::::get() + ::SequentialIdStartAt::get() + 1; - let key = Junction::from(BoundedVec::try_from(expected_asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + let expected_id = Pallet::::next_asset_id().unwrap(); + let is_sufficient = true; //Act assert_ok!(Registry::register( RuntimeOrigin::root(), - Some(name.clone()), - AssetType::Token, - existential_deposit, None, - Some(metadata.clone()), - Some(asset_location.clone()), - Some(xcm_rate_limit) - )); - - //Assert - let bounded_name = Pallet::::to_bounded_name(name).unwrap(); - assert_eq!( - Registry::assets(expected_asset_id), - Some(AssetDetails { - name: Some(bounded_name.clone()), - asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: Some(xcm_rate_limit), - metadata: Some(AssetMetadata { - symbol: Registry::to_bounded_name(metadata.symbol.clone()).unwrap(), - decimals: metadata.decimals - }) - }) - ); - - assert_eq!(Registry::asset_ids(bounded_name.clone()), Some(expected_asset_id)); - - assert_eq!( - Registry::location_assets(asset_location.clone()), - Some(expected_asset_id) - ); - assert_eq!(Registry::locations(expected_asset_id), Some(asset_location.clone())); - - assert!(has_event( - Event::::Registered { - asset_id: expected_asset_id, - asset_name: Some(bounded_name), - asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: Some(xcm_rate_limit) - } - .into() - )); - - assert!(has_event( - Event::::MetadataSet { - asset_id: expected_asset_id, - metadata: Some(metadata) - } - .into() - )); - - assert!(has_event( - Event::::LocationSet { - asset_id: expected_asset_id, - location: asset_location - } - .into() - )); - }); -} - -#[test] -fn register_should_work_when_metadata_is_not_provided() { - ExtBuilder::default().build().execute_with(|| { - let name = b"Test asset".to_vec(); - let xcm_rate_limit = 1_000; - let existential_deposit = 1 * UNIT; - - let expected_asset_id = crate::NextAssetId::::get() + ::SequentialIdStartAt::get() + 1; - let key = Junction::from(BoundedVec::try_from(expected_asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - - //Act - assert_ok!(Registry::register( - RuntimeOrigin::root(), - Some(name.clone()), + None, AssetType::Token, - existential_deposit, None, None, - Some(asset_location.clone()), - Some(xcm_rate_limit) - )); - - //Assert - let bounded_name = Pallet::::to_bounded_name(name).unwrap(); - assert_eq!( - Registry::assets(expected_asset_id), - Some(AssetDetails { - name: Some(bounded_name.clone()), - asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: Some(xcm_rate_limit), - metadata: None, - }) - ); - - assert_eq!(Registry::asset_ids(bounded_name.clone()), Some(expected_asset_id)); - - assert_eq!( - Registry::location_assets(asset_location.clone()), - Some(expected_asset_id) - ); - assert_eq!(Registry::locations(expected_asset_id), Some(asset_location.clone())); - - assert!(has_event( - Event::::Registered { - asset_id: expected_asset_id, - asset_name: Some(bounded_name), - asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: Some(xcm_rate_limit) - } - .into() - )); - - assert!(!has_event( - Event::::MetadataSet { - asset_id: expected_asset_id, - metadata: None - } - .into() - )); - - assert!(has_event( - Event::::LocationSet { - asset_id: expected_asset_id, - location: asset_location - } - .into() - )); - }); -} - -#[test] -fn register_should_work_when_location_is_not_provided() { - ExtBuilder::default().build().execute_with(|| { - let asset_id = 1; - let name = b"Test asset".to_vec(); - let metadata = Metadata { - symbol: b"TKN".to_vec(), - decimals: 12, - }; - let xcm_rate_limit = 1_000; - let existential_deposit = 10_000; - - //Act - assert_ok!(Registry::register( - RuntimeOrigin::root(), - Some(name.clone()), - AssetType::Token, - existential_deposit, - Some(asset_id), - Some(metadata.clone()), None, - Some(xcm_rate_limit) + None, + None, + is_sufficient )); //Assert - let bounded_name = Pallet::::to_bounded_name(name).unwrap(); assert_eq!( - Registry::assets(asset_id), + Registry::assets(expected_id), Some(AssetDetails { - name: Some(bounded_name.clone()), + name: None, asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: Some(xcm_rate_limit), - metadata: Some(AssetMetadata { - symbol: Registry::to_bounded_name(metadata.symbol.clone()).unwrap(), - decimals: metadata.decimals - }) + existential_deposit: 1, + xcm_rate_limit: None, + symbol: None, + decimals: None, + is_sufficient }) ); - assert_eq!(Registry::asset_ids(bounded_name.clone()), Some(asset_id)); - - assert_eq!(Registry::locations(asset_id), None); - assert!(has_event( Event::::Registered { - asset_id, - asset_name: Some(bounded_name), + asset_id: expected_id, + asset_name: None, asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: Some(xcm_rate_limit) - } - .into() - )); - - assert!(has_event( - Event::::MetadataSet { - asset_id, - metadata: Some(metadata) + existential_deposit: 1, + xcm_rate_limit: None, + symbol: None, + decimals: None, + is_sufficient } .into() )); @@ -305,110 +134,72 @@ fn register_should_work_when_location_is_not_provided() { } #[test] -fn register_should_work_when_xmc_rate_limit_is_not_provided() { +fn register_should_not_work_when_asset_id_is_not_from_reserved_range() { ExtBuilder::default().build().execute_with(|| { - let asset_id = 1; + let asset_id: AssetId = Pallet::::next_asset_id().unwrap(); let name = b"Test asset".to_vec(); - let metadata = Metadata { - symbol: b"TKN".to_vec(), - decimals: 12, - }; - let existential_deposit = 10_000; + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); //Act - assert_ok!(Registry::register( - RuntimeOrigin::root(), - Some(name.clone()), - AssetType::Token, - existential_deposit, - Some(asset_id), - Some(metadata.clone()), - Some(asset_location.clone()), - None - )); - - //Assert - let bounded_name = Pallet::::to_bounded_name(name).unwrap(); - assert_eq!( - Registry::assets(asset_id), - Some(AssetDetails { - name: Some(bounded_name.clone()), - asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: None, - metadata: Some(AssetMetadata { - symbol: Registry::to_bounded_name(metadata.symbol.clone()).unwrap(), - decimals: metadata.decimals - }) - }) + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + Error::::NotInReservedRange ); - - assert_eq!(Registry::asset_ids(bounded_name.clone()), Some(asset_id)); - - assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); - assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); - - assert!(has_event( - Event::::Registered { - asset_id, - asset_name: Some(bounded_name), - asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: None - } - .into() - )); - - assert!(has_event( - Event::::MetadataSet { - asset_id, - metadata: Some(metadata) - } - .into() - )); - - assert!(has_event( - Event::::LocationSet { - asset_id, - location: asset_location - } - .into() - )); }); } #[test] -fn register_should_fail_when_asset_name_is_already_used() { +fn register_should_not_work_when_asset_id_is_already_used() { ExtBuilder::default() - .with_assets(vec![(Some(b"Test asset".to_vec()), 1 * UNIT, Some(2))]) + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) .build() .execute_with(|| { let asset_id = 1; let name = b"Test asset".to_vec(); - let metadata = Metadata { - symbol: b"TKN".to_vec(), - decimals: 12, - }; + let symbol = b"TKN".to_vec(); + let decimals = 12; let xcm_rate_limit = 1_000; - let existential_deposit = 10_000; + let ed = 10_000; + let is_sufficient = true; let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - //Act & assert + //Act assert_noop!( Registry::register( RuntimeOrigin::root(), + Some(asset_id), Some(name.clone()), AssetType::Token, - existential_deposit, - Some(asset_id), - Some(metadata.clone()), + Some(ed), + Some(symbol.clone()), + Some(decimals), Some(asset_location.clone()), - Some(xcm_rate_limit) + Some(xcm_rate_limit), + is_sufficient ), Error::::AssetAlreadyRegistered ); @@ -416,34 +207,39 @@ fn register_should_fail_when_asset_name_is_already_used() { } #[test] -fn register_should_fail_when_asset_id_is_already_used() { +fn register_should_not_work_when_asset_name_is_already_used() { ExtBuilder::default() - .with_assets(vec![(Some(b"Test".to_vec()), 1 * UNIT, Some(2))]) + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) .build() .execute_with(|| { - let asset_id = 2; - let name = b"Test asset".to_vec(); - let metadata = Metadata { - symbol: b"TKN".to_vec(), - decimals: 12, - }; + let asset_id = 4; + let name = b"Tkn3".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; let xcm_rate_limit = 1_000; - let existential_deposit = 10_000; + let ed = 10_000; + let is_sufficient = true; let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - //Act & assert + //Act assert_noop!( Registry::register( RuntimeOrigin::root(), + Some(asset_id), Some(name.clone()), AssetType::Token, - existential_deposit, - Some(asset_id), - Some(metadata.clone()), + Some(ed), + Some(symbol.clone()), + Some(decimals), Some(asset_location.clone()), - Some(xcm_rate_limit) + Some(xcm_rate_limit), + is_sufficient ), Error::::AssetAlreadyRegistered ); @@ -451,161 +247,128 @@ fn register_should_fail_when_asset_id_is_already_used() { } #[test] -fn register_should_fail_when_origin_is_not_allowed() { - ExtBuilder::default().build().execute_with(|| { - let asset_id = 1; - let name = b"Test asset".to_vec(); - let metadata = Metadata { - symbol: b"TKN".to_vec(), - decimals: 12, - }; - let xcm_rate_limit = 1_000; - let existential_deposit = 10_000; - - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - - //Act - assert_noop!(Registry::register( - RuntimeOrigin::signed(ALICE), - Some(name.clone()), - AssetType::Token, - existential_deposit, - Some(asset_id), - Some(metadata.clone()), - Some(asset_location.clone()), - Some(xcm_rate_limit) - ), DispatchError::BadOrigin); - }); -} +fn register_should_not_work_when_asset_location_is_already_used() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) + .build() + .execute_with(|| { + //Arrange + let asset_id = 4; -#[test] -fn register_should_fail_when_origin_is_none() { - ExtBuilder::default().build().execute_with(|| { - let asset_id = 1; - let name = b"Test asset".to_vec(); - let metadata = Metadata { - symbol: b"TKN".to_vec(), - decimals: 12, - }; - let xcm_rate_limit = 1_000; - let existential_deposit = 10_000; + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::do_set_location(3, asset_location.clone()).unwrap(); - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + let name = b"Tkn4".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; - //Act - assert_noop!(Registry::register( - RuntimeOrigin::none(), - Some(name.clone()), - AssetType::Token, - existential_deposit, - Some(asset_id), - Some(metadata.clone()), - Some(asset_location.clone()), - Some(xcm_rate_limit) - ), DispatchError::BadOrigin); - }); + //Act + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + Error::::LocationAlreadyRegistered + ); + }); } #[test] -fn register_should_fail_when_provided_asset_id_is_not_from_reserved_range() { - ExtBuilder::default().build().execute_with(|| { - let asset_id = ::SequentialIdStartAt::get(); - let name = b"Test asset".to_vec(); - let metadata = Metadata { - symbol: b"TKN".to_vec(), - decimals: 12, - }; - let xcm_rate_limit = 1_000; - let existential_deposit = 10_000; - - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - - //Act - assert_noop!(Registry::register( - RuntimeOrigin::root(), - Some(name.clone()), - AssetType::Token, - existential_deposit, - Some(asset_id), - Some(metadata.clone()), - Some(asset_location.clone()), - Some(xcm_rate_limit) - ), Error::::NotInReservedRange); - }); -} +fn register_should_not_work_when_origin_is_none() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) + .build() + .execute_with(|| { + //Arrange + let asset_id = 4; -#[test] -fn register_should_fail_when_asset_name_is_too_long() { - ExtBuilder::default().build().execute_with(|| { - let asset_id = 1; - let name = b"Too long asset name".to_vec(); - let metadata = Metadata { - symbol: b"TKN".to_vec(), - decimals: 12, - }; - let xcm_rate_limit = 1_000; - let existential_deposit = 10_000; + let name = b"Tkn4".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - //Act - assert_noop!(Registry::register( - RuntimeOrigin::root(), - Some(name.clone()), - AssetType::Token, - existential_deposit, - Some(asset_id), - Some(metadata.clone()), - Some(asset_location.clone()), - Some(xcm_rate_limit) - ), Error::::TooLong); - }); + //Act + assert_noop!( + Registry::register( + RuntimeOrigin::none(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + BadOrigin + ); + }); } #[test] -fn register_should_work_when_only_required_params_are_provided() { - ExtBuilder::default().build().execute_with(|| { - let existential_deposit = 10_000; - let expected_asset_id = crate::NextAssetId::::get() + ::SequentialIdStartAt::get() + 1; - - //Act - assert_ok!(Registry::register( - RuntimeOrigin::root(), - None, - AssetType::Token, - existential_deposit, - None, - None, - None, - None)); +fn register_should_not_work_when_origin_is_not_allowed() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + ]) + .build() + .execute_with(|| { + //Arrange + let asset_id = 4; - //Assert - assert_eq!( - Registry::assets(expected_asset_id), - Some(AssetDetails { - name: None, - asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: None, - metadata: None, - }) - ); + let name = b"Tkn4".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; - assert_eq!(Registry::locations(expected_asset_id), None); + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - assert!(has_event( - Event::::Registered { - asset_id: expected_asset_id, - asset_name: None, - asset_type: AssetType::Token, - existential_deposit, - xcm_rate_limit: None - } - .into() - )); - }); + //Act + assert_noop!( + Registry::register( + RuntimeOrigin::signed(ALICE), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + BadOrigin + ); + }); } diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index c72e6c7ae..0786850c5 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -272,7 +272,7 @@ fn create_origin_should_always_set_decimals() { None, Some(decimals), )); - + assert_ok!(Registry::update( RuntimeOrigin::root(), asset_id, @@ -285,7 +285,6 @@ fn create_origin_should_always_set_decimals() { Some(u8::max_value()), )); - //Assert assert_eq!( Registry::assets(asset_id), @@ -339,16 +338,19 @@ fn update_should_fail_when_name_is_already_used() { Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); //Act - assert_noop!(Registry::update( - RuntimeOrigin::root(), - asset_id, - Some(name.clone()), - Some(AssetType::External), - Some(ed), - Some(xcm_rate_limit), - Some(is_sufficient), - Some(symbol.clone()), - Some(decimals), - ),Error::::AssetAlreadyRegistered); + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + ), + Error::::AssetAlreadyRegistered + ); }); } From 5763a8577e043906179d631f053feddfb0ab185c Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 28 Aug 2023 16:07:39 +0200 Subject: [PATCH 08/93] asset-registry: fix runtime and chain spec changes --- node/src/chain_spec/local.rs | 4 +- node/src/chain_spec/mod.rs | 11 ++++- pallets/bonds/src/lib.rs | 1 + runtime/hydradx/src/assets.rs | 4 +- runtime/hydradx/src/migrations.rs | 74 +------------------------------ 5 files changed, 16 insertions(+), 78 deletions(-) diff --git a/node/src/chain_spec/local.rs b/node/src/chain_spec/local.rs index ff1bfc095..4c2807ea1 100644 --- a/node/src/chain_spec/local.rs +++ b/node/src/chain_spec/local.rs @@ -81,8 +81,8 @@ pub fn parachain_config() -> Result { vec![], // registered assets vec![ - (b"KSM".to_vec(), 1_000u128, Some(1)), - (b"KUSD".to_vec(), 1_000u128, Some(2)), + (Some(1), Some(b"KSM".to_vec()), 1_000u128, None, None, false), + (Some(2), Some(b"KUSD".to_vec()), 1_000u128, None, None, false), ], // accepted assets vec![(1, Price::from_float(0.0000212)), (2, Price::from_float(0.000806))], diff --git a/node/src/chain_spec/mod.rs b/node/src/chain_spec/mod.rs index da280c343..44a7797e0 100644 --- a/node/src/chain_spec/mod.rs +++ b/node/src/chain_spec/mod.rs @@ -95,7 +95,14 @@ pub fn parachain_genesis( council_members: Vec, tech_committee_members: Vec, vesting_list: Vec<(AccountId, BlockNumber, BlockNumber, u32, Balance)>, - registered_assets: Vec<(Vec, Balance, Option)>, // (Asset name, Existential deposit, Chosen asset id) + registered_assets: Vec<( + Option, + Option>, + Balance, + Option>, + Option, + bool, + )>, // (asset_id, name, existential deposit, symbol, decimals, is_sufficient) accepted_assets: Vec<(AssetId, Price)>, // (Asset id, Fallback price) - asset which fee can be paid with token_balances: Vec<(AccountId, Vec<(AssetId, Balance)>)>, claims_data: Vec<(EthereumAddress, Balance)>, @@ -148,6 +155,8 @@ pub fn parachain_genesis( registered_assets: registered_assets.clone(), native_asset_name: TOKEN_SYMBOL.as_bytes().to_vec(), native_existential_deposit: NATIVE_EXISTENTIAL_DEPOSIT, + native_symbol: TOKEN_SYMBOL.as_bytes().to_vec(), + native_decimals: TOKEN_DECIMALS, }, multi_transaction_payment: MultiTransactionPaymentConfig { currencies: accepted_assets, diff --git a/pallets/bonds/src/lib.rs b/pallets/bonds/src/lib.rs index ea3c94339..d2ab671c3 100644 --- a/pallets/bonds/src/lib.rs +++ b/pallets/bonds/src/lib.rs @@ -248,6 +248,7 @@ pub mod pallet { None, AssetKind::Bond, ed, + false, )?; Bonds::::insert(bond_id, (asset_id, maturity)); diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index d0a739624..3fdd434ad 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -157,9 +157,9 @@ parameter_types! { impl pallet_asset_registry::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type RegistryOrigin = SuperMajorityTechCommittee; + type RegistryOrigin = EnsureRoot; + type UpdateOrigin = SuperMajorityTechCommittee; type AssetId = AssetId; - type Balance = Balance; type AssetNativeLocation = AssetLocation; type StringLimit = RegistryStrLimit; type SequentialIdStartAt = SequentialIdOffset; diff --git a/runtime/hydradx/src/migrations.rs b/runtime/hydradx/src/migrations.rs index 020cbfcd1..8846e7c53 100644 --- a/runtime/hydradx/src/migrations.rs +++ b/runtime/hydradx/src/migrations.rs @@ -1,11 +1,6 @@ use super::*; -use sp_std::marker::PhantomData; -use frame_support::{ - log, migration::storage_key_iter, pallet_prelude::*, traits::OnRuntimeUpgrade, weights::Weight, StoragePrefixedMap, -}; -use pallet_asset_registry::{AssetLocations, LocationAssets}; -use polkadot_xcm::v3::MultiLocation; +use frame_support::{log, traits::OnRuntimeUpgrade, weights::Weight}; pub struct OnRuntimeUpgradeMigration; impl OnRuntimeUpgrade for OnRuntimeUpgradeMigration { @@ -62,70 +57,3 @@ impl OnRuntimeUpgrade for OnRuntimeUpgradeMigration { Ok(()) } } - -#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo)] -pub struct AssetLocationV2(pub polkadot_xcm::v2::MultiLocation); - -pub struct MigrateRegistryLocationToV3(PhantomData); -impl OnRuntimeUpgrade for MigrateRegistryLocationToV3 -where - AssetLocation: Into, -{ - fn on_runtime_upgrade() -> Weight { - log::info!( - target: "asset-registry", - "MigrateRegistryLocationToV3::on_runtime_upgrade: migrating asset locations to v3" - ); - - let mut weight: Weight = Weight::zero(); - - AssetLocations::::translate(|_asset_id, old_location: AssetLocationV2| { - weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); - let new_multi_loc: MultiLocation = old_location.0.try_into().expect("xcm::v1::MultiLocation"); - let new_location: T::AssetNativeLocation = AssetLocation(new_multi_loc).into(); - Some(new_location) - }); - - let module_prefix = LocationAssets::::module_prefix(); - let storage_prefix = LocationAssets::::storage_prefix(); - let old_data = storage_key_iter::(module_prefix, storage_prefix) - .drain() - .collect::>(); - for (old_location, asset_id) in old_data { - weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); - let new_multi_loc: MultiLocation = old_location.0.try_into().expect("xcm::v1::MultiLocation"); - let new_location: T::AssetNativeLocation = AssetLocation(new_multi_loc).into(); - LocationAssets::::insert(new_location, asset_id); - } - weight - } -} - -pub struct XcmRateLimitMigration; -impl OnRuntimeUpgrade for XcmRateLimitMigration { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, &'static str> { - frame_support::log::info!("PreMigrate Asset Registry Pallet start"); - pallet_asset_registry::migration::v1::pre_migrate::(); - frame_support::log::info!("PreMigrate Asset Registry Pallet end"); - - Ok(vec![]) - } - - fn on_runtime_upgrade() -> Weight { - log::info!( - target: "runtime::asset-registry", - "XcmRateLimitMigration::on_runtime_upgrade: migrating asset details to include xcm rate limit" - ); - - pallet_asset_registry::migration::v1::migrate::() - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_state: Vec) -> Result<(), &'static str> { - frame_support::log::info!("PostMigrate Asset Registry Pallet start"); - pallet_asset_registry::migration::v1::post_migrate::(); - frame_support::log::info!("PostMigrate Asset Registry Pallet end"); - Ok(()) - } -} From 4931534cc3aea08c0be736f3d658166cb6f18eab Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 28 Aug 2023 17:08:50 +0200 Subject: [PATCH 09/93] asset-registry: fixed tests in all the pallets --- integration-tests/src/bonds.rs | 25 +++++++--------- integration-tests/src/cross_chain_transfer.rs | 6 ---- integration-tests/src/exchange_asset.rs | 30 +++++++++++-------- integration-tests/src/polkadot_test_net.rs | 16 +++++----- pallets/asset-registry/src/lib.rs | 5 ++-- pallets/asset-registry/src/tests/register.rs | 2 +- pallets/asset-registry/src/tests/update.rs | 12 ++++---- pallets/bonds/src/tests/mock.rs | 19 ++++++++++-- pallets/circuit-breaker/src/tests/mock.rs | 6 +++- pallets/dca/src/tests/mock.rs | 6 +++- pallets/liquidity-mining/src/tests/mock.rs | 12 ++++++-- .../src/tests/mock.rs | 6 +++- pallets/omnipool/src/tests/mock.rs | 6 +++- pallets/otc/src/tests/mock.rs | 6 +++- pallets/stableswap/src/tests/mock.rs | 9 ++++-- pallets/xcm-rate-limiter/src/tests/mock.rs | 6 +++- runtime/adapters/src/tests/mock.rs | 6 +++- 17 files changed, 114 insertions(+), 64 deletions(-) diff --git a/integration-tests/src/bonds.rs b/integration-tests/src/bonds.rs index f2a238863..36a20e168 100644 --- a/integration-tests/src/bonds.rs +++ b/integration-tests/src/bonds.rs @@ -5,10 +5,10 @@ use crate::polkadot_test_net::*; use frame_support::{assert_noop, assert_ok}; use orml_traits::MultiCurrency; -use sp_runtime::BoundedVec; use xcm_emulator::TestExt; use hydradx_runtime::{AssetRegistry, Bonds, Currencies, Runtime, RuntimeOrigin}; +use hydradx_traits::{AssetKind, CreateRegistry}; use primitives::constants::time::unix_time::MONTH; #[test] @@ -31,7 +31,7 @@ fn issue_bonds_should_work_when_issued_for_native_asset() { let bond_asset_details = AssetRegistry::assets(bond_id).unwrap(); assert_eq!(bond_asset_details.asset_type, pallet_asset_registry::AssetType::Bond); - assert!(bond_asset_details.name.is_empty()); + assert!(bond_asset_details.name.is_none()); assert_eq!(bond_asset_details.existential_deposit, NativeExistentialDeposit::get()); assert_balance!(&ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - amount); @@ -53,14 +53,12 @@ fn issue_bonds_should_work_when_issued_for_shared_asset() { let maturity = NOW + MONTH; - let bounded_name: BoundedVec::StringLimit> = - "SHARED".as_bytes().to_vec().try_into().unwrap(); - let shared_asset_id = AssetRegistry::register_asset( - bounded_name, - pallet_asset_registry::AssetType::PoolShare(HDX, DOT), + let name = b"SHARED".to_vec(); + let shared_asset_id = AssetRegistry::create_asset( + Some(&name), + pallet_asset_registry::AssetType::PoolShare(HDX, DOT).into(), 1_000, - None, - None, + false, ) .unwrap(); assert_ok!(Currencies::deposit(shared_asset_id, &ALICE.into(), amount,)); @@ -80,7 +78,7 @@ fn issue_bonds_should_work_when_issued_for_shared_asset() { let bond_asset_details = AssetRegistry::assets(bond_id).unwrap(); assert_eq!(bond_asset_details.asset_type, pallet_asset_registry::AssetType::Bond); - assert!(bond_asset_details.name.is_empty()); + assert!(bond_asset_details.name.is_none()); assert_eq!(bond_asset_details.existential_deposit, 1_000); assert_balance!(&ALICE.into(), shared_asset_id, 0); @@ -103,11 +101,8 @@ fn issue_bonds_should_not_work_when_issued_for_bond_asset() { let amount = 100 * UNITS; let maturity = NOW + MONTH; - let bounded_name: BoundedVec::StringLimit> = - "BOND".as_bytes().to_vec().try_into().unwrap(); - let underlying_asset_id = - AssetRegistry::register_asset(bounded_name, pallet_asset_registry::AssetType::Bond, 1_000, None, None) - .unwrap(); + let name = b"BOND".to_vec(); + let underlying_asset_id = AssetRegistry::create_asset(Some(&name), AssetKind::Bond, 1_000, false).unwrap(); assert_ok!(Currencies::deposit(underlying_asset_id, &ALICE.into(), amount,)); // Act & Assert diff --git a/integration-tests/src/cross_chain_transfer.rs b/integration-tests/src/cross_chain_transfer.rs index 3bc596437..9f42928fd 100644 --- a/integration-tests/src/cross_chain_transfer.rs +++ b/integration-tests/src/cross_chain_transfer.rs @@ -28,7 +28,6 @@ fn hydra_should_receive_asset_when_transferred_from_polkadot_relay_chain() { //Arrange Hydra::execute_with(|| { assert_ok!(hydradx_runtime::AssetRegistry::set_location( - hydradx_runtime::RuntimeOrigin::root(), 1, hydradx_runtime::AssetLocation(MultiLocation::parent()) )); @@ -73,7 +72,6 @@ fn polkadot_should_receive_asset_when_sent_from_hydra() { Hydra::execute_with(|| { assert_ok!(hydradx_runtime::AssetRegistry::set_location( - hydradx_runtime::RuntimeOrigin::root(), 1, hydradx_runtime::AssetLocation(MultiLocation::parent()) )); @@ -109,7 +107,6 @@ fn hydra_should_receive_asset_when_transferred_from_acala() { Hydra::execute_with(|| { assert_ok!(hydradx_runtime::AssetRegistry::set_location( - hydradx_runtime::RuntimeOrigin::root(), ACA, hydradx_runtime::AssetLocation(MultiLocation::new(1, X2(Parachain(ACALA_PARA_ID), GeneralIndex(0)))) )); @@ -160,7 +157,6 @@ fn transfer_from_acala_should_fail_when_transferring_insufficient_amount() { Hydra::execute_with(|| { assert_ok!(hydradx_runtime::AssetRegistry::set_location( - hydradx_runtime::RuntimeOrigin::root(), 1, hydradx_runtime::AssetLocation(MultiLocation::new(1, X2(Parachain(ACALA_PARA_ID), GeneralIndex(0)))) )); @@ -211,7 +207,6 @@ fn hydra_treasury_should_receive_asset_when_transferred_to_protocol_account() { init_omnipool(); assert_ok!(hydradx_runtime::AssetRegistry::set_location( - hydradx_runtime::RuntimeOrigin::root(), DAI, // we pretend that the incoming tokens are DAI hydradx_runtime::AssetLocation(MultiLocation::new(1, X2(Parachain(ACALA_PARA_ID), GeneralIndex(0)))) )); @@ -322,7 +317,6 @@ fn claim_trapped_asset_should_work() { // register the asset Hydra::execute_with(|| { assert_ok!(hydradx_runtime::AssetRegistry::set_location( - hydradx_runtime::RuntimeOrigin::root(), 1, hydradx_runtime::AssetLocation(MultiLocation::new(1, X2(Parachain(ACALA_PARA_ID), GeneralIndex(0)))) )); diff --git a/integration-tests/src/exchange_asset.rs b/integration-tests/src/exchange_asset.rs index 9e50f3bb3..4727c4492 100644 --- a/integration-tests/src/exchange_asset.rs +++ b/integration-tests/src/exchange_asset.rs @@ -273,48 +273,54 @@ fn transfer_and_swap_should_work_with_4_hops() { fn register_glmr() { assert_ok!(hydradx_runtime::AssetRegistry::register( hydradx_runtime::RuntimeOrigin::root(), - b"GLRM".to_vec(), - pallet_asset_registry::AssetType::Token, - 1_000_000, Some(GLMR), + Some(b"GLRM".to_vec()), + pallet_asset_registry::AssetType::Token, + Some(1_000_000), + None, None, Some(hydradx_runtime::AssetLocation(MultiLocation::new( 1, X2(Parachain(MOONBEAM_PARA_ID), GeneralIndex(0)) ))), - None + None, + false )); } fn register_aca() { assert_ok!(hydradx_runtime::AssetRegistry::register( hydradx_runtime::RuntimeOrigin::root(), - b"ACAL".to_vec(), - pallet_asset_registry::AssetType::Token, - 1_000_000, Some(ACA), + Some(b"ACAL".to_vec()), + pallet_asset_registry::AssetType::Token, + Some(1_000_000), + None, None, Some(hydradx_runtime::AssetLocation(MultiLocation::new( 1, X2(Parachain(ACALA_PARA_ID), GeneralIndex(0)) ))), - None + None, + false )); } fn register_ibtc() { assert_ok!(hydradx_runtime::AssetRegistry::register( hydradx_runtime::RuntimeOrigin::root(), - b"iBTC".to_vec(), - pallet_asset_registry::AssetType::Token, - 1_000_000, Some(IBTC), + Some(b"iBTC".to_vec()), + pallet_asset_registry::AssetType::Token, + Some(1_000_000), + None, None, Some(hydradx_runtime::AssetLocation(MultiLocation::new( 1, X2(Parachain(INTERLAY_PARA_ID), GeneralIndex(0)) ))), - None + None, + false )); } diff --git a/integration-tests/src/polkadot_test_net.rs b/integration-tests/src/polkadot_test_net.rs index f7759c97c..daa815eb0 100644 --- a/integration-tests/src/polkadot_test_net.rs +++ b/integration-tests/src/polkadot_test_net.rs @@ -220,17 +220,19 @@ pub fn hydra_ext() -> sp_io::TestExternalities { pallet_asset_registry::GenesisConfig:: { registered_assets: vec![ - (b"LRNA".to_vec(), 1_000u128, Some(LRNA)), - (b"DAI".to_vec(), 1_000u128, Some(DAI)), - (b"DOT".to_vec(), 1_000u128, Some(DOT)), - (b"ETH".to_vec(), 1_000u128, Some(ETH)), - (b"BTC".to_vec(), 1_000u128, Some(BTC)), - (b"ACA".to_vec(), 1_000u128, Some(ACA)), + (Some(LRNA), Some(b"LRNA".to_vec()), 1_000u128, None, None, false), + (Some(DAI), Some(b"DAI".to_vec()), 1_000u128, None, None, false), + (Some(DOT), Some(b"DOT".to_vec()), 1_000u128, None, None, false), + (Some(ETH), Some(b"ETH".to_vec()), 1_000u128, None, None, false), + (Some(BTC), Some(b"BTC".to_vec()), 1_000u128, None, None, false), + (Some(ACA), Some(b"ACA".to_vec()), 1_000u128, None, None, false), // workaround for next_asset_id() to return correct values - (b"DUMMY".to_vec(), 1_000u128, None), + (None, Some(b"DUMMY".to_vec()), 1_000u128, None, None, false), ], native_asset_name: b"HDX".to_vec(), native_existential_deposit: existential_deposit, + native_symbol: b"HDX".to_vec(), + native_decimals: 12, } .assimilate_storage(&mut t) .unwrap(); diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index b36a99c08..dd27c366d 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -441,8 +441,7 @@ impl Pallet { name.try_into().map_err(|_| Error::::TooLong) } - //Note: this is used in the tests. - pub(crate) fn do_set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { + pub fn set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { ensure!( Self::location_assets(&location).is_none(), Error::::LocationAlreadyRegistered @@ -501,7 +500,7 @@ impl Pallet { }); if let Some(loc) = location { - Self::do_set_location(asset_id, loc)?; + Self::set_location(asset_id, loc)?; } Ok(asset_id) diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index d7776083e..61f90d071 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -261,7 +261,7 @@ fn register_should_not_work_when_asset_location_is_already_used() { let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::do_set_location(3, asset_location.clone()).unwrap(); + Pallet::::set_location(3, asset_location.clone()).unwrap(); let name = b"Tkn4".to_vec(); let symbol = b"TKN".to_vec(); diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index 0786850c5..9fb7b0441 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -31,7 +31,7 @@ fn update_should_work_when_asset_exists() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); //Act assert_ok!(Registry::update( @@ -99,7 +99,7 @@ fn update_should_not_change_values_when_param_is_none() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); let details_0 = Registry::assets(asset_id).unwrap(); @@ -156,7 +156,7 @@ fn update_origin_should_set_decimals_if_its_none() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); let details_0 = Registry::assets(asset_id).unwrap(); @@ -218,7 +218,7 @@ fn update_origin_should_not_chane_decimals_if_its_some() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); //NOTE: update origin is ste to ensure_signed //Act & assert @@ -255,7 +255,7 @@ fn create_origin_should_always_set_decimals() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); let details_0 = Registry::assets(asset_id).unwrap(); @@ -335,7 +335,7 @@ fn update_should_fail_when_name_is_already_used() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::do_set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); //Act assert_noop!( diff --git a/pallets/bonds/src/tests/mock.rs b/pallets/bonds/src/tests/mock.rs index 0892b6a52..40b3f06c4 100644 --- a/pallets/bonds/src/tests/mock.rs +++ b/pallets/bonds/src/tests/mock.rs @@ -180,7 +180,12 @@ where { type Error = DispatchError; - fn create_asset(_name: &[u8], _kind: AssetKind, existential_deposit: Balance) -> Result { + fn create_asset( + _name: Option<&[u8]>, + _kind: AssetKind, + existential_deposit: Balance, + _sufficient: bool, + ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, (existential_deposit, AssetKind::Bond)); @@ -206,11 +211,19 @@ impl Registry, Balance, DispatchError> for DummyRegi .ok_or(DispatchError::Other("AssetNotFound")) } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { + fn create_asset( + _name: &Vec, + _existential_deposit: Balance, + _sufficient: bool, + ) -> Result { unimplemented!() } - fn get_or_create_asset(_name: Vec, _existential_deposit: Balance) -> Result { + fn get_or_create_asset( + _name: Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { unimplemented!() } } diff --git a/pallets/circuit-breaker/src/tests/mock.rs b/pallets/circuit-breaker/src/tests/mock.rs index 6ae036067..99150d167 100644 --- a/pallets/circuit-breaker/src/tests/mock.rs +++ b/pallets/circuit-breaker/src/tests/mock.rs @@ -384,7 +384,11 @@ where unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { + fn create_asset( + _name: &Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/pallets/dca/src/tests/mock.rs b/pallets/dca/src/tests/mock.rs index 5d84b79e0..a7aea1717 100644 --- a/pallets/dca/src/tests/mock.rs +++ b/pallets/dca/src/tests/mock.rs @@ -734,7 +734,11 @@ where unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { + fn create_asset( + _name: &Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/pallets/liquidity-mining/src/tests/mock.rs b/pallets/liquidity-mining/src/tests/mock.rs index f958404b3..1b700af4a 100644 --- a/pallets/liquidity-mining/src/tests/mock.rs +++ b/pallets/liquidity-mining/src/tests/mock.rs @@ -444,11 +444,19 @@ impl Registry, Balance, DispatchError> for AssetRegistry { unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { + fn create_asset( + _name: &Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { Err(sp_runtime::DispatchError::Other("NotImplemented")) } - fn get_or_create_asset(_name: Vec, _existential_deposit: Balance) -> Result { + fn get_or_create_asset( + _name: Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { Err(sp_runtime::DispatchError::Other("NotImplemented")) } } diff --git a/pallets/omnipool-liquidity-mining/src/tests/mock.rs b/pallets/omnipool-liquidity-mining/src/tests/mock.rs index d1627a73d..033aefcb9 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mock.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mock.rs @@ -657,7 +657,11 @@ where unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { + fn create_asset( + _name: &Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { //NOTE: This is to have same ids as real AssetRegistry which is used in the benchmarks. //1_000_000 - offset of the reals AssetRegistry diff --git a/pallets/omnipool/src/tests/mock.rs b/pallets/omnipool/src/tests/mock.rs index 637d50797..3e3ee6b81 100644 --- a/pallets/omnipool/src/tests/mock.rs +++ b/pallets/omnipool/src/tests/mock.rs @@ -532,7 +532,11 @@ where unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { + fn create_asset( + _name: &Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/pallets/otc/src/tests/mock.rs b/pallets/otc/src/tests/mock.rs index 04651cf11..9d974e6d0 100644 --- a/pallets/otc/src/tests/mock.rs +++ b/pallets/otc/src/tests/mock.rs @@ -152,7 +152,11 @@ impl Registry, Balance, DispatchError> for DummyRegi unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { + fn create_asset( + _name: &Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/pallets/stableswap/src/tests/mock.rs b/pallets/stableswap/src/tests/mock.rs index b26361e38..17df7bfd6 100644 --- a/pallets/stableswap/src/tests/mock.rs +++ b/pallets/stableswap/src/tests/mock.rs @@ -329,7 +329,11 @@ where unimplemented!() } - fn create_asset(name: &Vec, _existential_deposit: Balance) -> Result { + fn create_asset( + name: &Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); @@ -354,8 +358,9 @@ where name: &Vec, _assets: &[T::AssetId], existential_deposit: Balance, + is_sufficient: bool, ) -> Result { - Self::get_or_create_asset(name.clone(), existential_deposit) + Self::get_or_create_asset(name.clone(), existential_deposit, is_sufficient) } } diff --git a/pallets/xcm-rate-limiter/src/tests/mock.rs b/pallets/xcm-rate-limiter/src/tests/mock.rs index a038c5a8f..bfc8f20ae 100644 --- a/pallets/xcm-rate-limiter/src/tests/mock.rs +++ b/pallets/xcm-rate-limiter/src/tests/mock.rs @@ -331,7 +331,11 @@ where unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { + fn create_asset( + _name: &Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/runtime/adapters/src/tests/mock.rs b/runtime/adapters/src/tests/mock.rs index 3dddb08a2..367eea1a9 100644 --- a/runtime/adapters/src/tests/mock.rs +++ b/runtime/adapters/src/tests/mock.rs @@ -555,7 +555,11 @@ where unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { + fn create_asset( + _name: &Vec, + _existential_deposit: Balance, + _is_sufficient: bool, + ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); From 5c71166bae3050972b3e3b7b25844c5693b48ba5 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 29 Aug 2023 15:33:08 +0200 Subject: [PATCH 10/93] asset-registry: fixed benchmarks --- pallets/asset-registry/src/benchmarking.rs | 147 +++++++-------------- 1 file changed, 51 insertions(+), 96 deletions(-) diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index 4f92be61e..c0fe807ec 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -19,115 +19,70 @@ use super::*; +use crate::types::AssetDetails; use frame_benchmarking::benchmarks; use frame_system::RawOrigin; -use crate::types::Metadata; - -use sp_std::vec; - benchmarks! { - register{ - let name = vec![1; T::StringLimit::get() as usize]; - let ed = T::Balance::from(1_000_000u32); - - let symbol = vec![1; T::StringLimit::get() as usize]; - - let metadata = Metadata { - symbol, - decimals: 100, - }; - - }: _(RawOrigin::Root, name.clone(), AssetType::Token, ed, None, Some(metadata), Some(Default::default()), None) - verify { - let bname = crate::Pallet::::to_bounded_name(name).unwrap(); - assert!(crate::Pallet::::asset_ids(bname).is_some()); + where_clause { where + T: crate::pallet::Config, } - update{ - let name = b"NAME".to_vec(); - let ed = T::Balance::from(1_000_000u32); - let asset_id = T::AssetId::from(10u8); - let _ = crate::Pallet::::register(RawOrigin::Root.into(), name, AssetType::Token, ed, Some(asset_id), None, None, None); - - let new_name= vec![1; T::StringLimit::get() as usize]; - - let new_ed = T::Balance::from(2_000_000u32); - - let rate_limit = T::Balance::from(10_000_000u32); - - }: _(RawOrigin::Root, asset_id, new_name.clone(), AssetType::PoolShare(T::AssetId::from(10u8),T::AssetId::from(20u8)), Some(new_ed), Some(rate_limit)) + register { + let asset_id= T::AssetId::from(3); + let name = b"Test name".to_vec(); + let ed = 1_000_000_u128; + let symbol = b"TKN".to_vec(); + let decimals = 12_u8; + let location: T::AssetNativeLocation = Default::default(); + let xcm_rate_limit = 1_000_u128; + let is_sufficient = true; + + }: _(RawOrigin::Root, Some(asset_id), Some(name.clone()), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient) verify { - let bname = crate::Pallet::::to_bounded_name(new_name).unwrap(); - assert_eq!(crate::Pallet::::asset_ids(&bname), Some(asset_id)); - - let stored = crate::Pallet::::assets(asset_id); - - assert!(stored.is_some()); - let stored = stored.unwrap(); - - let expected = AssetDetails{ - asset_type: AssetType::PoolShare(T::AssetId::from(10u8), T::AssetId::from(20u8)), - existential_deposit: new_ed, - name: bname, - xcm_rate_limit: Some(rate_limit), - }; + let b_name = Pallet::::to_bounded_name(name).unwrap(); + assert!(Pallet::::asset_ids(b_name).is_some()); - assert_eq!(stored.asset_type, expected.asset_type); - assert_eq!(stored.existential_deposit, expected.existential_deposit); - assert_eq!(stored.name.to_vec(), expected.name.to_vec()); + assert!(Pallet::::assets(asset_id).is_some()); } - set_metadata{ - let name = b"NAME".to_vec(); - let bname = crate::Pallet::::to_bounded_name(name.clone()).unwrap(); - let ed = T::Balance::from(1_000_000u32); - let _ = crate::Pallet::::register(RawOrigin::Root.into(), name, AssetType::Token, ed, None, None, None, None); - - let asset_id = crate::Pallet::::asset_ids(bname).unwrap(); - - let max_symbol = vec![1; T::StringLimit::get() as usize]; - - }: _(RawOrigin::Root, asset_id, max_symbol.clone(), 10u8) + update { + let asset_id = T::AssetId::from(3); + let name = b"Test name".to_vec(); + let ed = 1_000_000_u128; + let symbol = b"TKN".to_vec(); + let decimals = 12_u8; + let location: T::AssetNativeLocation = Default::default(); + let xcm_rate_limit = 1_000_u128; + let is_sufficient = true; + + let _ = Pallet::::register(RawOrigin::Root.into(), Some(asset_id), Some(name.clone()), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient); + + let new_name= b"New name".to_vec(); + let new_type = AssetType::PoolShare(T::AssetId::from(10u8),T::AssetId::from(20u8)); + let new_ed = 1_000_000_u128; + let new_xcm_rate_limit = 1_000_u128; + let new_is_sufficient = false; + let new_symbol = b"TKNn".to_vec(); + let new_decimals = 12_u8; + + }: _(RawOrigin::Root, asset_id, Some(new_name.clone()), Some(new_type), Some(new_ed), Some(new_xcm_rate_limit), Some(new_is_sufficient), Some(new_symbol.clone()), Some(new_decimals)) verify { - let bsymbol= crate::Pallet::::to_bounded_name(max_symbol).unwrap(); - - let stored = crate::Pallet::::asset_metadata(asset_id); - - assert!(stored.is_some()); - - let stored = stored.unwrap(); - - let expected =AssetMetadata{ - symbol: bsymbol, - decimals: 10u8 - }; + let b_name = Pallet::::to_bounded_name(new_name).unwrap(); + let b_symbol = Pallet::::to_bounded_name(new_symbol).unwrap(); - assert_eq!(stored.symbol.to_vec(), expected.symbol.to_vec()); - assert_eq!(stored.decimals, expected.decimals); - } - - set_location{ - let name = b"NAME".to_vec(); - let ed = T::Balance::from(1_000_000u32); - let asset_id = T::AssetId::from(10u8); - let _ = crate::Pallet::::register(RawOrigin::Root.into(), name.clone(), AssetType::Token, ed, Some(asset_id), None, None, None); - - }: _(RawOrigin::Root, asset_id, Default::default()) - verify { - let bname = crate::Pallet::::to_bounded_name(name).unwrap(); - let bsymbol= crate::Pallet::::to_bounded_name(b"SYMBOL".to_vec()).unwrap(); + assert_eq!(Pallet::::asset_ids(&b_name), Some(asset_id)); - assert_eq!(crate::Pallet::::locations(asset_id), Some(Default::default())); - assert_eq!(crate::Pallet::::location_assets(T::AssetNativeLocation::default()), Some(asset_id)); + assert_eq!(crate::Pallet::::assets(asset_id), Some(AssetDetails { + name: Some(b_name), + asset_type: new_type, + existential_deposit: new_ed, + symbol: Some(b_symbol), + decimals: Some(new_decimals), + xcm_rate_limit: Some(xcm_rate_limit), + is_sufficient: new_is_sufficient, + })); } -} - -#[cfg(test)] -mod tests { - use super::Pallet; - use crate::mock::*; - use frame_benchmarking::impl_benchmark_test_suite; - impl_benchmark_test_suite!(Pallet, super::ExtBuilder::default().build(), super::Test); + impl_benchmark_test_suite!(Pallet, crate::tests::mock::ExtBuilder::default().build(), crate::tests::mock::Test); } From d7867413e00769184cca56577c5d0bf5c7d02d25 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 29 Aug 2023 16:01:44 +0200 Subject: [PATCH 11/93] asset-registry: added asset_id to CreateRegistry trait --- integration-tests/src/bonds.rs | 3 ++- pallets/asset-registry/src/benchmarking.rs | 2 +- pallets/asset-registry/src/lib.rs | 10 ++++++---- pallets/bonds/src/lib.rs | 1 + pallets/bonds/src/tests/mock.rs | 1 + traits/src/registry.rs | 1 + 6 files changed, 12 insertions(+), 6 deletions(-) diff --git a/integration-tests/src/bonds.rs b/integration-tests/src/bonds.rs index 36a20e168..6a182c643 100644 --- a/integration-tests/src/bonds.rs +++ b/integration-tests/src/bonds.rs @@ -55,6 +55,7 @@ fn issue_bonds_should_work_when_issued_for_shared_asset() { let name = b"SHARED".to_vec(); let shared_asset_id = AssetRegistry::create_asset( + None, Some(&name), pallet_asset_registry::AssetType::PoolShare(HDX, DOT).into(), 1_000, @@ -102,7 +103,7 @@ fn issue_bonds_should_not_work_when_issued_for_bond_asset() { let maturity = NOW + MONTH; let name = b"BOND".to_vec(); - let underlying_asset_id = AssetRegistry::create_asset(Some(&name), AssetKind::Bond, 1_000, false).unwrap(); + let underlying_asset_id = AssetRegistry::create_asset(None, Some(&name), AssetKind::Bond, 1_000, false).unwrap(); assert_ok!(Currencies::deposit(underlying_asset_id, &ALICE.into(), amount,)); // Act & Assert diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index c0fe807ec..819f4b3e3 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -56,7 +56,7 @@ benchmarks! { let xcm_rate_limit = 1_000_u128; let is_sufficient = true; - let _ = Pallet::::register(RawOrigin::Root.into(), Some(asset_id), Some(name.clone()), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient); + let _ = Pallet::::register(RawOrigin::Root.into(), Some(asset_id), Some(name), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient); let new_name= b"New name".to_vec(); let new_type = AssetType::PoolShare(T::AssetId::from(10u8),T::AssetId::from(20u8)); diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index dd27c366d..1a6cd64ee 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -51,6 +51,7 @@ use hydradx_traits::{AssetKind, CreateRegistry, Registry, ShareTokenRegistry}; pub const DEFAULT_ED: Balance = 1; #[frame_support::pallet] +#[allow(clippy::too_many_arguments)] pub mod pallet { use super::*; @@ -397,12 +398,12 @@ pub mod pallet { None }; - details.name = new_bounded_name.or(details.name.clone()); + details.name = new_bounded_name.or_else(|| details.name.clone()); details.asset_type = asset_type.unwrap_or(details.asset_type); details.existential_deposit = existential_deposit.unwrap_or(details.existential_deposit); details.xcm_rate_limit = details.xcm_rate_limit.or(xcm_rate_limit); details.is_sufficient = is_sufficient.unwrap_or(details.is_sufficient); - details.symbol = bounded_symbol.or(details.symbol.clone()); + details.symbol = bounded_symbol.or_else(|| details.symbol.clone()); if decimals.is_some() { if details.decimals.is_none() { @@ -458,7 +459,7 @@ impl Pallet { /// Register new asset. /// /// This function checks if asset name is already used. - fn do_register_asset( + pub fn do_register_asset( selected_asset_id: Option, details: AssetDetails>, location: Option, @@ -625,6 +626,7 @@ impl CreateRegistry for Pallet { type Error = DispatchError; fn create_asset( + asset_id: Option, name: Option<&[u8]>, kind: AssetKind, existential_deposit: Balance, @@ -638,7 +640,7 @@ impl CreateRegistry for Pallet { }; Pallet::::do_register_asset( - None, + asset_id, AssetDetails::new( bounded_name, kind.into(), diff --git a/pallets/bonds/src/lib.rs b/pallets/bonds/src/lib.rs index d2ab671c3..8ef36e5ac 100644 --- a/pallets/bonds/src/lib.rs +++ b/pallets/bonds/src/lib.rs @@ -245,6 +245,7 @@ pub mod pallet { let ed = T::ExistentialDeposits::get(&asset_id); let bond_id = >::create_asset( + None, None, AssetKind::Bond, ed, diff --git a/pallets/bonds/src/tests/mock.rs b/pallets/bonds/src/tests/mock.rs index 40b3f06c4..3e2a52bd1 100644 --- a/pallets/bonds/src/tests/mock.rs +++ b/pallets/bonds/src/tests/mock.rs @@ -181,6 +181,7 @@ where type Error = DispatchError; fn create_asset( + _asset_id: Option, _name: Option<&[u8]>, _kind: AssetKind, existential_deposit: Balance, diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 896b5ec35..cd982fefb 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -59,6 +59,7 @@ pub enum AssetKind { pub trait CreateRegistry { type Error; fn create_asset( + asset_id: Option, name: Option<&[u8]>, kind: AssetKind, existential_deposit: Balance, From c77fc9f925cb5a472403686b634549210c23856b Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 29 Aug 2023 17:32:22 +0200 Subject: [PATCH 12/93] asset-registry: make clippy happy --- integration-tests/src/bonds.rs | 5 +- node/src/chain_spec/mod.rs | 1 + pallets/asset-registry/src/lib.rs | 30 ++++----- pallets/asset-registry/src/tests/mock.rs | 2 + pallets/asset-registry/src/tests/register.rs | 66 +++++++++---------- pallets/asset-registry/src/tests/update.rs | 54 +++++++-------- pallets/bonds/src/lib.rs | 2 +- pallets/bonds/src/tests/mock.rs | 2 +- .../src/benchmarks.rs | 6 +- pallets/otc/src/benchmarks.rs | 4 +- pallets/stableswap/src/benchmarks.rs | 32 ++++----- runtime/hydradx/src/benchmarking/mod.rs | 19 +++--- runtime/hydradx/src/benchmarking/omnipool.rs | 20 +++--- .../src/benchmarking/route_executor.rs | 11 ++-- traits/src/registry.rs | 2 +- 15 files changed, 127 insertions(+), 129 deletions(-) diff --git a/integration-tests/src/bonds.rs b/integration-tests/src/bonds.rs index 6a182c643..13e2d5044 100644 --- a/integration-tests/src/bonds.rs +++ b/integration-tests/src/bonds.rs @@ -55,7 +55,7 @@ fn issue_bonds_should_work_when_issued_for_shared_asset() { let name = b"SHARED".to_vec(); let shared_asset_id = AssetRegistry::create_asset( - None, + None, Some(&name), pallet_asset_registry::AssetType::PoolShare(HDX, DOT).into(), 1_000, @@ -103,7 +103,8 @@ fn issue_bonds_should_not_work_when_issued_for_bond_asset() { let maturity = NOW + MONTH; let name = b"BOND".to_vec(); - let underlying_asset_id = AssetRegistry::create_asset(None, Some(&name), AssetKind::Bond, 1_000, false).unwrap(); + let underlying_asset_id = + AssetRegistry::create_asset(None, Some(&name), AssetKind::Bond, 1_000, false).unwrap(); assert_ok!(Currencies::deposit(underlying_asset_id, &ALICE.into(), amount,)); // Act & Assert diff --git a/node/src/chain_spec/mod.rs b/node/src/chain_spec/mod.rs index 44a7797e0..a3855b536 100644 --- a/node/src/chain_spec/mod.rs +++ b/node/src/chain_spec/mod.rs @@ -87,6 +87,7 @@ where AccountPublic::from(get_from_seed::(seed)).into_account() } +#[allow(clippy::type_complexity)] pub fn parachain_genesis( wasm_binary: &[u8], _root_key: AccountId, diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 1a6cd64ee..f0ab02a1e 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -222,24 +222,16 @@ pub mod pallet { self.registered_assets .iter() .for_each(|(id, name, ed, symbol, decimals, is_sufficient)| { - let bounded_name = if let Some(name) = name { - Some( - Pallet::::to_bounded_name(name.to_vec()) - .map_err(|_| panic!("Invalid asset name!")) - .unwrap(), - ) - } else { - None - }; - let bounded_symbol = if let Some(symbol) = symbol { - Some( - Pallet::::to_bounded_name(symbol.to_vec()) - .map_err(|_| panic!("Invalid symbol!")) - .unwrap(), - ) - } else { - None - }; + let bounded_name = name.as_ref().map(|name| { + Pallet::::to_bounded_name(name.to_vec()) + .map_err(|_| panic!("Invalid asset name!")) + .unwrap() + }); + let bounded_symbol = symbol.as_ref().map(|symbol| { + Pallet::::to_bounded_name(symbol.to_vec()) + .map_err(|_| panic!("Invalid symbol!")) + .unwrap() + }); let details = AssetDetails { name: bounded_name, @@ -626,7 +618,7 @@ impl CreateRegistry for Pallet { type Error = DispatchError; fn create_asset( - asset_id: Option, + asset_id: Option, name: Option<&[u8]>, kind: AssetKind, existential_deposit: Balance, diff --git a/pallets/asset-registry/src/tests/mock.rs b/pallets/asset-registry/src/tests/mock.rs index f3c46d5bb..9c3671ea7 100644 --- a/pallets/asset-registry/src/tests/mock.rs +++ b/pallets/asset-registry/src/tests/mock.rs @@ -106,6 +106,7 @@ impl pallet_asset_registry::Config for Test { } #[derive(Default)] +#[allow(clippy::type_complexity)] pub struct ExtBuilder { registered_assets: Vec<( Option, @@ -118,6 +119,7 @@ pub struct ExtBuilder { } impl ExtBuilder { + #[allow(clippy::type_complexity)] pub fn with_assets( mut self, assets: Vec<( diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index 61f90d071..c749b55e2 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -152,12 +152,12 @@ fn register_should_not_work_when_asset_id_is_not_from_reserved_range() { Registry::register( RuntimeOrigin::root(), Some(asset_id), - Some(name.clone()), + Some(name), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), - Some(asset_location.clone()), + Some(asset_location), Some(xcm_rate_limit), is_sufficient ), @@ -170,9 +170,9 @@ fn register_should_not_work_when_asset_id_is_not_from_reserved_range() { fn register_should_not_work_when_asset_id_is_already_used() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -192,12 +192,12 @@ fn register_should_not_work_when_asset_id_is_already_used() { Registry::register( RuntimeOrigin::root(), Some(asset_id), - Some(name.clone()), + Some(name), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), - Some(asset_location.clone()), + Some(asset_location), Some(xcm_rate_limit), is_sufficient ), @@ -210,9 +210,9 @@ fn register_should_not_work_when_asset_id_is_already_used() { fn register_should_not_work_when_asset_name_is_already_used() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -232,12 +232,12 @@ fn register_should_not_work_when_asset_name_is_already_used() { Registry::register( RuntimeOrigin::root(), Some(asset_id), - Some(name.clone()), + Some(name), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), - Some(asset_location.clone()), + Some(asset_location), Some(xcm_rate_limit), is_sufficient ), @@ -250,9 +250,9 @@ fn register_should_not_work_when_asset_name_is_already_used() { fn register_should_not_work_when_asset_location_is_already_used() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -275,12 +275,12 @@ fn register_should_not_work_when_asset_location_is_already_used() { Registry::register( RuntimeOrigin::root(), Some(asset_id), - Some(name.clone()), + Some(name), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), - Some(asset_location.clone()), + Some(asset_location), Some(xcm_rate_limit), is_sufficient ), @@ -293,9 +293,9 @@ fn register_should_not_work_when_asset_location_is_already_used() { fn register_should_not_work_when_origin_is_none() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -317,12 +317,12 @@ fn register_should_not_work_when_origin_is_none() { Registry::register( RuntimeOrigin::none(), Some(asset_id), - Some(name.clone()), + Some(name), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), - Some(asset_location.clone()), + Some(asset_location), Some(xcm_rate_limit), is_sufficient ), @@ -335,9 +335,9 @@ fn register_should_not_work_when_origin_is_none() { fn register_should_not_work_when_origin_is_not_allowed() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -359,12 +359,12 @@ fn register_should_not_work_when_origin_is_not_allowed() { Registry::register( RuntimeOrigin::signed(ALICE), Some(asset_id), - Some(name.clone()), + Some(name), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), - Some(asset_location.clone()), + Some(asset_location), Some(xcm_rate_limit), is_sufficient ), diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index 9fb7b0441..8522c01d6 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -14,9 +14,9 @@ fn update_should_work_when_asset_exists() { let old_asset_name = b"Tkn2".to_vec(); ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(old_asset_name.clone()), 1 * UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(old_asset_name.clone()), UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -64,7 +64,7 @@ fn update_should_work_when_asset_exists() { //NOTE: location should't change assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); - assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); + assert_eq!(Registry::locations(asset_id), Some(asset_location)); let old_bounded_name = Pallet::::to_bounded_name(old_asset_name).unwrap(); assert_eq!(Registry::asset_ids(bounded_name.clone()).unwrap(), asset_id); @@ -88,9 +88,9 @@ fn update_should_work_when_asset_exists() { fn update_should_not_change_values_when_param_is_none() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -120,11 +120,11 @@ fn update_should_not_change_values_when_param_is_none() { assert_eq!(Registry::assets(asset_id).unwrap(), details_0); let old_bounded_name = Pallet::::to_bounded_name(b"Tkn2".to_vec()).unwrap(); - assert_eq!(Registry::asset_ids(old_bounded_name.clone()).unwrap(), asset_id); + assert_eq!(Registry::asset_ids(old_bounded_name).unwrap(), asset_id); //NOTE: location should't change assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); - assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); + assert_eq!(Registry::locations(asset_id), Some(asset_location)); assert_last_event!(Event::::Updated { asset_id, @@ -144,9 +144,9 @@ fn update_should_not_change_values_when_param_is_none() { fn update_origin_should_set_decimals_if_its_none() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -156,7 +156,7 @@ fn update_origin_should_set_decimals_if_its_none() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location).unwrap(); let details_0 = Registry::assets(asset_id).unwrap(); @@ -206,9 +206,9 @@ fn update_origin_should_set_decimals_if_its_none() { fn update_origin_should_not_chane_decimals_if_its_some() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, Some(3), true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, Some(3), true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -218,7 +218,7 @@ fn update_origin_should_not_chane_decimals_if_its_some() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location).unwrap(); //NOTE: update origin is ste to ensure_signed //Act & assert @@ -243,9 +243,9 @@ fn update_origin_should_not_chane_decimals_if_its_some() { fn create_origin_should_always_set_decimals() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), 1 * UNIT, None, Some(3), true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, Some(3), true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -255,7 +255,7 @@ fn create_origin_should_always_set_decimals() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location).unwrap(); let details_0 = Registry::assets(asset_id).unwrap(); @@ -318,9 +318,9 @@ fn update_should_fail_when_name_is_already_used() { let old_asset_name = b"Tkn2".to_vec(); ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), 1 * UNIT, None, None, true), - (Some(2), Some(old_asset_name.clone()), 1 * UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), 1 * UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), + (Some(2), Some(old_asset_name), UNIT, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), ]) .build() .execute_with(|| { @@ -335,19 +335,19 @@ fn update_should_fail_when_name_is_already_used() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location).unwrap(); //Act assert_noop!( Registry::update( RuntimeOrigin::root(), asset_id, - Some(name.clone()), + Some(name), Some(AssetType::External), Some(ed), Some(xcm_rate_limit), Some(is_sufficient), - Some(symbol.clone()), + Some(symbol), Some(decimals), ), Error::::AssetAlreadyRegistered diff --git a/pallets/bonds/src/lib.rs b/pallets/bonds/src/lib.rs index 8ef36e5ac..834a864bc 100644 --- a/pallets/bonds/src/lib.rs +++ b/pallets/bonds/src/lib.rs @@ -245,7 +245,7 @@ pub mod pallet { let ed = T::ExistentialDeposits::get(&asset_id); let bond_id = >::create_asset( - None, + None, None, AssetKind::Bond, ed, diff --git a/pallets/bonds/src/tests/mock.rs b/pallets/bonds/src/tests/mock.rs index 3e2a52bd1..195c26db5 100644 --- a/pallets/bonds/src/tests/mock.rs +++ b/pallets/bonds/src/tests/mock.rs @@ -181,7 +181,7 @@ where type Error = DispatchError; fn create_asset( - _asset_id: Option, + _asset_id: Option, _name: Option<&[u8]>, _kind: AssetKind, existential_deposit: Balance, diff --git a/pallets/omnipool-liquidity-mining/src/benchmarks.rs b/pallets/omnipool-liquidity-mining/src/benchmarks.rs index 5132a6f0c..01ba059ef 100644 --- a/pallets/omnipool-liquidity-mining/src/benchmarks.rs +++ b/pallets/omnipool-liquidity-mining/src/benchmarks.rs @@ -115,9 +115,9 @@ where )?; // Register new asset in asset registry - T::AssetRegistry::create_asset(&b"BSX".to_vec(), Balance::one())?; - T::AssetRegistry::create_asset(&b"ETH".to_vec(), Balance::one())?; - T::AssetRegistry::create_asset(&b"BTC".to_vec(), Balance::one())?; + T::AssetRegistry::create_asset(&b"BSX".to_vec(), Balance::one(), true)?; + T::AssetRegistry::create_asset(&b"ETH".to_vec(), Balance::one(), true)?; + T::AssetRegistry::create_asset(&b"BTC".to_vec(), Balance::one(), true)?; // Create account for token provider and set balance let owner: T::AccountId = account("owner", 0, 1); diff --git a/pallets/otc/src/benchmarks.rs b/pallets/otc/src/benchmarks.rs index 0e494de05..ae314bd21 100644 --- a/pallets/otc/src/benchmarks.rs +++ b/pallets/otc/src/benchmarks.rs @@ -84,8 +84,8 @@ where u32: From<::AssetId>, { // Register new asset in asset registry - let hdx = T::AssetRegistry::create_asset(&b"HDX".to_vec(), ONE)?; - let dai = T::AssetRegistry::create_asset(&b"DAI".to_vec(), ONE)?; + let hdx = T::AssetRegistry::create_asset(&b"HDX".to_vec(), ONE, true)?; + let dai = T::AssetRegistry::create_asset(&b"DAI".to_vec(), ONE, true)?; Ok((hdx.into(), dai.into())) } diff --git a/pallets/stableswap/src/benchmarks.rs b/pallets/stableswap/src/benchmarks.rs index 7cf30dc6e..7d678f353 100644 --- a/pallets/stableswap/src/benchmarks.rs +++ b/pallets/stableswap/src/benchmarks.rs @@ -50,10 +50,10 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; asset_ids.push(asset_id); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; let amplification = 100u16; let trade_fee = Permill::from_percent(1); let withdraw_fee = Permill::from_percent(1); @@ -77,7 +77,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -90,7 +90,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; let amplification = 100u16; let trade_fee = Permill::from_percent(1); @@ -127,7 +127,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, liquidity_added as i128)?; @@ -140,7 +140,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; let asset_id_to_withdraw: T::AssetId = *asset_ids.last().unwrap(); @@ -191,7 +191,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -204,7 +204,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; let amplification = 100u16; let trade_fee = Permill::from_percent(1); @@ -262,7 +262,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -275,7 +275,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; let amplification = 100u16; let trade_fee = Permill::from_percent(1); @@ -332,7 +332,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -345,7 +345,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; let amplification = 100u16; let trade_fee = Permill::from_percent(1); @@ -380,7 +380,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -393,7 +393,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; let successful_origin = T::AuthorityOrigin::try_successful_origin().unwrap(); crate::Pallet::::create_pool(successful_origin.clone(), @@ -425,7 +425,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -438,7 +438,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; let successful_origin = T::AuthorityOrigin::try_successful_origin().unwrap(); crate::Pallet::::create_pool(successful_origin.clone(), diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index 4998fef07..8a60b0c9b 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -11,6 +11,8 @@ pub mod vesting; use crate::AssetRegistry; use frame_system::RawOrigin; +use frame_support::dispatch::DispatchError; +use hydradx_traits::Registry; use primitives::{AssetId, Balance}; use sp_std::vec; use sp_std::vec::Vec; @@ -18,14 +20,8 @@ use sp_std::vec::Vec; pub const BSX: Balance = primitives::constants::currency::UNITS; pub fn register_asset(name: Vec, deposit: Balance) -> Result { - AssetRegistry::register_asset( - AssetRegistry::to_bounded_name(name).map_err(|_| ())?, - pallet_asset_registry::AssetType::::Token, - deposit, - None, - None, - ) - .map_err(|_| ()) + , Balance, DispatchError>>::create_asset(&name, deposit, false) + .map_err(|_| ()) } #[allow(dead_code)] @@ -33,10 +29,13 @@ pub fn update_asset(asset_id: AssetId, name: Vec, deposit: Balance) -> Resul AssetRegistry::update( RawOrigin::Root.into(), asset_id, - name, - pallet_asset_registry::AssetType::::Token, + Some(name), + Some(pallet_asset_registry::AssetType::::Token), Some(deposit), None, + None, + None, + None, ) .map_err(|_| ()) } diff --git a/runtime/hydradx/src/benchmarking/omnipool.rs b/runtime/hydradx/src/benchmarking/omnipool.rs index 91fdd0de5..b98f0ce92 100644 --- a/runtime/hydradx/src/benchmarking/omnipool.rs +++ b/runtime/hydradx/src/benchmarking/omnipool.rs @@ -86,7 +86,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), Balance::one())?; + let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), Balance::one(), true)?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -123,7 +123,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; //Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), Balance::one())?; + let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), Balance::one(), true)?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -169,7 +169,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1u128)?; + let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), 1u128,true)?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -227,7 +227,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1u128)?; + let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), 1u128, true)?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -285,7 +285,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1_u128)?; + let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), 1_u128, true)?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -351,7 +351,7 @@ runtime_benchmarks! { refund_refused_asset { let recipient: AccountId = account("recipient", 3, 1); - let asset_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1_u128)?; + let asset_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), 1_u128, true)?; let amount = 1_000_000_000_000_000_u128; update_balance(asset_id, &Omnipool::protocol_account(), amount); @@ -380,7 +380,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price, Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), Balance::one())?; + let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), Balance::one(), true)?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -449,11 +449,13 @@ mod tests { pallet_asset_registry::GenesisConfig:: { registered_assets: vec![ - (b"LRNA".to_vec(), 1_000u128, Some(1)), - (b"DAI".to_vec(), 1_000u128, Some(2)), + (Some(1), Some(b"LRNA".to_vec()), 1_000u128, None, None, false), + (Some(2), Some(b"DAI".to_vec()), 1_000u128, None, None, false), ], native_asset_name: b"HDX".to_vec(), native_existential_deposit: NativeExistentialDeposit::get(), + native_decimals: 12, + native_symbol: b"HDX".to_vec(), } .assimilate_storage(&mut t) .unwrap(); diff --git a/runtime/hydradx/src/benchmarking/route_executor.rs b/runtime/hydradx/src/benchmarking/route_executor.rs index 7c0a84899..a34ecbc6e 100644 --- a/runtime/hydradx/src/benchmarking/route_executor.rs +++ b/runtime/hydradx/src/benchmarking/route_executor.rs @@ -22,6 +22,7 @@ use super::*; use frame_benchmarking::account; use frame_system::{Pallet as System, RawOrigin}; +use hydradx_traits::CreateRegistry; use orml_benchmarking::runtime_benchmarks; use orml_traits::{MultiCurrency, MultiCurrencyExtended}; @@ -86,12 +87,12 @@ fn initialize_omnipool() -> DispatchResult { pub fn regi_asset(name: Vec, deposit: Balance, asset_id: AssetId) -> Result { let name = AssetRegistry::to_bounded_name(name)?; - AssetRegistry::register_asset( - name, - pallet_asset_registry::AssetType::::Token, - deposit, + >::create_asset( Some(asset_id), - None, + Some(&name), + pallet_asset_registry::AssetType::::Token.into(), + deposit, + true, ) } diff --git a/traits/src/registry.rs b/traits/src/registry.rs index cd982fefb..733b71f53 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -59,7 +59,7 @@ pub enum AssetKind { pub trait CreateRegistry { type Error; fn create_asset( - asset_id: Option, + asset_id: Option, name: Option<&[u8]>, kind: AssetKind, existential_deposit: Balance, From a66a3d0e24ac12afd4d27109cf2cf2f8ef2cac46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20P=C3=A1nik?= Date: Wed, 30 Aug 2023 14:09:11 +0200 Subject: [PATCH 13/93] review --- pallets/asset-registry/src/lib.rs | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index f0ab02a1e..c4456ee5d 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -129,11 +129,13 @@ pub mod pallet { /// Location already registered with different asset LocationAlreadyRegistered, + //TODO: docs Forbidden, } #[pallet::type_value] pub fn DefaultNextAssetId() -> T::AssetId { + // TODO: docs 1.into() } @@ -187,7 +189,7 @@ pub mod pallet { GenesisConfig:: { registered_assets: vec![], native_asset_name: b"HDX".to_vec(), - native_existential_deposit: Default::default(), + native_existential_deposit: Default::default(), // TODO: Fix native_symbol: b"HDX".to_vec(), native_decimals: 12, } @@ -237,7 +239,7 @@ pub mod pallet { name: bounded_name, asset_type: AssetType::Token, existential_deposit: *ed, - xcm_rate_limit: None, + xcm_rate_limit: None, //TODO: add to setup symbol: bounded_symbol, decimals: *decimals, is_sufficient: *is_sufficient, @@ -355,7 +357,7 @@ pub mod pallet { symbol: Option>, decimals: Option, ) -> DispatchResult { - let is_registry_origing = match T::UpdateOrigin::ensure_origin(origin.clone()) { + let is_registry_origin = match T::UpdateOrigin::ensure_origin(origin.clone()) { Ok(_) => false, Err(_) => { T::RegistryOrigin::ensure_origin(origin)?; @@ -393,7 +395,7 @@ pub mod pallet { details.name = new_bounded_name.or_else(|| details.name.clone()); details.asset_type = asset_type.unwrap_or(details.asset_type); details.existential_deposit = existential_deposit.unwrap_or(details.existential_deposit); - details.xcm_rate_limit = details.xcm_rate_limit.or(xcm_rate_limit); + details.xcm_rate_limit = details.xcm_rate_limit.or(xcm_rate_limit); // BUG? Set new value instead of old details.is_sufficient = is_sufficient.unwrap_or(details.is_sufficient); details.symbol = bounded_symbol.or_else(|| details.symbol.clone()); @@ -401,8 +403,9 @@ pub mod pallet { if details.decimals.is_none() { details.decimals = decimals; } else { + // TODO: Maybe consider updating location here as it would require just 3 more LOC //Only highest origin can change decimal if it was set previously. - ensure!(is_registry_origing, Error::::Forbidden); + ensure!(is_registry_origin, Error::::Forbidden); details.decimals = decimals; }; } @@ -480,6 +483,10 @@ impl Pallet { ensure!(!AssetIds::::contains_key(name), Error::::AssetAlreadyRegistered); AssetIds::::insert(name, asset_id); } + + if let Some(loc) = location { + Self::set_location(asset_id, loc)?; + } Self::deposit_event(Event::Registered { asset_id, @@ -492,10 +499,6 @@ impl Pallet { is_sufficient: details.is_sufficient, }); - if let Some(loc) = location { - Self::set_location(asset_id, loc)?; - } - Ok(asset_id) } From 2d80b18c5dedc08b9ace48de63425e16d07c1702 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 31 Aug 2023 15:31:07 +0200 Subject: [PATCH 14/93] asset-registry: revert changes old registry trait and pallets using it + minor refactor and start of new traits for asset registry --- integration-tests/src/bonds.rs | 12 +-- integration-tests/src/cross_chain_transfer.rs | 1 + pallets/asset-registry/src/lib.rs | 98 ++++++++++++------- pallets/bonds/src/lib.rs | 4 +- pallets/bonds/src/tests/mock.rs | 20 +--- pallets/circuit-breaker/src/tests/mock.rs | 6 +- pallets/dca/src/tests/mock.rs | 6 +- pallets/liquidity-mining/src/tests/mock.rs | 12 +-- .../src/benchmarks.rs | 6 +- .../src/tests/mock.rs | 6 +- pallets/omnipool/src/tests/mock.rs | 6 +- pallets/otc/src/benchmarks.rs | 4 +- pallets/otc/src/tests/mock.rs | 6 +- pallets/stableswap/src/benchmarks.rs | 32 +++--- pallets/stableswap/src/tests/mock.rs | 9 +- pallets/xcm-rate-limiter/src/tests/mock.rs | 6 +- runtime/adapters/src/tests/mock.rs | 6 +- runtime/hydradx/src/benchmarking/mod.rs | 20 ++-- runtime/hydradx/src/benchmarking/omnipool.rs | 14 +-- .../src/benchmarking/route_executor.rs | 16 +-- traits/src/registry.rs | 78 +++++++++++---- 21 files changed, 198 insertions(+), 170 deletions(-) diff --git a/integration-tests/src/bonds.rs b/integration-tests/src/bonds.rs index 13e2d5044..c6c4daab5 100644 --- a/integration-tests/src/bonds.rs +++ b/integration-tests/src/bonds.rs @@ -4,11 +4,11 @@ use crate::assert_balance; use crate::polkadot_test_net::*; use frame_support::{assert_noop, assert_ok}; +use hydradx_traits::CreateRegistry; use orml_traits::MultiCurrency; use xcm_emulator::TestExt; use hydradx_runtime::{AssetRegistry, Bonds, Currencies, Runtime, RuntimeOrigin}; -use hydradx_traits::{AssetKind, CreateRegistry}; use primitives::constants::time::unix_time::MONTH; #[test] @@ -31,7 +31,7 @@ fn issue_bonds_should_work_when_issued_for_native_asset() { let bond_asset_details = AssetRegistry::assets(bond_id).unwrap(); assert_eq!(bond_asset_details.asset_type, pallet_asset_registry::AssetType::Bond); - assert!(bond_asset_details.name.is_none()); + assert!(bond_asset_details.name.unwrap().is_empty()); assert_eq!(bond_asset_details.existential_deposit, NativeExistentialDeposit::get()); assert_balance!(&ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - amount); @@ -55,11 +55,9 @@ fn issue_bonds_should_work_when_issued_for_shared_asset() { let name = b"SHARED".to_vec(); let shared_asset_id = AssetRegistry::create_asset( - None, - Some(&name), + &name, pallet_asset_registry::AssetType::PoolShare(HDX, DOT).into(), 1_000, - false, ) .unwrap(); assert_ok!(Currencies::deposit(shared_asset_id, &ALICE.into(), amount,)); @@ -79,7 +77,7 @@ fn issue_bonds_should_work_when_issued_for_shared_asset() { let bond_asset_details = AssetRegistry::assets(bond_id).unwrap(); assert_eq!(bond_asset_details.asset_type, pallet_asset_registry::AssetType::Bond); - assert!(bond_asset_details.name.is_none()); + assert!(bond_asset_details.name.unwrap().is_empty()); assert_eq!(bond_asset_details.existential_deposit, 1_000); assert_balance!(&ALICE.into(), shared_asset_id, 0); @@ -104,7 +102,7 @@ fn issue_bonds_should_not_work_when_issued_for_bond_asset() { let name = b"BOND".to_vec(); let underlying_asset_id = - AssetRegistry::create_asset(None, Some(&name), AssetKind::Bond, 1_000, false).unwrap(); + AssetRegistry::create_asset(&name, pallet_asset_registry::AssetType::::Bond.into(), 1_000).unwrap(); assert_ok!(Currencies::deposit(underlying_asset_id, &ALICE.into(), amount,)); // Act & Assert diff --git a/integration-tests/src/cross_chain_transfer.rs b/integration-tests/src/cross_chain_transfer.rs index 9f42928fd..dd8e4d7fe 100644 --- a/integration-tests/src/cross_chain_transfer.rs +++ b/integration-tests/src/cross_chain_transfer.rs @@ -13,6 +13,7 @@ use pretty_assertions::assert_eq; use sp_core::H256; use sp_runtime::traits::{AccountIdConversion, BlakeTwo256, Hash}; use xcm_emulator::TestExt; +use hydradx_traits::registry::Mutate; // Determine the hash for assets expected to be have been trapped. fn determine_hash(origin: &MultiLocation, assets: M) -> H256 diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index f0ab02a1e..1fd2291db 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -44,7 +44,10 @@ pub use pallet::*; pub use crate::types::{AssetDetails, Balance}; use frame_support::BoundedVec; -use hydradx_traits::{AssetKind, CreateRegistry, Registry, ShareTokenRegistry}; +use hydradx_traits::{ + registry::{Create, Inspect, Mutate}, + AssetKind, CreateRegistry, Registry, ShareTokenRegistry, +}; /// Default value of existential deposit. This value is used if existential deposit wasn't /// provided. @@ -430,11 +433,12 @@ impl Pallet { } /// Convert Vec to BoundedVec so it respects the max set limit, otherwise return TooLong error + //TODO: remove pub pub fn to_bounded_name(name: Vec) -> Result, Error> { name.try_into().map_err(|_| Error::::TooLong) } - pub fn set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { + fn do_set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { ensure!( Self::location_assets(&location).is_none(), Error::::LocationAlreadyRegistered @@ -448,10 +452,7 @@ impl Pallet { Ok(()) } - /// Register new asset. - /// - /// This function checks if asset name is already used. - pub fn do_register_asset( + fn do_register_asset( selected_asset_id: Option, details: AssetDetails>, location: Option, @@ -493,7 +494,7 @@ impl Pallet { }); if let Some(loc) = location { - Self::set_location(asset_id, loc)?; + Self::do_set_location(asset_id, loc)?; } Ok(asset_id) @@ -559,12 +560,8 @@ impl Registry, Balance, DispatchError> for Pallet Ok(asset_details.asset_type.into()) } - fn create_asset( - name: &Vec, - existential_deposit: Balance, - is_sufficient: bool, - ) -> Result { - Self::get_or_create_asset(name.clone(), AssetType::Token, existential_deposit, None, is_sufficient) + fn create_asset(name: &Vec, existential_deposit: Balance) -> Result { + Self::get_or_create_asset(name.clone(), AssetType::Token, existential_deposit, None, false) } } @@ -577,7 +574,6 @@ impl ShareTokenRegistry, Balance, DispatchError> name: &Vec, assets: &[T::AssetId], existential_deposit: Balance, - is_sufficient: bool, ) -> Result { ensure!(assets.len() == 2, Error::::InvalidSharedAssetLen); Self::get_or_create_asset( @@ -585,7 +581,7 @@ impl ShareTokenRegistry, Balance, DispatchError> AssetType::PoolShare(assets[0], assets[1]), existential_deposit, None, - is_sufficient, + false, ) } } @@ -618,31 +614,67 @@ impl CreateRegistry for Pallet { type Error = DispatchError; fn create_asset( - asset_id: Option, - name: Option<&[u8]>, + name: &[u8], kind: AssetKind, existential_deposit: Balance, - is_sufficient: bool, //TODO: add location ) -> Result { - let bounded_name = if let Some(n) = name { - Some(Self::to_bounded_name(n.to_vec())?) - } else { - None - }; + let bounded_name = Some(Self::to_bounded_name(name.to_vec())?); Pallet::::do_register_asset( - asset_id, - AssetDetails::new( - bounded_name, - kind.into(), - existential_deposit, - None, - None, - None, - is_sufficient, - ), + None, + AssetDetails::new(bounded_name, kind.into(), existential_deposit, None, None, None, false), None, ) } } + +impl Inspect for Pallet { + type Error = DispatchError; + type AssetId = T::AssetId; +} + +impl Mutate for Pallet { + fn set_location(asset_id: Self::AssetId, location: T::AssetNativeLocation) -> Result<(), Self::Error> { + Self::do_set_location(asset_id, location) + } +} + +impl Create for Pallet { + fn register_asset( + asset_id: Option, + name: Option<&[u8]>, + kind: AssetKind, + existential_deposit: Option, + symbol: Option<&[u8]>, + decimals: Option, + location: Option, + xcm_rate_limit: Option, + is_sufficient: bool, + ) -> Result { + let bounded_name = if let Some(name) = name { + let bounded_name = Self::to_bounded_name(name.to_vec())?; + Some(bounded_name) + } else { + None + }; + + let bounded_symbol = if let Some(symbol) = symbol { + Some(Self::to_bounded_name(symbol.to_vec())?) + } else { + None + }; + + let details = AssetDetails::new( + bounded_name, + kind.into(), + existential_deposit.unwrap_or(DEFAULT_ED), + bounded_symbol, + decimals, + xcm_rate_limit, + is_sufficient, + ); + + Self::do_register_asset(asset_id, details, location) + } +} diff --git a/pallets/bonds/src/lib.rs b/pallets/bonds/src/lib.rs index 834a864bc..4f111b9d8 100644 --- a/pallets/bonds/src/lib.rs +++ b/pallets/bonds/src/lib.rs @@ -245,11 +245,9 @@ pub mod pallet { let ed = T::ExistentialDeposits::get(&asset_id); let bond_id = >::create_asset( - None, - None, + &[], AssetKind::Bond, ed, - false, )?; Bonds::::insert(bond_id, (asset_id, maturity)); diff --git a/pallets/bonds/src/tests/mock.rs b/pallets/bonds/src/tests/mock.rs index 195c26db5..0892b6a52 100644 --- a/pallets/bonds/src/tests/mock.rs +++ b/pallets/bonds/src/tests/mock.rs @@ -180,13 +180,7 @@ where { type Error = DispatchError; - fn create_asset( - _asset_id: Option, - _name: Option<&[u8]>, - _kind: AssetKind, - existential_deposit: Balance, - _sufficient: bool, - ) -> Result { + fn create_asset(_name: &[u8], _kind: AssetKind, existential_deposit: Balance) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, (existential_deposit, AssetKind::Bond)); @@ -212,19 +206,11 @@ impl Registry, Balance, DispatchError> for DummyRegi .ok_or(DispatchError::Other("AssetNotFound")) } - fn create_asset( - _name: &Vec, - _existential_deposit: Balance, - _sufficient: bool, - ) -> Result { + fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { unimplemented!() } - fn get_or_create_asset( - _name: Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn get_or_create_asset(_name: Vec, _existential_deposit: Balance) -> Result { unimplemented!() } } diff --git a/pallets/circuit-breaker/src/tests/mock.rs b/pallets/circuit-breaker/src/tests/mock.rs index 99150d167..6ae036067 100644 --- a/pallets/circuit-breaker/src/tests/mock.rs +++ b/pallets/circuit-breaker/src/tests/mock.rs @@ -384,11 +384,7 @@ where unimplemented!() } - fn create_asset( - _name: &Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/pallets/dca/src/tests/mock.rs b/pallets/dca/src/tests/mock.rs index a7aea1717..5d84b79e0 100644 --- a/pallets/dca/src/tests/mock.rs +++ b/pallets/dca/src/tests/mock.rs @@ -734,11 +734,7 @@ where unimplemented!() } - fn create_asset( - _name: &Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/pallets/liquidity-mining/src/tests/mock.rs b/pallets/liquidity-mining/src/tests/mock.rs index 1b700af4a..f958404b3 100644 --- a/pallets/liquidity-mining/src/tests/mock.rs +++ b/pallets/liquidity-mining/src/tests/mock.rs @@ -444,19 +444,11 @@ impl Registry, Balance, DispatchError> for AssetRegistry { unimplemented!() } - fn create_asset( - _name: &Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { Err(sp_runtime::DispatchError::Other("NotImplemented")) } - fn get_or_create_asset( - _name: Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn get_or_create_asset(_name: Vec, _existential_deposit: Balance) -> Result { Err(sp_runtime::DispatchError::Other("NotImplemented")) } } diff --git a/pallets/omnipool-liquidity-mining/src/benchmarks.rs b/pallets/omnipool-liquidity-mining/src/benchmarks.rs index 01ba059ef..5132a6f0c 100644 --- a/pallets/omnipool-liquidity-mining/src/benchmarks.rs +++ b/pallets/omnipool-liquidity-mining/src/benchmarks.rs @@ -115,9 +115,9 @@ where )?; // Register new asset in asset registry - T::AssetRegistry::create_asset(&b"BSX".to_vec(), Balance::one(), true)?; - T::AssetRegistry::create_asset(&b"ETH".to_vec(), Balance::one(), true)?; - T::AssetRegistry::create_asset(&b"BTC".to_vec(), Balance::one(), true)?; + T::AssetRegistry::create_asset(&b"BSX".to_vec(), Balance::one())?; + T::AssetRegistry::create_asset(&b"ETH".to_vec(), Balance::one())?; + T::AssetRegistry::create_asset(&b"BTC".to_vec(), Balance::one())?; // Create account for token provider and set balance let owner: T::AccountId = account("owner", 0, 1); diff --git a/pallets/omnipool-liquidity-mining/src/tests/mock.rs b/pallets/omnipool-liquidity-mining/src/tests/mock.rs index 033aefcb9..d1627a73d 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mock.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mock.rs @@ -657,11 +657,7 @@ where unimplemented!() } - fn create_asset( - _name: &Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { //NOTE: This is to have same ids as real AssetRegistry which is used in the benchmarks. //1_000_000 - offset of the reals AssetRegistry diff --git a/pallets/omnipool/src/tests/mock.rs b/pallets/omnipool/src/tests/mock.rs index 3e3ee6b81..637d50797 100644 --- a/pallets/omnipool/src/tests/mock.rs +++ b/pallets/omnipool/src/tests/mock.rs @@ -532,11 +532,7 @@ where unimplemented!() } - fn create_asset( - _name: &Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/pallets/otc/src/benchmarks.rs b/pallets/otc/src/benchmarks.rs index ae314bd21..0e494de05 100644 --- a/pallets/otc/src/benchmarks.rs +++ b/pallets/otc/src/benchmarks.rs @@ -84,8 +84,8 @@ where u32: From<::AssetId>, { // Register new asset in asset registry - let hdx = T::AssetRegistry::create_asset(&b"HDX".to_vec(), ONE, true)?; - let dai = T::AssetRegistry::create_asset(&b"DAI".to_vec(), ONE, true)?; + let hdx = T::AssetRegistry::create_asset(&b"HDX".to_vec(), ONE)?; + let dai = T::AssetRegistry::create_asset(&b"DAI".to_vec(), ONE)?; Ok((hdx.into(), dai.into())) } diff --git a/pallets/otc/src/tests/mock.rs b/pallets/otc/src/tests/mock.rs index 9d974e6d0..04651cf11 100644 --- a/pallets/otc/src/tests/mock.rs +++ b/pallets/otc/src/tests/mock.rs @@ -152,11 +152,7 @@ impl Registry, Balance, DispatchError> for DummyRegi unimplemented!() } - fn create_asset( - _name: &Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/pallets/stableswap/src/benchmarks.rs b/pallets/stableswap/src/benchmarks.rs index 7d678f353..7cf30dc6e 100644 --- a/pallets/stableswap/src/benchmarks.rs +++ b/pallets/stableswap/src/benchmarks.rs @@ -50,10 +50,10 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; asset_ids.push(asset_id); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; let amplification = 100u16; let trade_fee = Permill::from_percent(1); let withdraw_fee = Permill::from_percent(1); @@ -77,7 +77,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -90,7 +90,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; let amplification = 100u16; let trade_fee = Permill::from_percent(1); @@ -127,7 +127,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, liquidity_added as i128)?; @@ -140,7 +140,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; let asset_id_to_withdraw: T::AssetId = *asset_ids.last().unwrap(); @@ -191,7 +191,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -204,7 +204,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; let amplification = 100u16; let trade_fee = Permill::from_percent(1); @@ -262,7 +262,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -275,7 +275,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; let amplification = 100u16; let trade_fee = Permill::from_percent(1); @@ -332,7 +332,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -345,7 +345,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; let amplification = 100u16; let trade_fee = Permill::from_percent(1); @@ -380,7 +380,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -393,7 +393,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; let successful_origin = T::AuthorityOrigin::try_successful_origin().unwrap(); crate::Pallet::::create_pool(successful_origin.clone(), @@ -425,7 +425,7 @@ benchmarks! { let mut asset_ids: Vec = Vec::new() ; for idx in 0..MAX_ASSETS_IN_POOL { let name: Vec = idx.to_ne_bytes().to_vec(); - let asset_id = T::AssetRegistry::create_asset(&name, 1u128, false)?; + let asset_id = T::AssetRegistry::create_asset(&name, 1u128)?; asset_ids.push(asset_id); T::Currency::update_balance(asset_id, &caller, 1_000_000_000_000_000i128)?; T::Currency::update_balance(asset_id, &lp_provider, 1_000_000_000_000_000_000_000i128)?; @@ -438,7 +438,7 @@ benchmarks! { amount: liquidity_added }); } - let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128, false)?; + let pool_id = T::AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; let successful_origin = T::AuthorityOrigin::try_successful_origin().unwrap(); crate::Pallet::::create_pool(successful_origin.clone(), diff --git a/pallets/stableswap/src/tests/mock.rs b/pallets/stableswap/src/tests/mock.rs index 17df7bfd6..b26361e38 100644 --- a/pallets/stableswap/src/tests/mock.rs +++ b/pallets/stableswap/src/tests/mock.rs @@ -329,11 +329,7 @@ where unimplemented!() } - fn create_asset( - name: &Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn create_asset(name: &Vec, _existential_deposit: Balance) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); @@ -358,9 +354,8 @@ where name: &Vec, _assets: &[T::AssetId], existential_deposit: Balance, - is_sufficient: bool, ) -> Result { - Self::get_or_create_asset(name.clone(), existential_deposit, is_sufficient) + Self::get_or_create_asset(name.clone(), existential_deposit) } } diff --git a/pallets/xcm-rate-limiter/src/tests/mock.rs b/pallets/xcm-rate-limiter/src/tests/mock.rs index bfc8f20ae..a038c5a8f 100644 --- a/pallets/xcm-rate-limiter/src/tests/mock.rs +++ b/pallets/xcm-rate-limiter/src/tests/mock.rs @@ -331,11 +331,7 @@ where unimplemented!() } - fn create_asset( - _name: &Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/runtime/adapters/src/tests/mock.rs b/runtime/adapters/src/tests/mock.rs index 367eea1a9..3dddb08a2 100644 --- a/runtime/adapters/src/tests/mock.rs +++ b/runtime/adapters/src/tests/mock.rs @@ -555,11 +555,7 @@ where unimplemented!() } - fn create_asset( - _name: &Vec, - _existential_deposit: Balance, - _is_sufficient: bool, - ) -> Result { + fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); v.borrow_mut().insert(l as u32, l as u32); diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index 8a60b0c9b..25d00e750 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -11,8 +11,7 @@ pub mod vesting; use crate::AssetRegistry; use frame_system::RawOrigin; -use frame_support::dispatch::DispatchError; -use hydradx_traits::Registry; +use hydradx_traits::{registry::Create, AssetKind}; use primitives::{AssetId, Balance}; use sp_std::vec; use sp_std::vec::Vec; @@ -20,8 +19,17 @@ use sp_std::vec::Vec; pub const BSX: Balance = primitives::constants::currency::UNITS; pub fn register_asset(name: Vec, deposit: Balance) -> Result { - , Balance, DispatchError>>::create_asset(&name, deposit, false) - .map_err(|_| ()) + AssetRegistry::register_insufficient_asset( + None, + Some(&name), + AssetKind::Token, + Some(deposit), + None, + None, + None, + None, + ) + .map_err(|_| ()) } #[allow(dead_code)] @@ -30,12 +38,12 @@ pub fn update_asset(asset_id: AssetId, name: Vec, deposit: Balance) -> Resul RawOrigin::Root.into(), asset_id, Some(name), - Some(pallet_asset_registry::AssetType::::Token), + None, Some(deposit), None, None, None, - None, + None, ) .map_err(|_| ()) } diff --git a/runtime/hydradx/src/benchmarking/omnipool.rs b/runtime/hydradx/src/benchmarking/omnipool.rs index b98f0ce92..dd8434bcf 100644 --- a/runtime/hydradx/src/benchmarking/omnipool.rs +++ b/runtime/hydradx/src/benchmarking/omnipool.rs @@ -86,7 +86,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), Balance::one(), true)?; + let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), Balance::one())?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -123,7 +123,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; //Register new asset in asset registry - let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), Balance::one(), true)?; + let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), Balance::one())?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -169,7 +169,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), 1u128,true)?; + let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1u128)?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -227,7 +227,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), 1u128, true)?; + let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1u128)?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -285,7 +285,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), 1_u128, true)?; + let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1_u128)?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -351,7 +351,7 @@ runtime_benchmarks! { refund_refused_asset { let recipient: AccountId = account("recipient", 3, 1); - let asset_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), 1_u128, true)?; + let asset_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1_u128)?; let amount = 1_000_000_000_000_000_u128; update_balance(asset_id, &Omnipool::protocol_account(), amount); @@ -380,7 +380,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price, Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = , Balance, DispatchError>>::create_asset(&b"FCK".to_vec(), Balance::one(), true)?; + let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), Balance::one())?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); diff --git a/runtime/hydradx/src/benchmarking/route_executor.rs b/runtime/hydradx/src/benchmarking/route_executor.rs index a34ecbc6e..1b1d93189 100644 --- a/runtime/hydradx/src/benchmarking/route_executor.rs +++ b/runtime/hydradx/src/benchmarking/route_executor.rs @@ -22,7 +22,7 @@ use super::*; use frame_benchmarking::account; use frame_system::{Pallet as System, RawOrigin}; -use hydradx_traits::CreateRegistry; +use hydradx_traits::{registry::Create, router::PoolType, AssetKind}; use orml_benchmarking::runtime_benchmarks; use orml_traits::{MultiCurrency, MultiCurrencyExtended}; @@ -86,13 +86,16 @@ fn initialize_omnipool() -> DispatchResult { } pub fn regi_asset(name: Vec, deposit: Balance, asset_id: AssetId) -> Result { - let name = AssetRegistry::to_bounded_name(name)?; - >::create_asset( + AssetRegistry::register_asset( Some(asset_id), Some(&name), - pallet_asset_registry::AssetType::::Token.into(), - deposit, - true, + AssetKind::Token, + Some(deposit), + None, + None, + None, + None, + false, ) } @@ -132,7 +135,6 @@ fn fund( use frame_support::assert_ok; use frame_support::traits::Hooks; -use hydradx_traits::router::PoolType; use pallet_route_executor::Trade; use sp_runtime::{DispatchError, DispatchResult, FixedU128, Permill}; use sp_std::vec; diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 733b71f53..05d3e3fdb 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -7,17 +7,13 @@ pub trait Registry { fn retrieve_asset_type(asset_id: AssetId) -> Result; - fn create_asset(name: &AssetName, existential_deposit: Balance, is_sufficient: bool) -> Result; + fn create_asset(name: &AssetName, existential_deposit: Balance) -> Result; - fn get_or_create_asset( - name: AssetName, - existential_deposit: Balance, - is_sufficient: bool, - ) -> Result { + fn get_or_create_asset(name: AssetName, existential_deposit: Balance) -> Result { if let Ok(asset_id) = Self::retrieve_asset(&name) { Ok(asset_id) } else { - Self::create_asset(&name, existential_deposit, is_sufficient) + Self::create_asset(&name, existential_deposit) } } } @@ -30,19 +26,17 @@ pub trait ShareTokenRegistry: Registry Result; fn get_or_create_shared_asset( name: AssetName, assets: Vec, existential_deposit: Balance, - is_sufficient: bool, ) -> Result { if let Ok(asset_id) = Self::retrieve_shared_asset(&name, &assets) { Ok(asset_id) } else { - Self::create_shared_asset(&name, &assets, existential_deposit, is_sufficient) + Self::create_shared_asset(&name, &assets, existential_deposit) } } } @@ -58,13 +52,7 @@ pub enum AssetKind { pub trait CreateRegistry { type Error; - fn create_asset( - asset_id: Option, - name: Option<&[u8]>, - kind: AssetKind, - existential_deposit: Balance, - is_sufficient: bool, - ) -> Result; + fn create_asset(name: &[u8], kind: AssetKind, existential_deposit: Balance) -> Result; } // Deprecated. @@ -84,3 +72,59 @@ pub trait AccountIdFor { /// Create a name to uniquely identify a share token for given assets and an identifier. fn name(assets: &Assets, identifier: Option<&[u8]>) -> Vec; } + +use frame_support::dispatch::Parameter; + +pub trait Inspect { + type Error; + type AssetId: Parameter; +} + +#[allow(clippy::too_many_arguments)] +pub trait Create: Inspect { + fn register_asset( + asset_id: Option, + name: Option<&[u8]>, + kind: AssetKind, + existential_deposit: Option, + symbol: Option<&[u8]>, + decimals: Option, + location: Option, + xcm_rate_limit: Option, + is_sufficient: bool, + ) -> Result; + + fn register_insufficient_asset( + asset_id: Option, + name: Option<&[u8]>, + kind: AssetKind, + existential_deposit: Option, + symbol: Option<&[u8]>, + decimals: Option, + location: Option, + xcm_rate_limit: Option, + ) -> Result { + Self::register_asset(asset_id, name, kind, existential_deposit, symbol, decimals, location, xcm_rate_limit, false) + } + + fn register_sufficient_asset( + asset_id: Option, + name: Option<&[u8]>, + kind: AssetKind, + existential_deposit: Option, + symbol: Option<&[u8]>, + decimals: Option, + location: Option, + xcm_rate_limit: Option, + ) -> Result { + Self::register_asset(asset_id, name, kind, existential_deposit, symbol, decimals, location, xcm_rate_limit, true) + } +} + +pub trait Mutate: Inspect { + /// Set location for existing asset id if it wasn't set yet. + fn set_location(asset_id: Self::AssetId, location: AssetNativeLocation) -> Result<(), Self::Error>; + + // /// Set or update location of existing asset + // fn force_set_location(asset_id: Self::AssetId, location: AssetNativeLocation) -> Result<(, Self::Error)> +} From 634a330d23659dd4485a31613d7fb12c00fd02d3 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 31 Aug 2023 16:25:31 +0200 Subject: [PATCH 15/93] asset-registry: fixed xcm_rate_limit update --- integration-tests/src/bonds.rs | 3 +- integration-tests/src/cross_chain_transfer.rs | 2 +- pallets/asset-registry/src/lib.rs | 2 +- pallets/asset-registry/src/tests/update.rs | 80 +++++++++++++++++++ runtime/hydradx/src/benchmarking/mod.rs | 4 +- traits/src/registry.rs | 28 ++++++- 6 files changed, 110 insertions(+), 9 deletions(-) diff --git a/integration-tests/src/bonds.rs b/integration-tests/src/bonds.rs index c6c4daab5..907964eff 100644 --- a/integration-tests/src/bonds.rs +++ b/integration-tests/src/bonds.rs @@ -102,7 +102,8 @@ fn issue_bonds_should_not_work_when_issued_for_bond_asset() { let name = b"BOND".to_vec(); let underlying_asset_id = - AssetRegistry::create_asset(&name, pallet_asset_registry::AssetType::::Bond.into(), 1_000).unwrap(); + AssetRegistry::create_asset(&name, pallet_asset_registry::AssetType::::Bond.into(), 1_000) + .unwrap(); assert_ok!(Currencies::deposit(underlying_asset_id, &ALICE.into(), amount,)); // Act & Assert diff --git a/integration-tests/src/cross_chain_transfer.rs b/integration-tests/src/cross_chain_transfer.rs index dd8e4d7fe..972baeab4 100644 --- a/integration-tests/src/cross_chain_transfer.rs +++ b/integration-tests/src/cross_chain_transfer.rs @@ -8,12 +8,12 @@ use polkadot_xcm::{latest::prelude::*, v3::WeightLimit, VersionedMultiAssets, Ve use cumulus_primitives_core::ParaId; use frame_support::weights::Weight; use hex_literal::hex; +use hydradx_traits::registry::Mutate; use orml_traits::currency::MultiCurrency; use pretty_assertions::assert_eq; use sp_core::H256; use sp_runtime::traits::{AccountIdConversion, BlakeTwo256, Hash}; use xcm_emulator::TestExt; -use hydradx_traits::registry::Mutate; // Determine the hash for assets expected to be have been trapped. fn determine_hash(origin: &MultiLocation, assets: M) -> H256 diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 1fd2291db..ff03a8e82 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -396,7 +396,7 @@ pub mod pallet { details.name = new_bounded_name.or_else(|| details.name.clone()); details.asset_type = asset_type.unwrap_or(details.asset_type); details.existential_deposit = existential_deposit.unwrap_or(details.existential_deposit); - details.xcm_rate_limit = details.xcm_rate_limit.or(xcm_rate_limit); + details.xcm_rate_limit = xcm_rate_limit.or(details.xcm_rate_limit); details.is_sufficient = is_sufficient.unwrap_or(details.is_sufficient); details.symbol = bounded_symbol.or_else(|| details.symbol.clone()); diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index 8522c01d6..7515abba5 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -84,6 +84,86 @@ fn update_should_work_when_asset_exists() { }); } +#[test] +fn update_should_update_provided_params_when_values_was_previously_set() { + let old_asset_name = b"Tkn2".to_vec(); + ExtBuilder::default().with_assets(vec![]).build().execute_with(|| { + //Arrange + let asset_id = 1; + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + assert_ok!(Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(b"Test asset".to_vec()), + AssetType::Token, + Some(10_000), + Some(b"TKN".to_vec()), + Some(12), + Some(asset_location.clone()), + Some(1_000), + true + )); + + let name = b"New name".to_vec(); + let ed = 20_000 * UNIT; + let xcm_rate_limit = 463; + let symbol = b"nTkn".to_vec(); + let decimals = 23; + let is_sufficient = false; + + //Act + assert_ok!(Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + )); + + //Assert + let bounded_name = Pallet::::to_bounded_name(name).unwrap(); + let bounded_symbol = Pallet::::to_bounded_name(symbol).unwrap(); + assert_eq!( + Registry::assets(asset_id), + Some(AssetDetails { + name: Some(bounded_name.clone()), + asset_type: AssetType::External, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: Some(bounded_symbol.clone()), + decimals: Some(decimals), + is_sufficient: false + }) + ); + + //NOTE: location should't change + assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(asset_location)); + + let old_bounded_name = Pallet::::to_bounded_name(old_asset_name).unwrap(); + assert_eq!(Registry::asset_ids(bounded_name.clone()).unwrap(), asset_id); + assert!(Registry::asset_ids(old_bounded_name).is_none()); + + assert_last_event!(Event::::Updated { + asset_id, + asset_name: Some(bounded_name), + asset_type: AssetType::External, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + decimals: Some(decimals), + symbol: Some(bounded_symbol), + is_sufficient, + } + .into()); + }); +} + #[test] fn update_should_not_change_values_when_param_is_none() { ExtBuilder::default() diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index 25d00e750..be5f93706 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -38,12 +38,12 @@ pub fn update_asset(asset_id: AssetId, name: Vec, deposit: Balance) -> Resul RawOrigin::Root.into(), asset_id, Some(name), - None, + None, Some(deposit), None, None, None, - None, + None, ) .map_err(|_| ()) } diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 05d3e3fdb..9514b4b4d 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -104,10 +104,20 @@ pub trait Create: Inspect, xcm_rate_limit: Option, ) -> Result { - Self::register_asset(asset_id, name, kind, existential_deposit, symbol, decimals, location, xcm_rate_limit, false) + Self::register_asset( + asset_id, + name, + kind, + existential_deposit, + symbol, + decimals, + location, + xcm_rate_limit, + false, + ) } - - fn register_sufficient_asset( + + fn register_sufficient_asset( asset_id: Option, name: Option<&[u8]>, kind: AssetKind, @@ -117,7 +127,17 @@ pub trait Create: Inspect, xcm_rate_limit: Option, ) -> Result { - Self::register_asset(asset_id, name, kind, existential_deposit, symbol, decimals, location, xcm_rate_limit, true) + Self::register_asset( + asset_id, + name, + kind, + existential_deposit, + symbol, + decimals, + location, + xcm_rate_limit, + true, + ) } } From 16d587f09e5f33466800810163f28f0b4bca2f33 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 1 Sep 2023 15:21:42 +0200 Subject: [PATCH 16/93] asset-registry: fix review comments --- integration-tests/src/polkadot_test_net.rs | 14 +- node/src/chain_spec/local.rs | 4 +- node/src/chain_spec/mod.rs | 3 +- pallets/asset-registry/src/benchmarking.rs | 3 +- pallets/asset-registry/src/lib.rs | 57 +++--- pallets/asset-registry/src/tests/mock.rs | 2 + pallets/asset-registry/src/tests/register.rs | 30 ++-- pallets/asset-registry/src/tests/update.rs | 174 +++++++++++++++++-- pallets/asset-registry/src/types.rs | 4 + runtime/hydradx/src/benchmarking/mod.rs | 1 + runtime/hydradx/src/benchmarking/omnipool.rs | 4 +- 11 files changed, 229 insertions(+), 67 deletions(-) diff --git a/integration-tests/src/polkadot_test_net.rs b/integration-tests/src/polkadot_test_net.rs index daa815eb0..948e07765 100644 --- a/integration-tests/src/polkadot_test_net.rs +++ b/integration-tests/src/polkadot_test_net.rs @@ -220,14 +220,14 @@ pub fn hydra_ext() -> sp_io::TestExternalities { pallet_asset_registry::GenesisConfig:: { registered_assets: vec![ - (Some(LRNA), Some(b"LRNA".to_vec()), 1_000u128, None, None, false), - (Some(DAI), Some(b"DAI".to_vec()), 1_000u128, None, None, false), - (Some(DOT), Some(b"DOT".to_vec()), 1_000u128, None, None, false), - (Some(ETH), Some(b"ETH".to_vec()), 1_000u128, None, None, false), - (Some(BTC), Some(b"BTC".to_vec()), 1_000u128, None, None, false), - (Some(ACA), Some(b"ACA".to_vec()), 1_000u128, None, None, false), + (Some(LRNA), Some(b"LRNA".to_vec()), 1_000u128, None, None, None, false), + (Some(DAI), Some(b"DAI".to_vec()), 1_000u128, None, None, None, false), + (Some(DOT), Some(b"DOT".to_vec()), 1_000u128, None, None, None, false), + (Some(ETH), Some(b"ETH".to_vec()), 1_000u128, None, None, None, false), + (Some(BTC), Some(b"BTC".to_vec()), 1_000u128, None, None, None, false), + (Some(ACA), Some(b"ACA".to_vec()), 1_000u128, None, None, None, false), // workaround for next_asset_id() to return correct values - (None, Some(b"DUMMY".to_vec()), 1_000u128, None, None, false), + (None, Some(b"DUMMY".to_vec()), 1_000u128, None, None, None, false), ], native_asset_name: b"HDX".to_vec(), native_existential_deposit: existential_deposit, diff --git a/node/src/chain_spec/local.rs b/node/src/chain_spec/local.rs index 4c2807ea1..cfa6d6836 100644 --- a/node/src/chain_spec/local.rs +++ b/node/src/chain_spec/local.rs @@ -81,8 +81,8 @@ pub fn parachain_config() -> Result { vec![], // registered assets vec![ - (Some(1), Some(b"KSM".to_vec()), 1_000u128, None, None, false), - (Some(2), Some(b"KUSD".to_vec()), 1_000u128, None, None, false), + (Some(1), Some(b"KSM".to_vec()), 1_000u128, None, None, None, false), + (Some(2), Some(b"KUSD".to_vec()), 1_000u128, None, None, None, false), ], // accepted assets vec![(1, Price::from_float(0.0000212)), (2, Price::from_float(0.000806))], diff --git a/node/src/chain_spec/mod.rs b/node/src/chain_spec/mod.rs index a3855b536..f5191c66b 100644 --- a/node/src/chain_spec/mod.rs +++ b/node/src/chain_spec/mod.rs @@ -102,8 +102,9 @@ pub fn parachain_genesis( Balance, Option>, Option, + Option, bool, - )>, // (asset_id, name, existential deposit, symbol, decimals, is_sufficient) + )>, // (asset_id, name, existential deposit, symbol, decimals, xcm_rate_limit, is_sufficient) accepted_assets: Vec<(AssetId, Price)>, // (Asset id, Fallback price) - asset which fee can be paid with token_balances: Vec<(AccountId, Vec<(AssetId, Balance)>)>, claims_data: Vec<(EthereumAddress, Balance)>, diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index 819f4b3e3..eca77d3f9 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -66,7 +66,8 @@ benchmarks! { let new_symbol = b"TKNn".to_vec(); let new_decimals = 12_u8; - }: _(RawOrigin::Root, asset_id, Some(new_name.clone()), Some(new_type), Some(new_ed), Some(new_xcm_rate_limit), Some(new_is_sufficient), Some(new_symbol.clone()), Some(new_decimals)) + + }: _(RawOrigin::Root, asset_id, Some(new_name.clone()), Some(new_type), Some(new_ed), Some(new_xcm_rate_limit), Some(new_is_sufficient), Some(new_symbol.clone()), Some(new_decimals), Some(Default::default())) verify { let b_name = Pallet::::to_bounded_name(new_name).unwrap(); let b_symbol = Pallet::::to_bounded_name(new_symbol).unwrap(); diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 8e13fe551..6b5a62184 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -132,13 +132,14 @@ pub mod pallet { /// Location already registered with different asset LocationAlreadyRegistered, - //TODO: docs + /// Origin is fobiddent to set/update value Forbidden, } #[pallet::type_value] + /// Default value of NextAssetId if storage is empty. 1 is used to offset for native token + /// which id is 0. pub fn DefaultNextAssetId() -> T::AssetId { - // TODO: docs 1.into() } @@ -171,13 +172,14 @@ pub mod pallet { #[allow(clippy::type_complexity)] #[pallet::genesis_config] pub struct GenesisConfig { - //asset_id, name, existential deposit, symbol, decimals, is_sufficient + //asset_id, name, existential deposit, symbol, decimals, xcm_rate_limit, is_sufficient pub registered_assets: Vec<( Option, Option>, Balance, Option>, Option, + Option, bool, )>, pub native_asset_name: Vec, @@ -192,7 +194,7 @@ pub mod pallet { GenesisConfig:: { registered_assets: vec![], native_asset_name: b"HDX".to_vec(), - native_existential_deposit: Default::default(), // TODO: Fix + native_existential_deposit: DEFAULT_ED, native_symbol: b"HDX".to_vec(), native_decimals: 12, } @@ -226,7 +228,7 @@ pub mod pallet { self.registered_assets .iter() - .for_each(|(id, name, ed, symbol, decimals, is_sufficient)| { + .for_each(|(id, name, ed, symbol, decimals, xcm_rate_limit, is_sufficient)| { let bounded_name = name.as_ref().map(|name| { Pallet::::to_bounded_name(name.to_vec()) .map_err(|_| panic!("Invalid asset name!")) @@ -242,7 +244,7 @@ pub mod pallet { name: bounded_name, asset_type: AssetType::Token, existential_deposit: *ed, - xcm_rate_limit: None, //TODO: add to setup + xcm_rate_limit: *xcm_rate_limit, symbol: bounded_symbol, decimals: *decimals, is_sufficient: *is_sufficient, @@ -291,10 +293,13 @@ pub mod pallet { impl Pallet { /// Register a new asset. /// - /// Asset is identified by `name` and the name must not be used to register another asset. - /// /// New asset is given `NextAssetId` - sequential asset id /// + /// Asset's id is optional and it can't be used by another asset if it's provided. + /// Provided `asset_id` must be from within reserved range. + /// If `asset_id` is `None`, new asset is given id for sequential ids. + /// + /// Asset's name is optional and it can't be used by another asset if it's provided. /// Adds mapping between `name` and assigned `asset_id` so asset id can be retrieved by name too (Note: this approach is used in AMM implementation (xyk)) /// /// Emits 'Registered` event when successful. @@ -344,7 +349,12 @@ pub mod pallet { /// Update registered asset. /// - /// Updates also mapping between name and asset id if provided name is different than currently registered. + /// All parameteres are optional and value is not updated if param is `None`. + /// + /// `decimals` - can be update by `UpdateOrigin` only if it wasn't set yet. Only + /// `RegistryOrigin` can update `decimals` if it was previously set. + /// + /// `location` - can be updated only by `RegistryOrigin`. /// /// Emits `Updated` event when successful. #[pallet::call_index(1)] @@ -359,13 +369,14 @@ pub mod pallet { is_sufficient: Option, symbol: Option>, decimals: Option, + location: Option, ) -> DispatchResult { - let is_registry_origin = match T::UpdateOrigin::ensure_origin(origin.clone()) { - Ok(_) => false, + let is_registry_origin = match T::RegistryOrigin::ensure_origin(origin.clone()) { + Ok(_) => true, Err(_) => { - T::RegistryOrigin::ensure_origin(origin)?; + T::UpdateOrigin::ensure_origin(origin)?; - true + false } }; @@ -406,13 +417,22 @@ pub mod pallet { if details.decimals.is_none() { details.decimals = decimals; } else { - // TODO: Maybe consider updating location here as it would require just 3 more LOC //Only highest origin can change decimal if it was set previously. ensure!(is_registry_origin, Error::::Forbidden); details.decimals = decimals; }; } + if let Some(loc) = location { + //Only highest origin can update location. + ensure!(is_registry_origin, Error::::Forbidden); + + if let Some(old_location) = AssetLocations::::take(asset_id) { + LocationAssets::::remove(&old_location); + } + Self::do_set_location(asset_id, loc)?; + } + Self::deposit_event(Event::Updated { asset_id, asset_name: details.name.clone(), @@ -484,7 +504,7 @@ impl Pallet { ensure!(!AssetIds::::contains_key(name), Error::::AssetAlreadyRegistered); AssetIds::::insert(name, asset_id); } - + if let Some(loc) = location { Self::set_location(asset_id, loc)?; } @@ -616,12 +636,7 @@ impl GetByKey> for XcmRateLimitsInRegistr impl CreateRegistry for Pallet { type Error = DispatchError; - fn create_asset( - name: &[u8], - kind: AssetKind, - existential_deposit: Balance, - //TODO: add location - ) -> Result { + fn create_asset(name: &[u8], kind: AssetKind, existential_deposit: Balance) -> Result { let bounded_name = Some(Self::to_bounded_name(name.to_vec())?); Pallet::::do_register_asset( diff --git a/pallets/asset-registry/src/tests/mock.rs b/pallets/asset-registry/src/tests/mock.rs index 9c3671ea7..500c5304c 100644 --- a/pallets/asset-registry/src/tests/mock.rs +++ b/pallets/asset-registry/src/tests/mock.rs @@ -114,6 +114,7 @@ pub struct ExtBuilder { Balance, Option>, Option, + Option, bool, )>, } @@ -128,6 +129,7 @@ impl ExtBuilder { Balance, Option>, Option, + Option, bool, )>, ) -> Self { diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index c749b55e2..be17d7d9a 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -170,9 +170,9 @@ fn register_should_not_work_when_asset_id_is_not_from_reserved_range() { fn register_should_not_work_when_asset_id_is_already_used() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { @@ -210,9 +210,9 @@ fn register_should_not_work_when_asset_id_is_already_used() { fn register_should_not_work_when_asset_name_is_already_used() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { @@ -250,9 +250,9 @@ fn register_should_not_work_when_asset_name_is_already_used() { fn register_should_not_work_when_asset_location_is_already_used() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { @@ -293,9 +293,9 @@ fn register_should_not_work_when_asset_location_is_already_used() { fn register_should_not_work_when_origin_is_none() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { @@ -335,9 +335,9 @@ fn register_should_not_work_when_origin_is_none() { fn register_should_not_work_when_origin_is_not_allowed() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index 7515abba5..e0da8ca72 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -14,9 +14,9 @@ fn update_should_work_when_asset_exists() { let old_asset_name = b"Tkn2".to_vec(); ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(old_asset_name.clone()), UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(old_asset_name.clone()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { @@ -44,6 +44,7 @@ fn update_should_work_when_asset_exists() { Some(is_sufficient), Some(symbol.clone()), Some(decimals), + None )); //Assert @@ -124,6 +125,7 @@ fn update_should_update_provided_params_when_values_was_previously_set() { Some(is_sufficient), Some(symbol.clone()), Some(decimals), + None )); //Assert @@ -168,9 +170,9 @@ fn update_should_update_provided_params_when_values_was_previously_set() { fn update_should_not_change_values_when_param_is_none() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { @@ -194,6 +196,7 @@ fn update_should_not_change_values_when_param_is_none() { None, None, None, + None, )); //Assert @@ -224,9 +227,9 @@ fn update_should_not_change_values_when_param_is_none() { fn update_origin_should_set_decimals_if_its_none() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { @@ -252,6 +255,7 @@ fn update_origin_should_set_decimals_if_its_none() { None, None, Some(decimals), + None, )); //Assert @@ -286,9 +290,9 @@ fn update_origin_should_set_decimals_if_its_none() { fn update_origin_should_not_chane_decimals_if_its_some() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, Some(3), true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, Some(3), None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { @@ -313,6 +317,7 @@ fn update_origin_should_not_chane_decimals_if_its_some() { None, None, Some(decimals), + None, ), Error::::Forbidden ); @@ -323,9 +328,9 @@ fn update_origin_should_not_chane_decimals_if_its_some() { fn create_origin_should_always_set_decimals() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, Some(3), true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, Some(3), None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { @@ -351,6 +356,7 @@ fn create_origin_should_always_set_decimals() { None, None, Some(decimals), + None, )); assert_ok!(Registry::update( @@ -363,6 +369,7 @@ fn create_origin_should_always_set_decimals() { None, None, Some(u8::max_value()), + None, )); //Assert @@ -398,9 +405,9 @@ fn update_should_fail_when_name_is_already_used() { let old_asset_name = b"Tkn2".to_vec(); ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, true), - (Some(2), Some(old_asset_name), UNIT, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, true), + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(old_asset_name), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() .execute_with(|| { @@ -429,8 +436,139 @@ fn update_should_fail_when_name_is_already_used() { Some(is_sufficient), Some(symbol), Some(decimals), + None, ), Error::::AssetAlreadyRegistered ); }); } + +#[test] +fn update_should_not_update_location_when_origin_is_not_registry_origin() { + let old_asset_name = b"Tkn2".to_vec(); + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(old_asset_name), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + + //Act 1 - asset without location also should work + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + assert_noop!( + Registry::update( + RuntimeOrigin::signed(ALICE), + asset_id, + None, + None, + None, + None, + None, + None, + None, + Some(asset_location), + ), + Error::::Forbidden + ); + + //Arrange - location should not be updated if it exists + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::set_location(asset_id, asset_location).unwrap(); + + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(400), key))); + //Act + assert_noop!( + Registry::update( + RuntimeOrigin::signed(ALICE), + asset_id, + None, + None, + None, + None, + None, + None, + None, + Some(asset_location) + ), + Error::::Forbidden + ); + }); +} + +#[test] +fn update_should_update_location_when_origin_is_registry_origin() { + let old_asset_name = b"Tkn2".to_vec(); + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(old_asset_name), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + + //Act 1 - asset without location also should work + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + assert_ok!(Registry::update( + RuntimeOrigin::root(), + asset_id, + None, + None, + None, + None, + None, + None, + None, + Some(asset_location.clone()), + )); + + assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); + assert!(has_event( + Event::::LocationSet { + asset_id, + location: asset_location.clone() + } + .into() + )); + + //Arrange - location should not be updated if it exists + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let second_location = AssetLocation(MultiLocation::new(0, X2(Parachain(400), key))); + + //Act + assert_ok!(Registry::update( + RuntimeOrigin::root(), + asset_id, + None, + None, + None, + None, + None, + None, + None, + Some(second_location.clone()) + )); + + assert!(Registry::location_assets(asset_location).is_none()); + + assert_eq!(Registry::location_assets(second_location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(second_location.clone())); + assert!(has_event( + Event::::LocationSet { + asset_id, + location: second_location + } + .into() + )); + }); +} diff --git a/pallets/asset-registry/src/types.rs b/pallets/asset-registry/src/types.rs index 31fda8675..0f3315aea 100644 --- a/pallets/asset-registry/src/types.rs +++ b/pallets/asset-registry/src/types.rs @@ -66,8 +66,10 @@ pub struct AssetDetails { /// The name of this asset. Limited in length by `StringLimit`. pub name: Option, + /// Asset type pub asset_type: AssetType, + /// Existential deposit pub existential_deposit: Balance, /// The ticker symbol for this asset. Limited in length by `StringLimit`. @@ -76,8 +78,10 @@ pub struct AssetDetails { /// The number of decimals this asset uses to represent one unit. pub decimals: Option, + /// XCM rate limit. pub xcm_rate_limit: Option, + /// Asset sufficiency. pub is_sufficient: bool, } diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index be5f93706..3f4e8a2bb 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -44,6 +44,7 @@ pub fn update_asset(asset_id: AssetId, name: Vec, deposit: Balance) -> Resul None, None, None, + None, ) .map_err(|_| ()) } diff --git a/runtime/hydradx/src/benchmarking/omnipool.rs b/runtime/hydradx/src/benchmarking/omnipool.rs index dd8434bcf..2ebb3e57c 100644 --- a/runtime/hydradx/src/benchmarking/omnipool.rs +++ b/runtime/hydradx/src/benchmarking/omnipool.rs @@ -449,8 +449,8 @@ mod tests { pallet_asset_registry::GenesisConfig:: { registered_assets: vec![ - (Some(1), Some(b"LRNA".to_vec()), 1_000u128, None, None, false), - (Some(2), Some(b"DAI".to_vec()), 1_000u128, None, None, false), + (Some(1), Some(b"LRNA".to_vec()), 1_000u128, None, None, None, false), + (Some(2), Some(b"DAI".to_vec()), 1_000u128, None, None, None, false), ], native_asset_name: b"HDX".to_vec(), native_existential_deposit: NativeExistentialDeposit::get(), From 7c93b905b2376a0b3348532dbd2d5091f3cd4136 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 4 Sep 2023 13:10:31 +0200 Subject: [PATCH 17/93] asset-registry: integration tests --- integration-tests/src/asset_registry.rs | 169 ++++++++++++++++++++++++ integration-tests/src/lib.rs | 1 + 2 files changed, 170 insertions(+) create mode 100644 integration-tests/src/asset_registry.rs diff --git a/integration-tests/src/asset_registry.rs b/integration-tests/src/asset_registry.rs new file mode 100644 index 000000000..499d5cf03 --- /dev/null +++ b/integration-tests/src/asset_registry.rs @@ -0,0 +1,169 @@ +#![cfg(test)] + +use crate::asset_registry::Junction::GeneralIndex; +use crate::polkadot_test_net::*; +use frame_support::{assert_noop, assert_ok}; +use frame_system::RawOrigin; +use hydradx_runtime::{AssetRegistry as Registry, TechnicalCollective}; +use polkadot_xcm::v3::{ + Junction::{self, Parachain}, + Junctions::X2, + MultiLocation, +}; +use pretty_assertions::{assert_eq, assert_ne}; +use xcm_emulator::TestExt; + +#[test] +fn root_should_update_decimals_when_it_was_already_set() { + TestNet::reset(); + Hydra::execute_with(|| { + let new_decimals = 53_u8; + + assert_ne!(Registry::assets(HDX).unwrap().decimals.unwrap(), new_decimals); + + assert_ok!(Registry::update( + RawOrigin::Root.into(), + HDX, + None, + None, + None, + None, + None, + None, + Some(new_decimals), + None + )); + + assert_eq!(Registry::assets(HDX).unwrap().decimals.unwrap(), new_decimals); + }); +} + +#[test] +fn tech_comm_should_not_update_decimals_when_it_was_aleady_set() { + TestNet::reset(); + Hydra::execute_with(|| { + let tech_comm = pallet_collective::RawOrigin::::Members(1, 1); + let new_decimals = 53_u8; + + assert_ne!(Registry::assets(HDX).unwrap().decimals.unwrap(), new_decimals); + + assert_noop!( + Registry::update( + tech_comm.into(), + HDX, + None, + None, + None, + None, + None, + None, + Some(new_decimals), + None + ), + pallet_asset_registry::Error::::Forbidden + ); + }); +} + +#[test] +fn tech_comm_should_update_decimals_when_it_wasnt_set_yet() { + TestNet::reset(); + Hydra::execute_with(|| { + let tech_comm = pallet_collective::RawOrigin::::Members(1, 1); + let new_decimals = 12_u8; + + assert!(Registry::assets(LRNA).unwrap().decimals.is_none()); + + assert_ok!(Registry::update( + tech_comm.into(), + LRNA, + None, + None, + None, + None, + None, + None, + Some(new_decimals), + None + )); + + assert_eq!(Registry::assets(LRNA).unwrap().decimals.unwrap(), new_decimals); + }); +} + +#[test] +fn tech_comm_should_not_update_location_when_asset_exists() { + TestNet::reset(); + Hydra::execute_with(|| { + let tech_comm = pallet_collective::RawOrigin::::Members(1, 1); + + assert!(Registry::locations(LRNA).is_none()); + + assert_noop!( + Registry::update( + tech_comm.into(), + LRNA, + None, + None, + None, + None, + None, + None, + None, + Some(hydradx_runtime::AssetLocation(MultiLocation::new( + 1, + X2(Parachain(MOONBEAM_PARA_ID), GeneralIndex(0)) + ))), + ), + pallet_asset_registry::Error::::Forbidden + ); + }); +} + +#[test] +fn root_should_update_location_when_asset_exists() { + TestNet::reset(); + Hydra::execute_with(|| { + assert!(Registry::locations(LRNA).is_none()); + + let loc_1 = + hydradx_runtime::AssetLocation(MultiLocation::new(1, X2(Parachain(MOONBEAM_PARA_ID), GeneralIndex(0)))); + + //Set location 1-th time. + assert_ok!(Registry::update( + RawOrigin::Root.into(), + LRNA, + None, + None, + None, + None, + None, + None, + None, + Some(loc_1.clone()) + ),); + assert_eq!(Registry::locations(LRNA).unwrap(), loc_1); + assert_eq!(Registry::location_assets(loc_1.clone()).unwrap(), LRNA); + + // Update location if it was previously set. + let loc_2 = + hydradx_runtime::AssetLocation(MultiLocation::new(1, X2(Parachain(INTERLAY_PARA_ID), GeneralIndex(0)))); + + assert_ok!(Registry::update( + RawOrigin::Root.into(), + LRNA, + None, + None, + None, + None, + None, + None, + None, + Some(loc_2.clone()) + ),); + assert_eq!(Registry::locations(LRNA).unwrap(), loc_2); + assert_eq!(Registry::location_assets(loc_2).unwrap(), LRNA); + + assert!(Registry::location_assets(loc_1).is_none()); + }); +} diff --git a/integration-tests/src/lib.rs b/integration-tests/src/lib.rs index 6f2285280..ac6525ff9 100644 --- a/integration-tests/src/lib.rs +++ b/integration-tests/src/lib.rs @@ -1,3 +1,4 @@ +mod asset_registry; mod bonds; mod call_filter; mod circuit_breaker; From bce9bcb8b15512694cb6648ff7a9932c3426d2e4 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 12 Sep 2023 18:28:11 +0200 Subject: [PATCH 18/93] asset-registry: implemented extrinsic to create external assets --- Cargo.lock | 1 + pallets/asset-registry/Cargo.toml | 1 + pallets/asset-registry/src/lib.rs | 65 ++++++++-- pallets/asset-registry/src/tests/mock.rs | 31 +++++ pallets/asset-registry/src/tests/register.rs | 129 +++++++++++++++++++ runtime/hydradx/src/assets.rs | 4 + 6 files changed, 220 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cb47901a0..53779e575 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6209,6 +6209,7 @@ dependencies = [ "frame-system", "frame-system-benchmarking", "hydradx-traits", + "orml-tokens", "orml-traits", "parity-scale-codec", "pretty_assertions", diff --git a/pallets/asset-registry/Cargo.toml b/pallets/asset-registry/Cargo.toml index 4dc2f5383..bc423093b 100644 --- a/pallets/asset-registry/Cargo.toml +++ b/pallets/asset-registry/Cargo.toml @@ -39,6 +39,7 @@ frame-benchmarking = { workspace = true, optional = true } sp-api = { workspace = true, optional = true } [dev-dependencies] +orml-tokens = { workspace = true } sp-io = { workspace = true } polkadot-xcm = { workspace = true } test-utils = { workspace = true } diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 6b5a62184..35b2138fd 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -21,8 +21,9 @@ use frame_support::dispatch::DispatchError; use frame_support::pallet_prelude::*; use frame_support::sp_runtime::traits::CheckedAdd; use frame_system::pallet_prelude::*; +use orml_traits::MultiCurrency; use scale_info::TypeInfo; -use sp_arithmetic::traits::BaseArithmetic; +use sp_arithmetic::traits::{BaseArithmetic, Zero}; use sp_std::convert::TryInto; use sp_std::vec::Vec; @@ -86,6 +87,9 @@ pub mod pallet { /// The maximum length of a name or symbol stored on-chain. type StringLimit: Get; + /// Multi currency mechanism + type Currency: MultiCurrency; + #[pallet::constant] type SequentialIdStartAt: Get; @@ -93,6 +97,14 @@ pub mod pallet { #[pallet::constant] type NativeAssetId: Get; + /// Storage fees for external asset creation. + #[pallet::constant] + type StorageFees: Get; + + /// Storage fees for external asset creation. + #[pallet::constant] + type StorageFeesBeneficiary: Get; + /// Weight information for the extrinsics type WeightInfo: WeightInfo; } @@ -134,6 +146,9 @@ pub mod pallet { /// Origin is fobiddent to set/update value Forbidden, + + /// Balance too low + InsufficientBalance, } #[pallet::type_value] @@ -249,7 +264,7 @@ pub mod pallet { decimals: *decimals, is_sufficient: *is_sufficient, }; - let _ = Pallet::::do_register_asset(*id, details, None) + let _ = Pallet::::do_register_asset(*id, &details, None) .map_err(|_| panic!("Failed to register asset")); }) } @@ -343,7 +358,7 @@ pub mod pallet { is_sufficient, ); - Self::do_register_asset(asset_id, details, location)?; + Self::do_register_asset(asset_id, &details, location)?; Ok(()) } @@ -447,6 +462,34 @@ pub mod pallet { Ok(()) }) } + + #[pallet::call_index(3)] + #[pallet::weight(::WeightInfo::register())] + pub fn register_external(origin: OriginFor, location: T::AssetNativeLocation) -> DispatchResult { + let who = ensure_signed(origin)?; + + if !T::StorageFees::get().is_zero() { + ensure!( + T::Currency::ensure_can_withdraw(T::NativeAssetId::get(), &who, T::StorageFees::get()).is_ok(), + Error::::InsufficientBalance + ); + + T::Currency::transfer( + T::NativeAssetId::get(), + &who, + &T::StorageFeesBeneficiary::get(), + T::StorageFees::get(), + )?; + } + + Self::do_register_asset( + None, + &AssetDetails::new(None, AssetType::External, DEFAULT_ED, None, None, None, false), + Some(location), + )?; + + Ok(()) + } } } @@ -477,7 +520,7 @@ impl Pallet { fn do_register_asset( selected_asset_id: Option, - details: AssetDetails>, + details: &AssetDetails>, location: Option, ) -> Result { let asset_id = if let Some(id) = selected_asset_id { @@ -499,23 +542,23 @@ impl Pallet { })? }; - Assets::::insert(asset_id, &details); + Assets::::insert(asset_id, details); if let Some(name) = details.name.as_ref() { ensure!(!AssetIds::::contains_key(name), Error::::AssetAlreadyRegistered); AssetIds::::insert(name, asset_id); } if let Some(loc) = location { - Self::set_location(asset_id, loc)?; + Self::do_set_location(asset_id, loc)?; } Self::deposit_event(Event::Registered { asset_id, - asset_name: details.name, + asset_name: details.name.clone(), asset_type: details.asset_type, existential_deposit: details.existential_deposit, xcm_rate_limit: details.xcm_rate_limit, - symbol: details.symbol, + symbol: details.symbol.clone(), decimals: details.decimals, is_sufficient: details.is_sufficient, }); @@ -538,7 +581,7 @@ impl Pallet { } else { Self::do_register_asset( asset_id, - AssetDetails::new( + &AssetDetails::new( Some(bounded_name), asset_type, existential_deposit, @@ -641,7 +684,7 @@ impl CreateRegistry for Pallet { Pallet::::do_register_asset( None, - AssetDetails::new(bounded_name, kind.into(), existential_deposit, None, None, None, false), + &AssetDetails::new(bounded_name, kind.into(), existential_deposit, None, None, None, false), None, ) } @@ -693,6 +736,6 @@ impl Create for Pallet { is_sufficient, ); - Self::do_register_asset(asset_id, details, location) + Self::do_register_asset(asset_id, &details, location) } } diff --git a/pallets/asset-registry/src/tests/mock.rs b/pallets/asset-registry/src/tests/mock.rs index 500c5304c..d6429dfe3 100644 --- a/pallets/asset-registry/src/tests/mock.rs +++ b/pallets/asset-registry/src/tests/mock.rs @@ -19,6 +19,7 @@ use frame_support::parameter_types; use frame_system as system; +use orml_traits::parameter_type_with_key; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -36,6 +37,7 @@ pub type Balance = u128; pub const UNIT: Balance = 1_000_000_000_000; pub const ALICE: u64 = 1_000; +pub const TREASURY: u64 = 2_222; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -47,6 +49,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event}, + Tokens: orml_tokens::{Pallet, Call, Storage, Event}, Registry: pallet_asset_registry::{Pallet, Call, Storage, Event}, } @@ -93,8 +96,14 @@ use scale_info::TypeInfo; #[derive(Debug, Default, Encode, Decode, Clone, PartialEq, Eq, TypeInfo, MaxEncodedLen)] pub struct AssetLocation(pub MultiLocation); +parameter_types! { + pub const StoreFees: Balance = 10 * UNIT; + pub const FeesBeneficiarry: u64 = TREASURY; +} + impl pallet_asset_registry::Config for Test { type RuntimeEvent = RuntimeEvent; + type Currency = Tokens; type RegistryOrigin = frame_system::EnsureRoot; type UpdateOrigin = frame_system::EnsureSigned; type AssetId = u32; @@ -102,7 +111,29 @@ impl pallet_asset_registry::Config for Test { type StringLimit = RegistryStringLimit; type SequentialIdStartAt = SequentialIdStart; type NativeAssetId = NativeAssetId; + type StorageFees = StoreFees; + type StorageFeesBeneficiary = FeesBeneficiarry; + type WeightInfo = (); +} + +parameter_type_with_key! { + pub ExistentialDeposits: |_currency_id: AssetId| -> Balance { + 0 + }; +} + +impl orml_tokens::Config for Test { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type Amount = i128; + type CurrencyId = AssetId; type WeightInfo = (); + type ExistentialDeposits = ExistentialDeposits; + type MaxLocks = (); + type DustRemovalWhitelist = Everything; + type MaxReserves = (); + type ReserveIdentifier = (); + type CurrencyHooks = (); } #[derive(Default)] diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index be17d7d9a..675bf1377 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -372,3 +372,132 @@ fn register_should_not_work_when_origin_is_not_allowed() { ); }); } + +#[test] +fn register_external_asset_should_work_when_location_is_provided() { + ExtBuilder::default().build().execute_with(|| { + let expected_id = Pallet::::next_asset_id().unwrap(); + + let key = Junction::from(BoundedVec::try_from(528.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + let alice_balance = 10_000 * UNIT; + Tokens::set_balance(RuntimeOrigin::root(), ALICE, NativeAssetId::get(), alice_balance, 0).unwrap(); + assert_eq!(Tokens::free_balance(NativeAssetId::get(), &TREASURY), 0); + + //Act + assert_ok!(Registry::register_external( + RuntimeOrigin::signed(ALICE), + asset_location.clone() + )); + + //Assert + assert_eq!( + Registry::assets(expected_id), + Some(AssetDetails { + name: None, + asset_type: AssetType::External, + existential_deposit: crate::DEFAULT_ED, + xcm_rate_limit: None, + symbol: None, + decimals: None, + is_sufficient: false + }) + ); + + assert_eq!(Registry::location_assets(asset_location.clone()), Some(expected_id)); + assert_eq!(Registry::locations(expected_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id: expected_id, + asset_name: None, + asset_type: AssetType::External, + existential_deposit: crate::DEFAULT_ED, + xcm_rate_limit: None, + symbol: None, + decimals: None, + is_sufficient: false + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id: expected_id, + location: asset_location + } + .into() + )); + + assert_eq!( + Tokens::free_balance(NativeAssetId::get(), &ALICE), + alice_balance - StoreFees::get() + ); + assert_eq!(Tokens::free_balance(NativeAssetId::get(), &TREASURY), StoreFees::get()); + }); +} + +#[test] +fn register_external_asset_should_not_work_when_location_is_already_used() { + ExtBuilder::default().build().execute_with(|| { + //Arrange + let asset_id = 1; + let name = b"Test asset".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + assert_ok!(Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name), + AssetType::Token, + Some(ed), + Some(symbol), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + )); + + let alice_balance = 10_000 * UNIT; + Tokens::set_balance(RuntimeOrigin::root(), ALICE, NativeAssetId::get(), alice_balance, 0).unwrap(); + assert_eq!(Tokens::free_balance(NativeAssetId::get(), &TREASURY), 0); + + //Act + assert_noop!( + Registry::register_external(RuntimeOrigin::signed(ALICE), asset_location), + Error::::LocationAlreadyRegistered + ); + }); +} + +#[test] +fn register_external_asset_should_not_work_when_user_cant_pay_storage_fees() { + ExtBuilder::default().build().execute_with(|| { + let key = Junction::from(BoundedVec::try_from(528.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + let alice_balance = 10_000 * UNIT; + Tokens::set_balance( + RuntimeOrigin::root(), + ALICE, + NativeAssetId::get(), + StoreFees::get() - 1, + alice_balance, + ) + .unwrap(); + + //Act + assert_noop!( + Registry::register_external(RuntimeOrigin::signed(ALICE), asset_location), + Error::::InsufficientBalance + ); + }); +} diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index b4462fae2..4f36ca215 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -154,17 +154,21 @@ impl pallet_claims::Config for Runtime { parameter_types! { pub const RegistryStrLimit: u32 = 32; pub const SequentialIdOffset: u32 = 1_000_000; + pub const StoreFees: Balance = 100 * UNITS; //TODO: } impl pallet_asset_registry::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RegistryOrigin = EnsureRoot; type UpdateOrigin = SuperMajorityTechCommittee; + type Currency = Currencies; type AssetId = AssetId; type AssetNativeLocation = AssetLocation; type StringLimit = RegistryStrLimit; type SequentialIdStartAt = SequentialIdOffset; type NativeAssetId = NativeAssetId; + type StorageFees = StoreFees; + type StorageFeesBeneficiary = TreasuryAccount; type WeightInfo = weights::registry::HydraWeight; } From ed92f488396ac7a3526ef3264141a376fba327ac Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 13 Sep 2023 14:52:35 +0200 Subject: [PATCH 19/93] asset-registry: added benchmarks for register_external() --- pallets/asset-registry/src/benchmarking.rs | 21 +++- pallets/asset-registry/src/lib.rs | 2 +- pallets/asset-registry/src/weights.rs | 135 +++++++++++++++------ runtime/hydradx/src/weights/registry.rs | 86 ++++++------- 4 files changed, 156 insertions(+), 88 deletions(-) diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index eca77d3f9..c582d02e0 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -20,11 +20,15 @@ use super::*; use crate::types::AssetDetails; -use frame_benchmarking::benchmarks; +use frame_benchmarking::{account, benchmarks}; use frame_system::RawOrigin; +use orml_traits::MultiCurrencyExtended; + +const UNIT: u128 = 1_000_000_000_000; benchmarks! { where_clause { where + T::Currency: MultiCurrencyExtended, T: crate::pallet::Config, } @@ -85,5 +89,20 @@ benchmarks! { })); } + register_external { + let caller: T::AccountId = account("caller", 0, 1); + T::Currency::update_balance(T::NativeAssetId::get(), &caller, (100_000 * UNIT) as i128)?; + + let expected_asset_id = Pallet::::next_asset_id().unwrap(); + let location: T::AssetNativeLocation = Default::default(); + + assert!(Pallet::::location_assets(location.clone()).is_none()); + }: _(RawOrigin::Signed(caller), location.clone()) + verify { + assert_eq!(Pallet::::locations(expected_asset_id), Some(location.clone())); + assert_eq!(Pallet::::location_assets(location), Some(expected_asset_id)); + + } + impl_benchmark_test_suite!(Pallet, crate::tests::mock::ExtBuilder::default().build(), crate::tests::mock::Test); } diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 35b2138fd..de65f5eca 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -464,7 +464,7 @@ pub mod pallet { } #[pallet::call_index(3)] - #[pallet::weight(::WeightInfo::register())] + #[pallet::weight(::WeightInfo::register_external())] pub fn register_external(origin: OriginFor, location: T::AssetNativeLocation) -> DispatchResult { let who = ensure_signed(origin)?; diff --git a/pallets/asset-registry/src/weights.rs b/pallets/asset-registry/src/weights.rs index 046273ebd..3e8d9e787 100644 --- a/pallets/asset-registry/src/weights.rs +++ b/pallets/asset-registry/src/weights.rs @@ -1,13 +1,13 @@ -// This file is part of pallet-asset-registry. +// This file is part of HydraDX. -// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). +// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,28 +15,30 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Autogenerated weights for asset-registry +//! Autogenerated weights for pallet_asset_registry //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 -//! DATE: 2021-06-16, STEPS: [5, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-13, STEPS: 10, REPEAT: 30, LOW RANGE: [], HIGH RANGE: [] +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/basilisk +// target/release/hydradx // benchmark -// --pallet=asset-registry +// pallet // --chain=dev -// --steps=5 -// --repeat=20 -// --extrinsic=* +// --steps=10 +// --repeat=30 // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --template=.maintain/pallet-weight-template.hbs -// --output=lbp.rs +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_asset_registry +// --output=weights.rs +// --extrinsic=* #![allow(unused_parens)] #![allow(unused_imports)] +#![allow(clippy::unnecessary_cast)] use frame_support::{ traits::Get, @@ -44,50 +46,105 @@ use frame_support::{ }; use sp_std::marker::PhantomData; -/// Weight functions needed for lbp. pub trait WeightInfo { fn register() -> Weight; fn update() -> Weight; - fn set_metadata() -> Weight; - fn set_location() -> Weight; + fn register_external() -> Weight; } -/// Weights for lbp using the hack.hydraDX node and recommended hardware. +/// Weights for pallet_asset_registry using the hydraDX node and recommended hardware. pub struct HydraWeight(PhantomData); impl WeightInfo for HydraWeight { + // Storage: AssetRegistry Assets (r:1 w:1) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetIds (r:1 w:1) + // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) + // Storage: AssetRegistry LocationAssets (r:1 w:1) + // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetLocations (r:0 w:1) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) fn register() -> Weight { - Weight::zero() + // Minimum execution time: 37_420 nanoseconds. + Weight::from_ref_time(38_232_000 as u64) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) } - + // Storage: AssetRegistry Assets (r:1 w:1) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetIds (r:1 w:2) + // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetLocations (r:1 w:1) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Storage: AssetRegistry LocationAssets (r:0 w:1) + // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) fn update() -> Weight { - Weight::zero() - } - - fn set_metadata() -> Weight { - Weight::zero() + // Minimum execution time: 45_094 nanoseconds. + Weight::from_ref_time(46_207_000 as u64) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(5 as u64)) } - - fn set_location() -> Weight { - Weight::zero() + // Storage: System Account (r:2 w:2) + // Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + // Storage: AssetRegistry NextAssetId (r:1 w:1) + // Proof: AssetRegistry NextAssetId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + // Storage: AssetRegistry LocationAssets (r:1 w:1) + // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetLocations (r:0 w:1) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Storage: AssetRegistry Assets (r:0 w:1) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + fn register_external() -> Weight { + // Minimum execution time: 62_277 nanoseconds. + Weight::from_ref_time(63_068_000 as u64) + .saturating_add(T::DbWeight::get().reads(4 as u64)) + .saturating_add(T::DbWeight::get().writes(6 as u64)) } } -// For backwards compatibility and tests impl WeightInfo for () { + // Storage: AssetRegistry Assets (r:1 w:1) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetIds (r:1 w:1) + // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) + // Storage: AssetRegistry LocationAssets (r:1 w:1) + // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetLocations (r:0 w:1) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) fn register() -> Weight { - Weight::zero() + // Minimum execution time: 37_420 nanoseconds. + Weight::from_ref_time(38_232_000 as u64) + .saturating_add(RocksDbWeight::get().reads(3 as u64)) + .saturating_add(RocksDbWeight::get().writes(4 as u64)) } - + // Storage: AssetRegistry Assets (r:1 w:1) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetIds (r:1 w:2) + // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetLocations (r:1 w:1) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Storage: AssetRegistry LocationAssets (r:0 w:1) + // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) fn update() -> Weight { - Weight::zero() + // Minimum execution time: 45_094 nanoseconds. + Weight::from_ref_time(46_207_000 as u64) + .saturating_add(RocksDbWeight::get().reads(3 as u64)) + .saturating_add(RocksDbWeight::get().writes(5 as u64)) } - - fn set_metadata() -> Weight { - Weight::zero() - } - - fn set_location() -> Weight { - Weight::zero() + // Storage: System Account (r:2 w:2) + // Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + // Storage: AssetRegistry NextAssetId (r:1 w:1) + // Proof: AssetRegistry NextAssetId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) + // Storage: AssetRegistry LocationAssets (r:1 w:1) + // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetLocations (r:0 w:1) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Storage: AssetRegistry Assets (r:0 w:1) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + fn register_external() -> Weight { + // Minimum execution time: 62_277 nanoseconds. + Weight::from_ref_time(63_068_000 as u64) + .saturating_add(RocksDbWeight::get().reads(4 as u64)) + .saturating_add(RocksDbWeight::get().writes(6 as u64)) } } diff --git a/runtime/hydradx/src/weights/registry.rs b/runtime/hydradx/src/weights/registry.rs index 7ef08decd..df84cfcce 100644 --- a/runtime/hydradx/src/weights/registry.rs +++ b/runtime/hydradx/src/weights/registry.rs @@ -18,25 +18,23 @@ //! Autogenerated weights for pallet_asset_registry //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-06-16, STEPS: 5, REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] +//! DATE: 2023-09-13, STEPS: 10, REPEAT: 30, LOW RANGE: [], HIGH RANGE: [] //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-asset-registry +// --chain=dev +// --steps=10 +// --repeat=30 // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_asset_registry +// --output=weights.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// registry.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs #![allow(unused_parens)] #![allow(unused_imports)] @@ -54,54 +52,48 @@ use pallet_asset_registry::weights::WeightInfo; pub struct HydraWeight(PhantomData); impl WeightInfo for HydraWeight { + // Storage: AssetRegistry Assets (r:1 w:1) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) // Storage: AssetRegistry AssetIds (r:1 w:1) - // Proof Skipped: AssetRegistry AssetIds (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry NextAssetId (r:1 w:1) - // Proof Skipped: AssetRegistry NextAssetId (max_values: Some(1), max_size: None, mode: Measured) + // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) // Storage: AssetRegistry LocationAssets (r:1 w:1) - // Proof Skipped: AssetRegistry LocationAssets (max_values: None, max_size: None, mode: Measured) + // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry AssetLocations (r:0 w:1) - // Proof Skipped: AssetRegistry AssetLocations (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry AssetMetadataMap (r:0 w:1) - // Proof Skipped: AssetRegistry AssetMetadataMap (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry Assets (r:0 w:1) - // Proof Skipped: AssetRegistry Assets (max_values: None, max_size: None, mode: Measured) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) fn register() -> Weight { - // Minimum execution time: 44_102 nanoseconds. - Weight::from_ref_time(44_514_000 as u64) + // Minimum execution time: 37_420 nanoseconds. + Weight::from_ref_time(38_232_000 as u64) .saturating_add(T::DbWeight::get().reads(3 as u64)) - .saturating_add(T::DbWeight::get().writes(6 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) } // Storage: AssetRegistry Assets (r:1 w:1) - // Proof Skipped: AssetRegistry Assets (max_values: None, max_size: None, mode: Measured) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) // Storage: AssetRegistry AssetIds (r:1 w:2) - // Proof Skipped: AssetRegistry AssetIds (max_values: None, max_size: None, mode: Measured) + // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetLocations (r:1 w:1) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Storage: AssetRegistry LocationAssets (r:0 w:1) + // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) fn update() -> Weight { - // Minimum execution time: 28_233 nanoseconds. - Weight::from_ref_time(28_610_000 as u64) - .saturating_add(T::DbWeight::get().reads(2 as u64)) - .saturating_add(T::DbWeight::get().writes(3 as u64)) - } - // Storage: AssetRegistry Assets (r:1 w:0) - // Proof Skipped: AssetRegistry Assets (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry AssetMetadataMap (r:0 w:1) - // Proof Skipped: AssetRegistry AssetMetadataMap (max_values: None, max_size: None, mode: Measured) - fn set_metadata() -> Weight { - // Minimum execution time: 20_998 nanoseconds. - Weight::from_ref_time(21_273_000 as u64) - .saturating_add(T::DbWeight::get().reads(1 as u64)) - .saturating_add(T::DbWeight::get().writes(1 as u64)) + // Minimum execution time: 45_094 nanoseconds. + Weight::from_ref_time(46_207_000 as u64) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(5 as u64)) } - // Storage: AssetRegistry Assets (r:1 w:0) - // Proof Skipped: AssetRegistry Assets (max_values: None, max_size: None, mode: Measured) + // Storage: System Account (r:2 w:2) + // Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + // Storage: AssetRegistry NextAssetId (r:1 w:1) + // Proof: AssetRegistry NextAssetId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) // Storage: AssetRegistry LocationAssets (r:1 w:1) - // Proof Skipped: AssetRegistry LocationAssets (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry AssetLocations (r:1 w:1) - // Proof Skipped: AssetRegistry AssetLocations (max_values: None, max_size: None, mode: Measured) - fn set_location() -> Weight { - // Minimum execution time: 25_144 nanoseconds. - Weight::from_ref_time(25_552_000 as u64) - .saturating_add(T::DbWeight::get().reads(3 as u64)) - .saturating_add(T::DbWeight::get().writes(2 as u64)) + // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) + // Storage: AssetRegistry AssetLocations (r:0 w:1) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Storage: AssetRegistry Assets (r:0 w:1) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + fn register_external() -> Weight { + // Minimum execution time: 62_277 nanoseconds. + Weight::from_ref_time(63_068_000 as u64) + .saturating_add(T::DbWeight::get().reads(4 as u64)) + .saturating_add(T::DbWeight::get().writes(6 as u64)) } } From 797620e1e32948d670727a455beee6048b4f735a Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 27 Sep 2023 16:09:10 +0200 Subject: [PATCH 20/93] asset-registry: WIP sufficiency check --- .../src/insufficient_assets_ed.rs | 77 +++++++++++++ integration-tests/src/lib.rs | 1 + pallets/asset-registry/src/lib.rs | 7 ++ pallets/transaction-multi-payment/src/lib.rs | 2 +- runtime/hydradx/src/assets.rs | 108 +++++++++++++++++- traits/src/registry.rs | 2 + 6 files changed, 192 insertions(+), 5 deletions(-) create mode 100644 integration-tests/src/insufficient_assets_ed.rs diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs new file mode 100644 index 000000000..f8d68e87b --- /dev/null +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -0,0 +1,77 @@ +#![cfg(test)] + +use crate::insufficient_assets_ed::v3::Junction::GeneralIndex; +use crate::polkadot_test_net::*; +use frame_support::assert_ok; +use frame_system::RawOrigin; +use hydradx_runtime::RuntimeOrigin as hydra_origin; +use hydradx_runtime::{AssetRegistry as Registry, Currencies, Tokens, TreasuryAccount, SUFFICIENCY_LOCK}; +use orml_traits::MultiCurrency; +use polkadot_xcm::v3::{self, Junction::Parachain, Junctions::X2, MultiLocation}; +use sp_runtime::{FixedPointNumber, FixedU128}; +use xcm_emulator::TestExt; + +#[test] +fn alice_should_pay_ed_in_hdx_when_receive_transfered_shitcoin() { + TestNet::reset(); + Hydra::execute_with(|| { + //init_omnipool(); + + let doge: AssetId = register_shitcoin(0_u128); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + doge, + 100_000_000 * UNITS, + 0, + )); + + let alice_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + + assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + assert_eq!(treasury_suffyciency_lock(), 0); + + //Act + assert_ok!(Tokens::transfer( + hydra_origin::signed(BOB.into()), + ALICE.into(), + doge, + 1_000_000 * UNITS + )); + + //Assert + let hdx_ed = FixedU128::from_rational(11, 10) + .saturating_mul_int(::ExistentialDeposit::get()); + + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_balance - hdx_ed); + assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 1_000_000 * UNITS); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_balance + hdx_ed + ); + + assert_eq!(treasury_suffyciency_lock(), hdx_ed); + }); +} + +fn register_shitcoin(general_index: u128) -> AssetId { + let location = hydradx_runtime::AssetLocation(MultiLocation::new( + 1, + X2(Parachain(MOONBEAM_PARA_ID), GeneralIndex(general_index)), + )); + + let next_asset_id = Registry::next_asset_id().unwrap(); + Registry::register_external(hydra_origin::signed(BOB.into()), location).unwrap(); + + next_asset_id +} + +fn treasury_suffyciency_lock() -> Balance { + pallet_balances::Locks::::get(TreasuryAccount::get()) + .iter() + .find(|x| x.id == SUFFICIENCY_LOCK) + .map(|p| p.amount) + .unwrap_or_default() +} diff --git a/integration-tests/src/lib.rs b/integration-tests/src/lib.rs index ac6525ff9..4f0e89b19 100644 --- a/integration-tests/src/lib.rs +++ b/integration-tests/src/lib.rs @@ -8,6 +8,7 @@ mod dust; mod dust_removal_whitelist; mod dynamic_fees; mod exchange_asset; +mod insufficient_assets_ed; mod non_native_fee; mod omnipool_init; mod omnipool_liquidity_mining; diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index de65f5eca..35db75aee 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -693,6 +693,13 @@ impl CreateRegistry for Pallet { impl Inspect for Pallet { type Error = DispatchError; type AssetId = T::AssetId; + + fn is_sufficient(id: Self::AssetId) -> bool { + match Self::assets(id) { + Some(a) => a.is_sufficient, + None => false, + } + } } impl Mutate for Pallet { diff --git a/pallets/transaction-multi-payment/src/lib.rs b/pallets/transaction-multi-payment/src/lib.rs index 1a3f4170c..06dc37f65 100644 --- a/pallets/transaction-multi-payment/src/lib.rs +++ b/pallets/transaction-multi-payment/src/lib.rs @@ -308,7 +308,7 @@ impl Pallet where BalanceOf: FixedPointOperand, { - fn account_currency(who: &T::AccountId) -> AssetIdOf { + pub fn account_currency(who: &T::AccountId) -> AssetIdOf { Pallet::::get_currency(who).unwrap_or_else(T::NativeAssetId::get) } diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 4f36ca215..ee1c983ca 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -23,7 +23,7 @@ use hydradx_adapters::{ OracleAssetVolumeProvider, OraclePriceProviderAdapterForOmnipool, PriceAdjustmentAdapter, VestingInfo, }; use hydradx_adapters::{RelayChainBlockHashProvider, RelayChainBlockNumberProvider}; -use hydradx_traits::{AssetKind, AssetPairAccountIdFor, OraclePeriod, Source}; +use hydradx_traits::{registry::Inspect, AssetKind, AssetPairAccountIdFor, NativePriceOracle, OraclePeriod, Source}; use pallet_currencies::BasicCurrencyAdapter; use pallet_omnipool::traits::EnsurePriceWithin; use pallet_otc::NamedReserveIdentifier; @@ -71,12 +71,112 @@ pub struct CurrencyHooks; impl MutationHooks for CurrencyHooks { type OnDust = Duster; type OnSlash = (); - type PreDeposit = (); + type PreDeposit = SufficiencyCheck; type PostDeposit = (); - type PreTransfer = (); + type PreTransfer = SufficiencyCheck; type PostTransfer = (); type OnNewTokenAccount = AddTxAssetOnAccount; - type OnKilledTokenAccount = RemoveTxAssetOnKilled; + type OnKilledTokenAccount = (RemoveTxAssetOnKilled, OnKilledTokenAccount); +} + +use frame_support::traits::LockIdentifier; +use orml_traits::currency::{MultiCurrency, MultiLockableCurrency, OnDeposit, OnTransfer}; +use orml_traits::Happened; +use sp_runtime::{DispatchResult, FixedPointNumber}; + +pub const SUFFICIENCY_LOCK: LockIdentifier = *b"suffchck"; +pub struct SufficiencyCheck; +impl SufficiencyCheck { + fn on_funds(asset: AssetId, paying_account: &AccountId) -> DispatchResult { + //NOTE: account existance means it already paid ED + //TODO: make sure try_get works as expected - storage returns valueQuery + if orml_tokens::Accounts::::try_get(paying_account, asset).is_err() + && !AssetRegistry::is_sufficient(asset) + { + //TODO: make configurable + let ed = FixedU128::from_rational(11, 10) + .saturating_mul_int(::ExistentialDeposit::get()); + + let fee_payment_asset = MultiTransactionPayment::account_currency(paying_account); + + //TODO: handle unwrap + let ed = MultiTransactionPayment::price(fee_payment_asset) + .unwrap() + .saturating_mul_int(ed); + + >::transfer( + fee_payment_asset, + paying_account, + &TreasuryAccount::get(), + ed, + )?; + + let to_lock = pallet_balances::Locks::::get(TreasuryAccount::get()) + .iter() + .find(|x| x.id == SUFFICIENCY_LOCK) + .map(|p| p.amount) + .unwrap_or_default() + .saturating_add(ed); + + //NOTE: this probably should be frozen or something - we can end up in situation when + //locked tokens are not enough to return ED to all users becase locks overlay + >::set_lock( + SUFFICIENCY_LOCK, + NativeAssetId::get(), + &TreasuryAccount::get(), + to_lock, + )?; + + frame_system::Pallet::::inc_sufficients(paying_account); + } + + Ok(()) + } +} + +impl OnTransfer for SufficiencyCheck { + fn on_transfer(asset: AssetId, _from: &AccountId, to: &AccountId, _amount: Balance) -> DispatchResult { + Self::on_funds(asset, to) + } +} + +impl OnDeposit for SufficiencyCheck { + fn on_deposit(asset: AssetId, to: &AccountId, _amount: Balance) -> DispatchResult { + Self::on_funds(asset, to) + } +} + +pub struct OnKilledTokenAccount; +impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { + fn happened((who, _asset): &(AccountId, AssetId)) { + //TODO: unlock ED + + let ed = FixedU128::from_rational(11, 10) + .saturating_mul_int(::ExistentialDeposit::get()); + + let to_lock = pallet_balances::Locks::::get(TreasuryAccount::get()) + .iter() + .find(|x| x.id == SUFFICIENCY_LOCK) + .map(|p| p.amount) + .unwrap_or_default() + .saturating_sub(ed); + + //NOTE: this probably should be frozen or something - we can end up in situation when + //locked tokens are not enough to return ED to all users becase locks overlay + //TODO: at least log error + let _ = >::set_lock( + SUFFICIENCY_LOCK, + NativeAssetId::get(), + &TreasuryAccount::get(), + to_lock, + ); + + //TODO: lock error + let _ = + >::transfer(NativeAssetId::get(), &TreasuryAccount::get(), who, ed); + + frame_system::Pallet::::dec_sufficients(who); + } } impl orml_tokens::Config for Runtime { diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 9514b4b4d..a3bed6e39 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -78,6 +78,8 @@ use frame_support::dispatch::Parameter; pub trait Inspect { type Error; type AssetId: Parameter; + + fn is_sufficient(id: Self::AssetId) -> bool; } #[allow(clippy::too_many_arguments)] From 49f793a20a46bb5cffe6b5a3747e9f758d69d214 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 27 Sep 2023 16:48:22 +0200 Subject: [PATCH 21/93] asset-registry: wip suffiency check, remove lock when all tokens should be unlocked --- .../src/insufficient_assets_ed.rs | 84 ++++++++++++++++++- runtime/hydradx/src/assets.rs | 22 +++-- 2 files changed, 97 insertions(+), 9 deletions(-) diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index f8d68e87b..6f757dda0 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -15,8 +15,6 @@ use xcm_emulator::TestExt; fn alice_should_pay_ed_in_hdx_when_receive_transfered_shitcoin() { TestNet::reset(); Hydra::execute_with(|| { - //init_omnipool(); - let doge: AssetId = register_shitcoin(0_u128); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), @@ -56,6 +54,88 @@ fn alice_should_pay_ed_in_hdx_when_receive_transfered_shitcoin() { }); } +#[test] +fn alice_should_pay_ed_in_hdx_when_shitcoin_was_depositted() { + TestNet::reset(); + Hydra::execute_with(|| { + let doge: AssetId = register_shitcoin(0_u128); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + doge, + 100_000_000 * UNITS, + 0, + )); + + let alice_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + + assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + assert_eq!(treasury_suffyciency_lock(), 0); + + //Act + assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000_000 * UNITS)); + + //Assert + let hdx_ed = FixedU128::from_rational(11, 10) + .saturating_mul_int(::ExistentialDeposit::get()); + + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_balance - hdx_ed); + assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 1_000_000 * UNITS); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_balance + hdx_ed + ); + + assert_eq!(treasury_suffyciency_lock(), hdx_ed); + }); +} + +#[test] +fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_hdx() { + TestNet::reset(); + Hydra::execute_with(|| { + let doge: AssetId = register_shitcoin(0_u128); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + doge, + 100_000_000 * UNITS, + 0, + )); + + assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000_000 * UNITS)); + + let alice_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + + assert_eq!(treasury_suffyciency_lock(), 1100000000000_u128); + + //Act + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + doge, + 1_000_000 * UNITS + )); + + //Assert + let hdx_ed = FixedU128::from_rational(11, 10) + .saturating_mul_int(::ExistentialDeposit::get()); + + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_balance + hdx_ed); + assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_balance - hdx_ed + ); + + assert_eq!(treasury_suffyciency_lock(), 0); + }); +} + fn register_shitcoin(general_index: u128) -> AssetId { let location = hydradx_runtime::AssetLocation(MultiLocation::new( 1, diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index ee1c983ca..9464a1a7b 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -82,7 +82,7 @@ impl MutationHooks for CurrencyHooks { use frame_support::traits::LockIdentifier; use orml_traits::currency::{MultiCurrency, MultiLockableCurrency, OnDeposit, OnTransfer}; use orml_traits::Happened; -use sp_runtime::{DispatchResult, FixedPointNumber}; +use sp_runtime::{traits::Zero, DispatchResult, FixedPointNumber}; pub const SUFFICIENCY_LOCK: LockIdentifier = *b"suffchck"; pub struct SufficiencyCheck; @@ -164,12 +164,20 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { //NOTE: this probably should be frozen or something - we can end up in situation when //locked tokens are not enough to return ED to all users becase locks overlay //TODO: at least log error - let _ = >::set_lock( - SUFFICIENCY_LOCK, - NativeAssetId::get(), - &TreasuryAccount::get(), - to_lock, - ); + if to_lock.is_zero() { + let _ = >::remove_lock( + SUFFICIENCY_LOCK, + NativeAssetId::get(), + &TreasuryAccount::get(), + ); + } else { + let _ = >::set_lock( + SUFFICIENCY_LOCK, + NativeAssetId::get(), + &TreasuryAccount::get(), + to_lock, + ); + } //TODO: lock error let _ = From faad304ae99e0a851b225b44ddb81430b5e0a1ae Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 28 Sep 2023 17:20:47 +0200 Subject: [PATCH 22/93] asset-registry: added tests for sufficiency check --- .../src/insufficient_assets_ed.rs | 792 +++++++++++++++++- integration-tests/src/polkadot_test_net.rs | 16 +- runtime/hydradx/src/assets.rs | 57 +- 3 files changed, 813 insertions(+), 52 deletions(-) diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index 6f757dda0..5d1c8332d 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -2,17 +2,21 @@ use crate::insufficient_assets_ed::v3::Junction::GeneralIndex; use crate::polkadot_test_net::*; -use frame_support::assert_ok; +use frame_support::{assert_noop, assert_ok}; use frame_system::RawOrigin; use hydradx_runtime::RuntimeOrigin as hydra_origin; -use hydradx_runtime::{AssetRegistry as Registry, Currencies, Tokens, TreasuryAccount, SUFFICIENCY_LOCK}; +use hydradx_runtime::{ + AssetRegistry as Registry, Currencies, InsufficientEDinHDX, MultiTransactionPayment, Tokens, TreasuryAccount, + SUFFICIENCY_LOCK, +}; +use hydradx_traits::NativePriceOracle; use orml_traits::MultiCurrency; use polkadot_xcm::v3::{self, Junction::Parachain, Junctions::X2, MultiLocation}; -use sp_runtime::{FixedPointNumber, FixedU128}; +use sp_runtime::FixedPointNumber; use xcm_emulator::TestExt; #[test] -fn alice_should_pay_ed_in_hdx_when_receive_transfered_shitcoin() { +fn alice_should_pay_ed_in_hdx_when_receive_insufficient_asset() { TestNet::reset(); Hydra::execute_with(|| { let doge: AssetId = register_shitcoin(0_u128); @@ -39,23 +43,23 @@ fn alice_should_pay_ed_in_hdx_when_receive_transfered_shitcoin() { )); //Assert - let hdx_ed = FixedU128::from_rational(11, 10) - .saturating_mul_int(::ExistentialDeposit::get()); - - assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_balance - hdx_ed); + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_balance - InsufficientEDinHDX::get() + ); assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 1_000_000 * UNITS); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_balance + hdx_ed + treasury_balance + InsufficientEDinHDX::get() ); - assert_eq!(treasury_suffyciency_lock(), hdx_ed); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); }); } #[test] -fn alice_should_pay_ed_in_hdx_when_shitcoin_was_depositted() { +fn alice_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted_to_her() { TestNet::reset(); Hydra::execute_with(|| { let doge: AssetId = register_shitcoin(0_u128); @@ -77,18 +81,18 @@ fn alice_should_pay_ed_in_hdx_when_shitcoin_was_depositted() { assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000_000 * UNITS)); //Assert - let hdx_ed = FixedU128::from_rational(11, 10) - .saturating_mul_int(::ExistentialDeposit::get()); - - assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_balance - hdx_ed); + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_balance - InsufficientEDinHDX::get() + ); assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 1_000_000 * UNITS); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_balance + hdx_ed + treasury_balance + InsufficientEDinHDX::get() ); - assert_eq!(treasury_suffyciency_lock(), hdx_ed); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); }); } @@ -121,17 +125,763 @@ fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_hdx )); //Assert - let hdx_ed = FixedU128::from_rational(11, 10) - .saturating_mul_int(::ExistentialDeposit::get()); + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_balance + InsufficientEDinHDX::get() + ); + assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_balance - InsufficientEDinHDX::get() + ); + + assert_eq!(treasury_suffyciency_lock(), 0); + }); +} + +#[test] +fn alice_should_pay_ed_only_once_when_received_insufficient_asset() { + TestNet::reset(); + Hydra::execute_with(|| { + let doge: AssetId = register_shitcoin(0_u128); + let fee_asset = BTC; + + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + doge, + 100_000_000 * UNITS, + 0, + )); + + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + fee_asset, + 1_000_000, + 0, + )); + + assert_ok!(MultiTransactionPayment::set_currency( + hydra_origin::signed(ALICE.into()), + fee_asset + )); + + assert_ok!(Tokens::transfer( + hydra_origin::signed(BOB.into()), + ALICE.into(), + doge, + 1_000_000 * UNITS + )); + + let alice_fee_asset_balance = Currencies::free_balance(fee_asset, &ALICE.into()); + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + let treasury_fee_asset_balance = Currencies::free_balance(fee_asset, &TreasuryAccount::get()); + + //Act + assert_ok!(Tokens::transfer( + hydra_origin::signed(BOB.into()), + ALICE.into(), + doge, + 1_000_000 * UNITS + )); + + //Assert + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); + assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 2_000_000 * UNITS); + assert_eq!( + Currencies::free_balance(fee_asset, &ALICE.into()), + alice_fee_asset_balance + ); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance + ); + assert_eq!( + Currencies::free_balance(fee_asset, &TreasuryAccount::get()), + treasury_fee_asset_balance + ); + + let ed_in_hdx: Balance = MultiTransactionPayment::price(fee_asset) + .unwrap() + .saturating_mul_int(InsufficientEDinHDX::get()); + assert_eq!(treasury_suffyciency_lock(), ed_in_hdx); + }); +} + +#[test] +fn alice_should_pay_ed_only_once_when_insufficient_asset_is_depositted_to_her() { + TestNet::reset(); + Hydra::execute_with(|| { + let doge: AssetId = register_shitcoin(0_u128); + let fee_asset = BTC; + + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + fee_asset, + 1_000_000, + 0, + )); + + assert_ok!(MultiTransactionPayment::set_currency( + hydra_origin::signed(ALICE.into()), + fee_asset + )); + + assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000 * UNITS)); + + let alice_fee_asset_balance = Currencies::free_balance(fee_asset, &ALICE.into()); + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + let treasury_fee_asset_balance = Currencies::free_balance(fee_asset, &TreasuryAccount::get()); + + //Act + assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000 * UNITS)); + + //Assert + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); + assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 2_000 * UNITS); + assert_eq!( + Currencies::free_balance(fee_asset, &ALICE.into()), + alice_fee_asset_balance + ); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance + ); + assert_eq!( + Currencies::free_balance(fee_asset, &TreasuryAccount::get()), + treasury_fee_asset_balance + ); + let ed_in_hdx: Balance = MultiTransactionPayment::price(fee_asset) + .unwrap() + .saturating_mul_int(InsufficientEDinHDX::get()); + assert_eq!(treasury_suffyciency_lock(), ed_in_hdx); + }); +} + +#[test] +fn hdx_ed_should_be_released_in_hdx_when_alice_account_is_killed_and_ed_was_paid_in_fee_asset() { + TestNet::reset(); + Hydra::execute_with(|| { + let doge: AssetId = register_shitcoin(0_u128); + let fee_asset = BTC; + + //NOTE: this is imporatant for this tests - it basically mean that Bob already paid ED. + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + doge, + 100_000_000 * UNITS, + 0, + )); + + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + fee_asset, + 1_000_000, + 0, + )); + + assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000_000 * UNITS)); + assert_ok!(MultiTransactionPayment::set_currency( + hydra_origin::signed(ALICE.into()), + fee_asset + )); + + let alice_fee_asset_balance = Currencies::free_balance(fee_asset, &ALICE.into()); + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + let treasury_fee_asset_balance = Currencies::free_balance(fee_asset, &TreasuryAccount::get()); + + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + //Act + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + doge, + 1_000_000 * UNITS + )); + + //Assert + //NOTE: we always returns ED in HDX + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_hdx_balance + InsufficientEDinHDX::get() + ); + assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + assert_eq!( + Currencies::free_balance(fee_asset, &ALICE.into()), + alice_fee_asset_balance + ); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance - InsufficientEDinHDX::get() + ); + assert_eq!( + Currencies::free_balance(fee_asset, &TreasuryAccount::get()), + treasury_fee_asset_balance + ); + assert_eq!(treasury_suffyciency_lock(), 0); + }); +} + +#[test] +fn tx_should_fail_with_keepalive_err_when_dest_account_cant_pay_ed() { + TestNet::reset(); + Hydra::execute_with(|| { + let doge: AssetId = register_shitcoin(0_u128); + let fee_asset = BTC; + + assert_ok!(MultiTransactionPayment::set_currency( + hydra_origin::signed(ALICE.into()), + fee_asset + )); + + let ed_in_hdx: Balance = MultiTransactionPayment::price(fee_asset) + .unwrap() + .saturating_mul_int(InsufficientEDinHDX::get()); + assert!(Tokens::free_balance(fee_asset, &ALICE.into()) < ed_in_hdx); + + assert_noop!( + Tokens::deposit(doge, &ALICE.into(), 1_000_000 * UNITS), + orml_tokens::Error::::KeepAlive + ); + }); +} + +#[test] +fn alice_should_pay_ed_in_fee_asset_when_receive_insufficient_asset() { + TestNet::reset(); + Hydra::execute_with(|| { + let doge: AssetId = register_shitcoin(0_u128); + let fee_asset = BTC; + + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + doge, + 100_000_000 * UNITS, + 0, + )); + + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + fee_asset, + 1_000_000, + 0, + )); + + assert_ok!(MultiTransactionPayment::set_currency( + hydra_origin::signed(ALICE.into()), + fee_asset + )); + + let alice_fee_asset_balance = Currencies::free_balance(fee_asset, &ALICE.into()); + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + let treasury_fee_asset_balance = Currencies::free_balance(fee_asset, &TreasuryAccount::get()); - assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_balance + hdx_ed); assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + assert_eq!(treasury_suffyciency_lock(), 0); + + //Act + assert_ok!(Tokens::transfer( + hydra_origin::signed(BOB.into()), + ALICE.into(), + doge, + 1_000_000 * UNITS + )); + + //Assert + let ed_in_hdx: Balance = MultiTransactionPayment::price(fee_asset) + .unwrap() + .saturating_mul_int(InsufficientEDinHDX::get()); + + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); + assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 1_000_000 * UNITS); + assert_eq!( + Currencies::free_balance(fee_asset, &ALICE.into()), + alice_fee_asset_balance - ed_in_hdx + ); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_balance - hdx_ed + treasury_hdx_balance ); + assert_eq!( + Currencies::free_balance(fee_asset, &TreasuryAccount::get()), + treasury_fee_asset_balance + ed_in_hdx + ); + assert_eq!(treasury_suffyciency_lock(), ed_in_hdx); + }); +} + +#[test] +fn grandfathered_account_should_receive_hdx_when_account_is_killed() { + //NOTE: this is case simulating old account that received insufficient asset before sufficiency + //check and didn't paid ED. This test is important becase grandfathered accounts doesn't have + //incremented `sufficients`. + + TestNet::reset(); + Hydra::execute_with(|| { + let dummy: AssetId = 1_000_001; + + assert_ok!(Tokens::deposit(dummy, &ALICE.into(), 1_000_000 * UNITS)); + + let grandfathered_balance = Currencies::free_balance(HDX, &GRANDFATHERED_UNPAID_ED.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + + let dummy_balance = Currencies::free_balance(dummy, &GRANDFATHERED_UNPAID_ED.into()); + //Act + assert_ok!(Tokens::transfer( + hydra_origin::signed(GRANDFATHERED_UNPAID_ED.into()), + ALICE.into(), + dummy, + dummy_balance + )); + + //Assert + assert_eq!( + Currencies::free_balance(HDX, &GRANDFATHERED_UNPAID_ED.into()), + grandfathered_balance + InsufficientEDinHDX::get() + ); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance - InsufficientEDinHDX::get() + ); + + //NOTE: this is zero becasue Alice paid ED and it was paid to grandfathered + assert_eq!(treasury_suffyciency_lock(), 0); + }); +} + +#[test] +fn sufficient_asset_should_not_pay_ed_to_treasury_when_transfered_or_deposited() { + TestNet::reset(); + Hydra::execute_with(|| { + let doge = register_shitcoin(0_u128); + let sufficient_asset = DAI; + //This pays ED. + assert_ok!(Tokens::deposit(doge, &BOB.into(), 100_000_000 * UNITS,)); + + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let alice_sufficient_asset_balance = Currencies::free_balance(DAI, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + //Act 1 - transfer + assert_ok!(Tokens::transfer( + hydra_origin::signed(BOB.into()), + ALICE.into(), + sufficient_asset, + 1_000_000 * UNITS + )); + + //Assert + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); + assert_eq!( + Currencies::free_balance(sufficient_asset, &ALICE.into()), + alice_sufficient_asset_balance + 1_000_000 * UNITS + ); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance + ); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + //Arrange 2 + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let alice_sufficient_asset_balance = Currencies::free_balance(DAI, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + + //Act 2 - deposit + assert_ok!(Tokens::deposit(sufficient_asset, &ALICE.into(), 1_000_000 * UNITS)); + + //Assert + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); + assert_eq!( + Currencies::free_balance(sufficient_asset, &ALICE.into()), + alice_sufficient_asset_balance + 1_000_000 * UNITS + ); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance + ); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + }); +} + +#[test] +fn sufficient_asset_should_not_release_ed_from_treasury_when_account_is_killed() { + TestNet::reset(); + Hydra::execute_with(|| { + let sufficient_asset = DAI; + + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let alice_sufficient_asset_balance = Currencies::free_balance(DAI, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + + assert_eq!(treasury_suffyciency_lock(), 0); + + //Act + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + sufficient_asset, + alice_sufficient_asset_balance + )); + + //Assert + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); + assert_eq!(Currencies::free_balance(sufficient_asset, &ALICE.into()), 0); + //NOTE: make sure storage was killed + assert!(orml_tokens::Accounts::::try_get( + &sp_runtime::AccountId32::from(ALICE), + sufficient_asset + ) + .is_err()); + + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance + ); + assert_eq!(treasury_suffyciency_lock(), 0); + }); +} + +#[test] +fn each_insufficient_asset_should_pay_ed_when_transfer_or_depositted() { + TestNet::reset(); + Hydra::execute_with(|| { + let sht1: AssetId = register_shitcoin(0_u128); + let sht2: AssetId = register_shitcoin(1_u128); + let sht3: AssetId = register_shitcoin(2_u128); + let sht4: AssetId = register_shitcoin(3_u128); + + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + assert_eq!(treasury_suffyciency_lock(), 0); + + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + sht1, + 100_000_000 * UNITS, + 0, + )); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + sht2, + 100_000_000 * UNITS, + 0, + )); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + sht3, + 100_000_000 * UNITS, + 0, + )); + + //Act + assert_ok!(Tokens::transfer( + hydra_origin::signed(BOB.into()), + ALICE.into(), + sht1, + 10_000 * UNITS + )); + + assert_ok!(Tokens::transfer( + hydra_origin::signed(BOB.into()), + ALICE.into(), + sht3, + 10_000 * UNITS + )); + + assert_ok!(Tokens::transfer( + hydra_origin::signed(BOB.into()), + ALICE.into(), + sht2, + 10_000 * UNITS + )); + + assert_ok!(Tokens::deposit(sht4, &ALICE.into(), 1_000_000 * UNITS)); + + //Assert + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_hdx_balance - InsufficientEDinHDX::get() * 4 + ); + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance + InsufficientEDinHDX::get() * 4 + ); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 4); + }); +} + +#[test] +fn each_insufficient_asset_should_release_ed_when_account_is_killed() { + TestNet::reset(); + Hydra::execute_with(|| { + let sht1: AssetId = register_shitcoin(0_u128); + let sht2: AssetId = register_shitcoin(1_u128); + let sht3: AssetId = register_shitcoin(2_u128); + let sht4: AssetId = register_shitcoin(3_u128); + + //so bob doesn't pay ed + assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), BOB.into(), sht1, 1, 0)); + assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), BOB.into(), sht2, 1, 0)); + assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), BOB.into(), sht3, 1, 0)); + assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), BOB.into(), sht4, 1, 0)); + + assert_ok!(Tokens::deposit(sht1, &ALICE.into(), 10_000 * UNITS)); + assert_ok!(Tokens::deposit(sht2, &ALICE.into(), 10_000 * UNITS)); + assert_ok!(Tokens::deposit(sht3, &ALICE.into(), 10_000 * UNITS)); + assert_ok!(Tokens::deposit(sht4, &ALICE.into(), 10_000 * UNITS)); + + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 4); + + //Act 1 + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + sht1, + 10_000 * UNITS + )); + + //Assert 1 + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_hdx_balance + InsufficientEDinHDX::get() * 1 + ); + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance - InsufficientEDinHDX::get() + ); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 3); + + //Act 2 + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + sht2, + 10_000 * UNITS + )); + + //Assert 2 + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_hdx_balance + InsufficientEDinHDX::get() * 2 + ); + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance - InsufficientEDinHDX::get() * 2 + ); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 2); + + //Act 3 + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + sht3, + 10_000 * UNITS + )); + + //Assert 3 + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_hdx_balance + InsufficientEDinHDX::get() * 3 + ); + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance - InsufficientEDinHDX::get() * 3 + ); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + //Act 4 + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + sht4, + 10_000 * UNITS + )); + + //Assert 3 + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_hdx_balance + InsufficientEDinHDX::get() * 4 + ); + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance - InsufficientEDinHDX::get() * 4 + ); + assert_eq!(treasury_suffyciency_lock(), 0); + }); +} + +#[test] +fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { + TestNet::reset(); + Hydra::execute_with(|| { + let sht1: AssetId = register_shitcoin(0_u128); + let sht2: AssetId = register_shitcoin(1_u128); + let sht3: AssetId = register_shitcoin(2_u128); + let sht4: AssetId = register_shitcoin(3_u128); + + //so bob doesn't pay ed + assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), BOB.into(), sht1, 1, 0)); + assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), BOB.into(), sht2, 1, 0)); + assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), BOB.into(), sht3, 1, 0)); + assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), BOB.into(), sht4, 1, 0)); + + assert_ok!(Tokens::deposit(sht1, &ALICE.into(), 10_000 * UNITS)); + assert_ok!(Tokens::deposit(sht4, &ALICE.into(), 10_000 * UNITS)); + //NOTE: set_balance baypass mutation hooks so these doesn't pay ED + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + sht2, + 10_000 * UNITS, + 0 + )); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + sht3, + 10_000 * UNITS, + 0 + )); + + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 2); + + //Act 1 + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + sht1, + 10_000 * UNITS + )); + + //Assert 1 + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_hdx_balance + InsufficientEDinHDX::get() + ); + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance - InsufficientEDinHDX::get() + ); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + //Arrange 2 + let alice_dai_balance = Currencies::free_balance(DAI, &ALICE.into()); + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + + //Act 2 + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + DAI, + alice_dai_balance + )); + + //Assert 2 - sufficient asset so nothing should change + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance + ); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + //Arrange 3 + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + + //Act 3 + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + sht2, + 10_000 * UNITS + )); + + //Assert 3 + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_hdx_balance + InsufficientEDinHDX::get() + ); + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance - InsufficientEDinHDX::get() + ); + assert_eq!(treasury_suffyciency_lock(), 0); + + //Arrange 4 + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + + //Act 4 - unlocking ED for account that doesn't paid ED + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + sht3, + 10_000 * UNITS + )); + + //Assert 4 + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_hdx_balance + InsufficientEDinHDX::get() + ); + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance - InsufficientEDinHDX::get() + ); + assert_eq!(treasury_suffyciency_lock(), 0); + + //Arrange 5 + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + + //Act 5 - unlocking ED for account that doesn't paid ED + assert_ok!(Tokens::transfer( + hydra_origin::signed(ALICE.into()), + BOB.into(), + sht4, + 10_000 * UNITS + )); + + //Assert 5 + assert_eq!( + Currencies::free_balance(HDX, &ALICE.into()), + alice_hdx_balance + InsufficientEDinHDX::get() + ); + assert_eq!( + Currencies::free_balance(HDX, &TreasuryAccount::get()), + treasury_hdx_balance - InsufficientEDinHDX::get() + ); assert_eq!(treasury_suffyciency_lock(), 0); }); } diff --git a/integration-tests/src/polkadot_test_net.rs b/integration-tests/src/polkadot_test_net.rs index 2ede45b21..331647fca 100644 --- a/integration-tests/src/polkadot_test_net.rs +++ b/integration-tests/src/polkadot_test_net.rs @@ -24,6 +24,8 @@ pub const ALICE: [u8; 32] = [4u8; 32]; pub const BOB: [u8; 32] = [5u8; 32]; pub const CHARLIE: [u8; 32] = [6u8; 32]; pub const DAVE: [u8; 32] = [7u8; 32]; +//This account received insufficient asset before sufficiency check. +pub const GRANDFATHERED_UNPAID_ED: [u8; 32] = [8u8; 32]; pub const UNITS: Balance = 1_000_000_000_000; @@ -221,12 +223,12 @@ pub fn hydra_ext() -> sp_io::TestExternalities { pallet_asset_registry::GenesisConfig:: { registered_assets: vec![ - (Some(LRNA), Some(b"LRNA".to_vec()), 1_000u128, None, None, None, false), - (Some(DAI), Some(b"DAI".to_vec()), 1_000u128, None, None, None, false), - (Some(DOT), Some(b"DOT".to_vec()), 1_000u128, None, None, None, false), - (Some(ETH), Some(b"ETH".to_vec()), 1_000u128, None, None, None, false), - (Some(BTC), Some(b"BTC".to_vec()), 1_000u128, None, None, None, false), - (Some(ACA), Some(b"ACA".to_vec()), 1_000u128, None, None, None, false), + (Some(LRNA), Some(b"LRNA".to_vec()), 1_000u128, None, None, None, true), + (Some(DAI), Some(b"DAI".to_vec()), 1_000u128, None, None, None, true), + (Some(DOT), Some(b"DOT".to_vec()), 1_000u128, None, None, None, true), + (Some(ETH), Some(b"ETH".to_vec()), 1_000u128, None, None, None, true), + (Some(BTC), Some(b"BTC".to_vec()), 1_000u128, None, None, None, true), + (Some(ACA), Some(b"ACA".to_vec()), 1_000u128, None, None, None, true), // workaround for next_asset_id() to return correct values (None, Some(b"DUMMY".to_vec()), 1_000u128, None, None, None, false), ], @@ -261,6 +263,8 @@ pub fn hydra_ext() -> sp_io::TestExternalities { (omnipool_account.clone(), ETH, eth_amount), (omnipool_account.clone(), BTC, btc_amount), (omnipool_account, DOT, dot_amount), + //Special account for insufficient assets ED tests + (AccountId::from(GRANDFATHERED_UNPAID_ED), 1_000_001, 1_000 * UNITS), ], } .assimilate_storage(&mut t) diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 9464a1a7b..966ff74fd 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -82,34 +82,37 @@ impl MutationHooks for CurrencyHooks { use frame_support::traits::LockIdentifier; use orml_traits::currency::{MultiCurrency, MultiLockableCurrency, OnDeposit, OnTransfer}; use orml_traits::Happened; +use sp_runtime::traits::Bounded; use sp_runtime::{traits::Zero, DispatchResult, FixedPointNumber}; pub const SUFFICIENCY_LOCK: LockIdentifier = *b"suffchck"; +parameter_types! { + pub InsufficientEDinHDX: Balance = FixedU128::from_rational(11, 10) + .saturating_mul_int(::ExistentialDeposit::get()); +} + pub struct SufficiencyCheck; impl SufficiencyCheck { fn on_funds(asset: AssetId, paying_account: &AccountId) -> DispatchResult { //NOTE: account existance means it already paid ED - //TODO: make sure try_get works as expected - storage returns valueQuery if orml_tokens::Accounts::::try_get(paying_account, asset).is_err() && !AssetRegistry::is_sufficient(asset) { - //TODO: make configurable - let ed = FixedU128::from_rational(11, 10) - .saturating_mul_int(::ExistentialDeposit::get()); - let fee_payment_asset = MultiTransactionPayment::account_currency(paying_account); - //TODO: handle unwrap + //NOTE: unwrap should never fail. MutiTransctionPayment should always provide price. let ed = MultiTransactionPayment::price(fee_payment_asset) - .unwrap() - .saturating_mul_int(ed); + .unwrap_or(FixedU128::max_value()) + .saturating_mul_int(InsufficientEDinHDX::get()); + //NOTE: Account doesn't have enough funds to pay ED if this fail. >::transfer( fee_payment_asset, paying_account, &TreasuryAccount::get(), ed, - )?; + ) + .map_err(|_| orml_tokens::Error::::KeepAlive)?; let to_lock = pallet_balances::Locks::::get(TreasuryAccount::get()) .iter() @@ -118,8 +121,6 @@ impl SufficiencyCheck { .unwrap_or_default() .saturating_add(ed); - //NOTE: this probably should be frozen or something - we can end up in situation when - //locked tokens are not enough to return ED to all users becase locks overlay >::set_lock( SUFFICIENCY_LOCK, NativeAssetId::get(), @@ -148,22 +149,19 @@ impl OnDeposit for SufficiencyCheck { pub struct OnKilledTokenAccount; impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { - fn happened((who, _asset): &(AccountId, AssetId)) { - //TODO: unlock ED - - let ed = FixedU128::from_rational(11, 10) - .saturating_mul_int(::ExistentialDeposit::get()); + fn happened((who, asset): &(AccountId, AssetId)) { + if AssetRegistry::is_sufficient(*asset) { + return; + } let to_lock = pallet_balances::Locks::::get(TreasuryAccount::get()) .iter() .find(|x| x.id == SUFFICIENCY_LOCK) .map(|p| p.amount) .unwrap_or_default() - .saturating_sub(ed); + .saturating_sub(InsufficientEDinHDX::get()); - //NOTE: this probably should be frozen or something - we can end up in situation when - //locked tokens are not enough to return ED to all users becase locks overlay - //TODO: at least log error + //TODO: log error if to_lock.is_zero() { let _ = >::remove_lock( SUFFICIENCY_LOCK, @@ -179,11 +177,20 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { ); } - //TODO: lock error - let _ = - >::transfer(NativeAssetId::get(), &TreasuryAccount::get(), who, ed); - - frame_system::Pallet::::dec_sufficients(who); + //TODO: log error + let _ = >::transfer( + NativeAssetId::get(), + &TreasuryAccount::get(), + who, + InsufficientEDinHDX::get(), + ); + + //NOTE: this is necessary becasue grandfathered accounts doesn't have inc-ed suffients by + //this `SufficiencyCheck` so without this `if` it can overflow. + //`set_balanse` also baypass `MutationHooks` + if frame_system::Pallet::::account(who).sufficients > 0 { + frame_system::Pallet::::dec_sufficients(who); + } } } From 6cb908287dbf3529735eda4f1951aa9919226a61 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 29 Sep 2023 10:27:55 +0200 Subject: [PATCH 23/93] asset-registry: added whitelist to suffiency check + tests --- integration-tests/src/bonds.rs | 22 ++++- .../src/insufficient_assets_ed.rs | 88 ++++++++++++++++++- runtime/hydradx/src/assets.rs | 14 ++- runtime/hydradx/src/lib.rs | 1 + 4 files changed, 118 insertions(+), 7 deletions(-) diff --git a/integration-tests/src/bonds.rs b/integration-tests/src/bonds.rs index aa9804208..e2763f903 100644 --- a/integration-tests/src/bonds.rs +++ b/integration-tests/src/bonds.rs @@ -4,17 +4,20 @@ use crate::assert_balance; use crate::polkadot_test_net::*; use frame_support::{assert_noop, assert_ok}; +use frame_system::RawOrigin; use hydradx_traits::CreateRegistry; use orml_traits::MultiCurrency; use xcm_emulator::TestExt; -use hydradx_runtime::{AssetRegistry, Bonds, Currencies, Runtime, RuntimeOrigin}; +use hydradx_runtime::{AssetRegistry, Bonds, Currencies, MultiTransactionPayment, Runtime, RuntimeOrigin, Tokens}; use primitives::constants::time::unix_time::MONTH; #[test] fn issue_bonds_should_work_when_issued_for_native_asset() { Hydra::execute_with(|| { // Arrange + set_fee_asset_and_fund(ALICE.into(), BTC, 1_000_000); + let amount = 100 * UNITS; let fee = ::ProtocolFee::get().mul_ceil(amount); let amount_without_fee: Balance = amount.checked_sub(fee).unwrap(); @@ -50,6 +53,8 @@ fn issue_bonds_should_work_when_issued_for_native_asset() { fn issue_bonds_should_work_when_issued_for_share_asset() { Hydra::execute_with(|| { // Arrange + set_fee_asset_and_fund(ALICE.into(), BTC, 1_000_000); + let amount = 100 * UNITS; let fee = ::ProtocolFee::get().mul_ceil(amount); let amount_without_fee: Balance = amount.checked_sub(fee).unwrap(); @@ -124,3 +129,18 @@ fn issue_bonds_should_not_work_when_issued_for_bond_asset() { ); }); } + +fn set_fee_asset_and_fund(who: AccountId, fee_asset: AssetId, amount: Balance) { + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + who.clone().into(), + fee_asset, + amount, + 0, + )); + + assert_ok!(MultiTransactionPayment::set_currency( + hydradx_runtime::RuntimeOrigin::signed(who.into()), + fee_asset + )); +} diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index 5d1c8332d..dac9ab138 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -2,12 +2,12 @@ use crate::insufficient_assets_ed::v3::Junction::GeneralIndex; use crate::polkadot_test_net::*; -use frame_support::{assert_noop, assert_ok}; +use frame_support::{assert_noop, assert_ok, traits::Contains}; use frame_system::RawOrigin; use hydradx_runtime::RuntimeOrigin as hydra_origin; use hydradx_runtime::{ - AssetRegistry as Registry, Currencies, InsufficientEDinHDX, MultiTransactionPayment, Tokens, TreasuryAccount, - SUFFICIENCY_LOCK, + AssetRegistry as Registry, Currencies, DustRemovalWhitelist, InsufficientEDinHDX, MultiTransactionPayment, Tokens, + TreasuryAccount, SUFFICIENCY_LOCK, }; use hydradx_traits::NativePriceOracle; use orml_traits::MultiCurrency; @@ -886,6 +886,88 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { }); } +#[test] +fn whitelisted_account_should_not_pay_ed_when_transferred_or_deposited() { + TestNet::reset(); + Hydra::execute_with(|| { + let sht1: AssetId = register_shitcoin(0_u128); + let sht2: AssetId = register_shitcoin(1_u128); + + assert_ok!(Tokens::deposit(sht1, &BOB.into(), 1_000_000 * UNITS)); + + let treasury = TreasuryAccount::get(); + + assert!(DustRemovalWhitelist::contains(&treasury)); + assert_eq!(MultiTransactionPayment::account_currency(&treasury), HDX); + + let treasury_hdx_balance = Currencies::free_balance(HDX, &treasury); + + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + //Act 1 + assert_ok!(Tokens::transfer( + hydra_origin::signed(BOB.into()), + treasury.clone(), + sht1, + 10 + )); + + //Assert 1 + assert_eq!(Currencies::free_balance(HDX, &treasury), treasury_hdx_balance); + assert_eq!(Currencies::free_balance(sht1, &treasury), 10); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + //Act 2 + assert_ok!(Tokens::deposit(sht2, &treasury.clone(), 20)); + + //Assert 2 + assert_eq!(Currencies::free_balance(HDX, &treasury), treasury_hdx_balance); + assert_eq!(Currencies::free_balance(sht1, &treasury), 10); + assert_eq!(Currencies::free_balance(sht2, &treasury), 20); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + }); +} + +#[test] +fn whitelisted_account_should_not_release_ed_when_killed() { + TestNet::reset(); + Hydra::execute_with(|| { + let sht1: AssetId = register_shitcoin(0_u128); + let treasury = TreasuryAccount::get(); + + assert_ok!(Tokens::deposit(sht1, &BOB.into(), 1_000_000 * UNITS)); + assert_ok!(Tokens::deposit(sht1, &treasury, 1_000_000 * UNITS)); + + assert!(DustRemovalWhitelist::contains(&treasury)); + assert_eq!(MultiTransactionPayment::account_currency(&treasury), HDX); + let treasury_hdx_balance = Currencies::free_balance(HDX, &treasury); + + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + //Act 1 + assert_ok!(Tokens::transfer( + hydra_origin::signed(treasury.clone().into()), + BOB.into(), + sht1, + 1_000_000 * UNITS + )); + + //Assert 1 + assert_eq!(Currencies::free_balance(HDX, &treasury), treasury_hdx_balance); + assert_eq!(Currencies::free_balance(sht1, &treasury), 0); + assert_eq!(Currencies::free_balance(sht1, &BOB.into()), 2_000_000 * UNITS); + + //BOB already paid ED for this asset + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + assert!(orml_tokens::Accounts::::try_get( + &sp_runtime::AccountId32::from(treasury), + sht1 + ) + .is_err()); + }); +} + fn register_shitcoin(general_index: u128) -> AssetId { let location = hydradx_runtime::AssetLocation(MultiLocation::new( 1, diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 966ff74fd..d1cabb2b0 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -94,6 +94,10 @@ parameter_types! { pub struct SufficiencyCheck; impl SufficiencyCheck { fn on_funds(asset: AssetId, paying_account: &AccountId) -> DispatchResult { + if ::DustRemovalWhitelist::contains(paying_account) { + return Ok(()); + } + //NOTE: account existance means it already paid ED if orml_tokens::Accounts::::try_get(paying_account, asset).is_err() && !AssetRegistry::is_sufficient(asset) @@ -154,6 +158,10 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { return; } + if ::DustRemovalWhitelist::contains(who) { + return; + } + let to_lock = pallet_balances::Locks::::get(TreasuryAccount::get()) .iter() .find(|x| x.id == SUFFICIENCY_LOCK) @@ -185,9 +193,9 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { InsufficientEDinHDX::get(), ); - //NOTE: this is necessary becasue grandfathered accounts doesn't have inc-ed suffients by - //this `SufficiencyCheck` so without this `if` it can overflow. - //`set_balanse` also baypass `MutationHooks` + //NOTE: This is necessary because grandfathered accounts doesn't have inc-ed suffients by + //`SufficiencyCheck` so without check it can overflow. + //`set_balanse` also baypass `MutationHooks` if frame_system::Pallet::::account(who).sufficients > 0 { frame_system::Pallet::::dec_sufficients(who); } diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index d57468eee..a79d2b1ac 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -114,6 +114,7 @@ pub fn get_all_module_accounts() -> Vec { vec![ TreasuryPalletId::get().into_account_truncating(), VestingPalletId::get().into_account_truncating(), + BondsPalletId::get().into_account_truncating(), ] } From 985c401d87f0427b7fd5fe8ea5140a4193f68df6 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 29 Sep 2023 13:20:09 +0200 Subject: [PATCH 24/93] asset-registry: make clippy happy --- integration-tests/src/bonds.rs | 4 +- .../src/insufficient_assets_ed.rs | 38 +++++++++---------- runtime/hydradx/src/assets.rs | 31 +++++++-------- 3 files changed, 33 insertions(+), 40 deletions(-) diff --git a/integration-tests/src/bonds.rs b/integration-tests/src/bonds.rs index e2763f903..ad758fc49 100644 --- a/integration-tests/src/bonds.rs +++ b/integration-tests/src/bonds.rs @@ -133,14 +133,14 @@ fn issue_bonds_should_not_work_when_issued_for_bond_asset() { fn set_fee_asset_and_fund(who: AccountId, fee_asset: AssetId, amount: Balance) { assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), - who.clone().into(), + who.clone(), fee_asset, amount, 0, )); assert_ok!(MultiTransactionPayment::set_currency( - hydradx_runtime::RuntimeOrigin::signed(who.into()), + hydradx_runtime::RuntimeOrigin::signed(who), fee_asset )); } diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index dac9ab138..46a14aa38 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -266,13 +266,13 @@ fn alice_should_pay_ed_only_once_when_insufficient_asset_is_depositted_to_her() } #[test] -fn hdx_ed_should_be_released_in_hdx_when_alice_account_is_killed_and_ed_was_paid_in_fee_asset() { +fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_fee_asset() { TestNet::reset(); Hydra::execute_with(|| { let doge: AssetId = register_shitcoin(0_u128); let fee_asset = BTC; - //NOTE: this is imporatant for this tests - it basically mean that Bob already paid ED. + //NOTE: this is important for this tests - it basically mean that Bob already paid ED. assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), BOB.into(), @@ -429,7 +429,7 @@ fn alice_should_pay_ed_in_fee_asset_when_receive_insufficient_asset() { #[test] fn grandfathered_account_should_receive_hdx_when_account_is_killed() { //NOTE: this is case simulating old account that received insufficient asset before sufficiency - //check and didn't paid ED. This test is important becase grandfathered accounts doesn't have + //check and didn't paid ED. This test is important because grandfathered accounts doesn't have //incremented `sufficients`. TestNet::reset(); @@ -461,7 +461,7 @@ fn grandfathered_account_should_receive_hdx_when_account_is_killed() { treasury_hdx_balance - InsufficientEDinHDX::get() ); - //NOTE: this is zero becasue Alice paid ED and it was paid to grandfathered + //NOTE: this is zero because Alice paid ED and it was paid to grandfathered assert_eq!(treasury_suffyciency_lock(), 0); }); } @@ -551,7 +551,7 @@ fn sufficient_asset_should_not_release_ed_from_treasury_when_account_is_killed() assert_eq!(Currencies::free_balance(sufficient_asset, &ALICE.into()), 0); //NOTE: make sure storage was killed assert!(orml_tokens::Accounts::::try_get( - &sp_runtime::AccountId32::from(ALICE), + sp_runtime::AccountId32::from(ALICE), sufficient_asset ) .is_err()); @@ -574,7 +574,7 @@ fn each_insufficient_asset_should_pay_ed_when_transfer_or_depositted() { let sht4: AssetId = register_shitcoin(3_u128); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); assert_eq!(treasury_suffyciency_lock(), 0); assert_ok!(Tokens::set_balance( @@ -657,7 +657,7 @@ fn each_insufficient_asset_should_release_ed_when_account_is_killed() { assert_ok!(Tokens::deposit(sht4, &ALICE.into(), 10_000 * UNITS)); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 4); //Act 1 @@ -671,7 +671,7 @@ fn each_insufficient_asset_should_release_ed_when_account_is_killed() { //Assert 1 assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance + InsufficientEDinHDX::get() * 1 + alice_hdx_balance + InsufficientEDinHDX::get() ); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), @@ -755,7 +755,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { assert_ok!(Tokens::deposit(sht1, &ALICE.into(), 10_000 * UNITS)); assert_ok!(Tokens::deposit(sht4, &ALICE.into(), 10_000 * UNITS)); - //NOTE: set_balance baypass mutation hooks so these doesn't pay ED + //NOTE: set_balance bypass mutation hooks so these doesn't pay ED assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), ALICE.into(), @@ -772,7 +772,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { )); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 2); //Act 1 @@ -797,7 +797,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { //Arrange 2 let alice_dai_balance = Currencies::free_balance(DAI, &ALICE.into()); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); //Act 2 assert_ok!(Tokens::transfer( @@ -817,7 +817,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { //Arrange 3 let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); //Act 3 assert_ok!(Tokens::transfer( @@ -840,7 +840,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { //Arrange 4 let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); //Act 4 - unlocking ED for account that doesn't paid ED assert_ok!(Tokens::transfer( @@ -863,7 +863,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { //Arrange 5 let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); - let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get().into()); + let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); //Act 5 - unlocking ED for account that doesn't paid ED assert_ok!(Tokens::transfer( @@ -918,7 +918,7 @@ fn whitelisted_account_should_not_pay_ed_when_transferred_or_deposited() { assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); //Act 2 - assert_ok!(Tokens::deposit(sht2, &treasury.clone(), 20)); + assert_ok!(Tokens::deposit(sht2, &treasury, 20)); //Assert 2 assert_eq!(Currencies::free_balance(HDX, &treasury), treasury_hdx_balance); @@ -946,7 +946,7 @@ fn whitelisted_account_should_not_release_ed_when_killed() { //Act 1 assert_ok!(Tokens::transfer( - hydra_origin::signed(treasury.clone().into()), + hydra_origin::signed(treasury.clone()), BOB.into(), sht1, 1_000_000 * UNITS @@ -960,11 +960,7 @@ fn whitelisted_account_should_not_release_ed_when_killed() { //BOB already paid ED for this asset assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); - assert!(orml_tokens::Accounts::::try_get( - &sp_runtime::AccountId32::from(treasury), - sht1 - ) - .is_err()); + assert!(orml_tokens::Accounts::::try_get(&treasury, sht1).is_err()); }); } diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index d1cabb2b0..1ea0be662 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -34,17 +34,21 @@ use primitives::constants::{ currency::{NATIVE_EXISTENTIAL_DEPOSIT, UNITS}, }; +use sp_runtime::{traits::Zero, DispatchResult, FixedPointNumber}; + use frame_support::{ parameter_types, sp_runtime::app_crypto::sp_core::crypto::UncheckedFrom, - sp_runtime::traits::{One, PhantomData}, + sp_runtime::traits::{Bounded, One, PhantomData}, sp_runtime::{FixedU128, Perbill, Permill}, - traits::{AsEnsureOriginWithArg, ConstU32, Contains, EnsureOrigin, NeverEnsureOrigin}, + traits::{AsEnsureOriginWithArg, ConstU32, Contains, EnsureOrigin, LockIdentifier, NeverEnsureOrigin}, BoundedVec, PalletId, }; use frame_system::{EnsureRoot, EnsureSigned, RawOrigin}; -use orml_traits::currency::MutationHooks; -use orml_traits::GetByKey; +use orml_traits::{ + currency::{MultiCurrency, MultiLockableCurrency, MutationHooks, OnDeposit, OnTransfer}, + GetByKey, Happened, +}; use pallet_dynamic_fees::types::FeeParams; use pallet_staking::types::Action; use pallet_staking::SigmoidPercentage; @@ -79,13 +83,8 @@ impl MutationHooks for CurrencyHooks { type OnKilledTokenAccount = (RemoveTxAssetOnKilled, OnKilledTokenAccount); } -use frame_support::traits::LockIdentifier; -use orml_traits::currency::{MultiCurrency, MultiLockableCurrency, OnDeposit, OnTransfer}; -use orml_traits::Happened; -use sp_runtime::traits::Bounded; -use sp_runtime::{traits::Zero, DispatchResult, FixedPointNumber}; +pub const SUFFICIENCY_LOCK: LockIdentifier = *b"insuffEd"; -pub const SUFFICIENCY_LOCK: LockIdentifier = *b"suffchck"; parameter_types! { pub InsufficientEDinHDX: Balance = FixedU128::from_rational(11, 10) .saturating_mul_int(::ExistentialDeposit::get()); @@ -98,7 +97,7 @@ impl SufficiencyCheck { return Ok(()); } - //NOTE: account existance means it already paid ED + //NOTE: account existence means it already paid ED if orml_tokens::Accounts::::try_get(paying_account, asset).is_err() && !AssetRegistry::is_sufficient(asset) { @@ -106,7 +105,7 @@ impl SufficiencyCheck { //NOTE: unwrap should never fail. MutiTransctionPayment should always provide price. let ed = MultiTransactionPayment::price(fee_payment_asset) - .unwrap_or(FixedU128::max_value()) + .unwrap_or_else(FixedU128::max_value) .saturating_mul_int(InsufficientEDinHDX::get()); //NOTE: Account doesn't have enough funds to pay ED if this fail. @@ -169,7 +168,6 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { .unwrap_or_default() .saturating_sub(InsufficientEDinHDX::get()); - //TODO: log error if to_lock.is_zero() { let _ = >::remove_lock( SUFFICIENCY_LOCK, @@ -185,7 +183,6 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { ); } - //TODO: log error let _ = >::transfer( NativeAssetId::get(), &TreasuryAccount::get(), @@ -193,9 +190,9 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { InsufficientEDinHDX::get(), ); - //NOTE: This is necessary because grandfathered accounts doesn't have inc-ed suffients by - //`SufficiencyCheck` so without check it can overflow. - //`set_balanse` also baypass `MutationHooks` + //NOTE: This is necessary because grandfathered accounts doesn't have incremented + //sufficients by `SufficiencyCheck` so without check it can overflow. + //`set_balance` also bypass `MutationHooks` if frame_system::Pallet::::account(who).sufficients > 0 { frame_system::Pallet::::dec_sufficients(who); } From 1156f597f469731e9b9e64a6dc0dd2978499b4a0 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 29 Sep 2023 15:14:43 +0200 Subject: [PATCH 25/93] bump versions --- Cargo.lock | 8 ++++---- integration-tests/Cargo.toml | 2 +- node/Cargo.toml | 2 +- pallets/asset-registry/Cargo.toml | 2 +- traits/Cargo.toml | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 200297606..cfdb3ebb8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3710,7 +3710,7 @@ dependencies = [ [[package]] name = "hydradx" -version = "10.0.1" +version = "10.1.0" dependencies = [ "clap 4.3.9", "cumulus-client-cli", @@ -3935,7 +3935,7 @@ dependencies = [ [[package]] name = "hydradx-traits" -version = "2.6.0" +version = "2.7.0" dependencies = [ "frame-support", "impl-trait-for-tuples", @@ -6216,7 +6216,7 @@ dependencies = [ [[package]] name = "pallet-asset-registry" -version = "2.3.1" +version = "3.0.0" dependencies = [ "frame-benchmarking", "frame-support", @@ -10191,7 +10191,7 @@ dependencies = [ [[package]] name = "runtime-integration-tests" -version = "1.12.1" +version = "1.13.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index 8fa0b5995..4848d0c4b 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runtime-integration-tests" -version = "1.12.1" +version = "1.13.0" description = "Integration tests" authors = ["GalacticCouncil"] edition = "2021" diff --git a/node/Cargo.toml b/node/Cargo.toml index ef67a465f..717dd834b 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx" -version = "10.0.1" +version = "10.1.0" description = "HydraDX node" authors = ["GalacticCouncil"] edition = "2021" diff --git a/pallets/asset-registry/Cargo.toml b/pallets/asset-registry/Cargo.toml index 0f2959058..993254824 100644 --- a/pallets/asset-registry/Cargo.toml +++ b/pallets/asset-registry/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-asset-registry" -version = "2.3.1" +version = "3.0.0" description = "Pallet for asset registry management" authors = ["GalacticCouncil"] edition = "2021" diff --git a/traits/Cargo.toml b/traits/Cargo.toml index 14cbde5f6..8a236ed39 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-traits" -version = "2.6.0" +version = "2.7.0" description = "Shared traits" authors = ["GalacticCouncil"] edition = "2021" From 092a829b2981d749def740cce563c937df0624f4 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 9 Oct 2023 13:26:34 +0200 Subject: [PATCH 26/93] sufficiency-check: added UnsupportedCurrency error + tests --- .../src/insufficient_assets_ed.rs | 46 +++++++++++++++++++ runtime/hydradx/src/assets.rs | 5 +- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index 46a14aa38..bab89c38f 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -964,6 +964,52 @@ fn whitelisted_account_should_not_release_ed_when_killed() { }); } +#[test] +fn tx_should_fail_with_unsupported_currency_error_when_fee_asset_price_wasn_not_provided() { + TestNet::reset(); + Hydra::execute_with(|| { + let sht1: AssetId = register_shitcoin(0_u128); + let fee_asset = BTC; + + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + sht1, + 100_000_000 * UNITS, + 0, + )); + + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + fee_asset, + 1_000_000, + 0, + )); + + assert_ok!(MultiTransactionPayment::set_currency( + hydra_origin::signed(ALICE.into()), + fee_asset + )); + + assert_ok!(MultiTransactionPayment::remove_currency(RawOrigin::Root.into(), BTC)); + + polkadot_run_to_block(2); + + //Act 1 - transfer + assert_noop!( + Tokens::transfer(hydra_origin::signed(BOB.into()), ALICE.into(), sht1, 1_000_000 * UNITS), + pallet_transaction_multi_payment::Error::::UnsupportedCurrency + ); + + //Act 2 - deposit + assert_noop!( + Tokens::deposit(sht1, &ALICE.into(), 1_000_000 * UNITS), + pallet_transaction_multi_payment::Error::::UnsupportedCurrency + ); + }); +} + fn register_shitcoin(general_index: u128) -> AssetId { let location = hydradx_runtime::AssetLocation(MultiLocation::new( 1, diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index b65bf3f1c..19e09dc75 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -46,7 +46,7 @@ use core::ops::RangeInclusive; use frame_support::{ parameter_types, sp_runtime::app_crypto::sp_core::crypto::UncheckedFrom, - sp_runtime::traits::{Bounded, One, PhantomData}, + sp_runtime::traits::{One, PhantomData}, sp_runtime::{FixedU128, Perbill, Permill}, traits::{AsEnsureOriginWithArg, ConstU32, Contains, EnsureOrigin, LockIdentifier, NeverEnsureOrigin}, BoundedVec, PalletId, @@ -113,9 +113,8 @@ impl SufficiencyCheck { { let fee_payment_asset = MultiTransactionPayment::account_currency(paying_account); - //NOTE: unwrap should never fail. MutiTransctionPayment should always provide price. let ed = MultiTransactionPayment::price(fee_payment_asset) - .unwrap_or_else(FixedU128::max_value) + .ok_or(pallet_transaction_multi_payment::Error::::UnsupportedCurrency)? .saturating_mul_int(InsufficientEDinHDX::get()); //NOTE: Account doesn't have enough funds to pay ED if this fail. From e8d8224d8f6399e7dd7243a8dd682247aec423d3 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 9 Oct 2023 14:16:10 +0200 Subject: [PATCH 27/93] asset-registry: removed BoundedString from AssetDetails --- pallets/asset-registry/src/lib.rs | 13 +++++++------ pallets/asset-registry/src/tests/mock.rs | 1 + pallets/asset-registry/src/types.rs | 15 ++++++++------- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 556d208d7..861fbc837 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -59,7 +59,7 @@ pub const DEFAULT_ED: Balance = 1; pub mod pallet { use super::*; - pub type AssetDetailsT = AssetDetails<::AssetId, BoundedVec::StringLimit>>; + pub type AssetDetailsT = AssetDetails<::AssetId, ::StringLimit>; #[pallet::config] pub trait Config: frame_system::Config { @@ -84,9 +84,6 @@ pub mod pallet { /// Asset location type type AssetNativeLocation: Parameter + Member + Default + MaxEncodedLen; - /// The maximum length of a name or symbol stored on-chain. - type StringLimit: Get; - /// Multi currency mechanism type Currency: MultiCurrency; @@ -105,6 +102,10 @@ pub mod pallet { #[pallet::constant] type StorageFeesBeneficiary: Get; + /// The maximum length of a name or symbol stored on-chain. + #[pallet::constant] + type StringLimit: Get; + /// Weight information for the extrinsics type WeightInfo: WeightInfo; } @@ -144,7 +145,7 @@ pub mod pallet { /// Location already registered with different asset LocationAlreadyRegistered, - /// Origin is fobiddent to set/update value + /// Origin is forbidden to set/update value Forbidden, /// Balance too low @@ -520,7 +521,7 @@ impl Pallet { fn do_register_asset( selected_asset_id: Option, - details: &AssetDetails>, + details: &AssetDetails, location: Option, ) -> Result { let asset_id = if let Some(id) = selected_asset_id { diff --git a/pallets/asset-registry/src/tests/mock.rs b/pallets/asset-registry/src/tests/mock.rs index d6429dfe3..9dc90e806 100644 --- a/pallets/asset-registry/src/tests/mock.rs +++ b/pallets/asset-registry/src/tests/mock.rs @@ -59,6 +59,7 @@ parameter_types! { pub const BlockHashCount: u64 = 250; pub const SS58Prefix: u8 = 63; pub const NativeAssetId: AssetId = 0; + #[derive(PartialEq, Debug)] pub const RegistryStringLimit: u32 = 10; pub const SequentialIdStart: u32 = 1_000_000; } diff --git a/pallets/asset-registry/src/types.rs b/pallets/asset-registry/src/types.rs index 0f3315aea..606722b89 100644 --- a/pallets/asset-registry/src/types.rs +++ b/pallets/asset-registry/src/types.rs @@ -60,11 +60,12 @@ impl From> for AssetKind { } } -#[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[derive(Encode, Decode, Eq, PartialEq, Clone, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[scale_info(skip_type_params(StringLimit))] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct AssetDetails { +pub struct AssetDetails> { /// The name of this asset. Limited in length by `StringLimit`. - pub name: Option, + pub name: Option>, /// Asset type pub asset_type: AssetType, @@ -73,7 +74,7 @@ pub struct AssetDetails { pub existential_deposit: Balance, /// The ticker symbol for this asset. Limited in length by `StringLimit`. - pub symbol: Option, + pub symbol: Option>, /// The number of decimals this asset uses to represent one unit. pub decimals: Option, @@ -85,12 +86,12 @@ pub struct AssetDetails { pub is_sufficient: bool, } -impl AssetDetails { +impl> AssetDetails { pub fn new( - name: Option, + name: Option>, asset_type: AssetType, existential_deposit: Balance, - symbol: Option, + symbol: Option>, decimals: Option, xcm_rate_limit: Option, is_sufficient: bool, From 2d2ee8196c316ecaa40dd5074c37ad4474ed2930 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 9 Oct 2023 14:26:12 +0200 Subject: [PATCH 28/93] asset-registry: changed hasher for Assets and AssetLocations + minor refactor --- pallets/asset-registry/src/lib.rs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 861fbc837..e39168bb8 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -162,7 +162,7 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn assets)] /// Details of an asset. - pub type Assets = StorageMap<_, Twox64Concat, T::AssetId, AssetDetailsT, OptionQuery>; + pub type Assets = StorageMap<_, Blake2_128Concat, T::AssetId, AssetDetailsT, OptionQuery>; #[pallet::storage] /// Next available asset id. This is sequential id assigned for each new registered asset. @@ -177,7 +177,8 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn locations)] /// Native location of an asset. - pub type AssetLocations = StorageMap<_, Twox64Concat, T::AssetId, T::AssetNativeLocation, OptionQuery>; + pub type AssetLocations = + StorageMap<_, Blake2_128Concat, T::AssetId, T::AssetNativeLocation, OptionQuery>; #[pallet::storage] #[pallet::getter(fn location_assets)] @@ -387,14 +388,10 @@ pub mod pallet { decimals: Option, location: Option, ) -> DispatchResult { - let is_registry_origin = match T::RegistryOrigin::ensure_origin(origin.clone()) { - Ok(_) => true, - Err(_) => { - T::UpdateOrigin::ensure_origin(origin)?; - - false - } - }; + let is_registry_origin = T::RegistryOrigin::ensure_origin(origin.clone()).is_ok(); + if !is_registry_origin { + T::UpdateOrigin::ensure_origin(origin)?; + } Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { let mut details = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; From e1c8f1268bbd63cea615da81c4370f5a5fcb010e Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 10 Oct 2023 11:10:07 +0200 Subject: [PATCH 29/93] asset-registry: fixed typos and removed unsued generics from registry trait. sufficiency-check: added doc comment --- pallets/asset-registry/src/lib.rs | 8 ++++---- runtime/hydradx/src/assets.rs | 12 ++++++++++++ traits/src/registry.rs | 9 +++------ 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index e39168bb8..182d52339 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -98,7 +98,7 @@ pub mod pallet { #[pallet::constant] type StorageFees: Get; - /// Storage fees for external asset creation. + /// Beneficiary account of storage fees for external asset creation. #[pallet::constant] type StorageFeesBeneficiary: Get; @@ -153,8 +153,8 @@ pub mod pallet { } #[pallet::type_value] - /// Default value of NextAssetId if storage is empty. 1 is used to offset for native token - /// which id is 0. + /// Default value of NextAssetId if storage is empty. + /// 1 is used to offset the native asset with id 0. pub fn DefaultNextAssetId() -> T::AssetId { 1.into() } @@ -688,7 +688,7 @@ impl CreateRegistry for Pallet { } } -impl Inspect for Pallet { +impl Inspect for Pallet { type Error = DispatchError; type AssetId = T::AssetId; diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 19e09dc75..079e10e52 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -102,6 +102,18 @@ parameter_types! { pub struct SufficiencyCheck; impl SufficiencyCheck { + /// This function is used by `orml-toknes` `MutationHooks` before a transaction is executed. + /// It is called from `PreDeposit` and `PreTransfer`. + /// If transferred asset is not sufficient asset it calculates ED amount in user's fee asset + /// and transfers it from user to treasury account. + /// Function also locks corresponding HDX amount in the treasury because returned ED to the users + /// when the account is killed is in the HDX. + /// + /// NOTE: `OnNewTokenAccount` mutation hooks is not used because it can't fail so we would not + /// be able to fail transactions e.g. if the user doesn't have enough funds to pay ED. + /// + /// NOTE: Changing of ED in the `pallet_balances` requires migration of all the users with + /// insufficient assets to the new ED amount. fn on_funds(asset: AssetId, paying_account: &AccountId) -> DispatchResult { if ::DustRemovalWhitelist::contains(paying_account) { return Ok(()); diff --git a/traits/src/registry.rs b/traits/src/registry.rs index a3d4013ae..d4f4eb1b9 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -80,7 +80,7 @@ pub trait AccountIdFor { use frame_support::dispatch::Parameter; -pub trait Inspect { +pub trait Inspect { type Error; type AssetId: Parameter; @@ -88,7 +88,7 @@ pub trait Inspect { } #[allow(clippy::too_many_arguments)] -pub trait Create: Inspect { +pub trait Create: Inspect { fn register_asset( asset_id: Option, name: Option<&[u8]>, @@ -148,10 +148,7 @@ pub trait Create: Inspect: Inspect { +pub trait Mutate: Inspect { /// Set location for existing asset id if it wasn't set yet. fn set_location(asset_id: Self::AssetId, location: AssetNativeLocation) -> Result<(), Self::Error>; - - // /// Set or update location of existing asset - // fn force_set_location(asset_id: Self::AssetId, location: AssetNativeLocation) -> Result<(, Self::Error)> } From d9bf21d0eab404e1dbd05f5c4c6942100e1ca5dc Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 10 Oct 2023 11:43:07 +0200 Subject: [PATCH 30/93] make clippy happy --- pallets/asset-registry/src/lib.rs | 4 +++- primitives/src/constants.rs | 2 ++ runtime/hydradx/src/assets.rs | 3 ++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 182d52339..eadc269f2 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -57,6 +57,8 @@ pub const DEFAULT_ED: Balance = 1; #[frame_support::pallet] #[allow(clippy::too_many_arguments)] pub mod pallet { + use sp_std::fmt::Debug; + use super::*; pub type AssetDetailsT = AssetDetails<::AssetId, ::StringLimit>; @@ -104,7 +106,7 @@ pub mod pallet { /// The maximum length of a name or symbol stored on-chain. #[pallet::constant] - type StringLimit: Get; + type StringLimit: Get + Debug + PartialEq; /// Weight information for the extrinsics type WeightInfo: WeightInfo; diff --git a/primitives/src/constants.rs b/primitives/src/constants.rs index 120935efc..239528924 100644 --- a/primitives/src/constants.rs +++ b/primitives/src/constants.rs @@ -23,6 +23,8 @@ pub mod currency { pub const DOLLARS: Balance = UNITS * 100; // 100 UNITS ~= 1 $ pub const CENTS: Balance = DOLLARS / 100; // 1 UNITS ~= 1 cent pub const MILLICENTS: Balance = CENTS / 1_000; + //NOTE: Changing of this value require migration. + //See `SufficiencyCheck.on_fund()` doc. pub const NATIVE_EXISTENTIAL_DEPOSIT: Balance = CENTS; pub fn deposit(items: u32, bytes: u32) -> Balance { diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 079e10e52..6371597b1 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -93,7 +93,7 @@ impl MutationHooks for CurrencyHooks { type OnKilledTokenAccount = (RemoveTxAssetOnKilled, OnKilledTokenAccount); } -pub const SUFFICIENCY_LOCK: LockIdentifier = *b"insuffEd"; +pub const SUFFICIENCY_LOCK: LockIdentifier = *b"insuffED"; parameter_types! { pub InsufficientEDinHDX: Balance = FixedU128::from_rational(11, 10) @@ -293,6 +293,7 @@ impl pallet_claims::Config for Runtime { } parameter_types! { + #[derive(PartialEq, Debug)] pub const RegistryStrLimit: u32 = 32; pub const SequentialIdOffset: u32 = 1_000_000; pub const StoreFees: Balance = 100 * UNITS; //TODO: From 46db72b64099b4cbc83a96af14493451a5ede52c Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 10 Oct 2023 19:04:17 +0200 Subject: [PATCH 31/93] asset-registry: wip migration --- pallets/asset-registry/src/lib.rs | 3 +- pallets/asset-registry/src/migration.rs | 116 ++++++++++++++++++------ runtime/hydradx/src/migrations.rs | 7 ++ 3 files changed, 94 insertions(+), 32 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index eadc269f2..823d2f3a4 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -31,8 +31,7 @@ use sp_std::vec::Vec; mod tests; mod benchmarking; -//TODO -//pub mod migration; +pub mod migration; mod types; pub mod weights; diff --git a/pallets/asset-registry/src/migration.rs b/pallets/asset-registry/src/migration.rs index c3a1e278d..f4d28ed8f 100644 --- a/pallets/asset-registry/src/migration.rs +++ b/pallets/asset-registry/src/migration.rs @@ -7,7 +7,7 @@ // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, @@ -15,34 +15,64 @@ // See the License for the specific language governing permissions and // limitations under the License.. -use crate::{AssetDetails, AssetType, Assets, Config, Pallet}; +use crate::{AssetDetails, AssetType, Assets, Balance, Config, Pallet}; use frame_support::{ log, traits::{Get, StorageVersion}, weights::Weight, + Twox64Concat, }; -/// +use crate::*; + pub mod v1 { + use super::*; use codec::{Decode, Encode}; + use frame_support::storage_alias; use scale_info::TypeInfo; use sp_core::RuntimeDebug; + use sp_runtime::BoundedVec; #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, TypeInfo)] pub struct OldAssetDetails { - /// The name of this asset. Limited in length by `StringLimit`. - pub(super) name: BoundedString, + pub name: BoundedString, + pub asset_type: AssetType, + pub existential_deposit: Balance, + pub xcm_rate_limit: Option, + } - pub(super) asset_type: AssetType, + #[derive(Clone, Encode, Decode, Eq, PartialEq, Default, RuntimeDebug, TypeInfo)] + pub struct OldAssetMetadata { + pub(super) symbol: BoundedString, + pub(super) decimals: u8, + } - pub(super) existential_deposit: Balance, + #[storage_alias] + pub type Assets = StorageMap< + Pallet, + Twox64Concat, + ::AssetId, + OldAssetDetails<::AssetId, Balance, BoundedVec::StringLimit>>, + OptionQuery, + >; + + #[storage_alias] + pub type AssetMetadataMap = StorageMap< + Pallet, + Twox64Concat, + ::AssetId, + OldAssetMetadata::StringLimit>>, + OptionQuery, + >; +} - pub(super) locked: bool, - } +pub mod v2 { + use super::*; + use sp_std::vec::Vec; pub fn pre_migrate() { - assert_eq!(StorageVersion::get::>(), 0, "Storage version too high."); + assert_eq!(StorageVersion::get::>(), 1, "Storage version too high."); log::info!( target: "runtime::asset-registry", @@ -50,30 +80,56 @@ pub mod v1 { ); } - pub fn migrate() -> Weight { + pub fn migrate>() -> Weight { log::info!( target: "runtime::asset-registry", - "Running migration to v1 for Asset Registry" + "Running migration to v2 for Asset Registry" ); let mut i = 0; - Assets::::translate( - |_key, - OldAssetDetails { - name, - asset_type, - existential_deposit, - locked: _, - }| { - i += 1; - Some(AssetDetails { - name, - asset_type, - existential_deposit, - xcm_rate_limit: None, - }) - }, - ); + let mut details_updated = Vec::<( + ::AssetId, + AssetDetails<::AssetId, ::StringLimit>, + )>::new(); + + for (k, v) in v1::Assets::::iter() { + log::info!( + target: "runtime::asset-registry", + "key: {:?}, name: {:?}", k, v.name + ); + + //insert + old metada read = 2 + i += 2; + let (symbol, decimals) = if let Some(meta) = v1::AssetMetadataMap::::get(k) { + (Some(meta.symbol), Some(meta.decimals)) + } else { + (None, None) + }; + + details_updated.push(( + k.clone(), + AssetDetails { + name: Some(v.name), + asset_type: v.asset_type, + existential_deposit: v.existential_deposit, + symbol, + decimals, + xcm_rate_limit: v.xcm_rate_limit, + //All assets created until this point are sufficient + is_sufficient: true, + }, + )); + + //NOTE: problem is with stablepool - probably becasue master is not merged yet + let _ = Assets::::clear(u32::MAX, None); + for (k, v) in &details_updated { + log::info!( + target: "runtime::asset-registry", + "Inserting asset: {:?}:", k + ); + Assets::::insert(k, v); + } + } StorageVersion::new(1).put::>(); @@ -81,7 +137,7 @@ pub mod v1 { } pub fn post_migrate() { - assert_eq!(StorageVersion::get::>(), 1, "Unexpected storage version."); + assert_eq!(StorageVersion::get::>(), 2, "Unexpected storage version."); log::info!( target: "runtime::asset-registry", diff --git a/runtime/hydradx/src/migrations.rs b/runtime/hydradx/src/migrations.rs index 7bb4291fb..1e7bdfae2 100644 --- a/runtime/hydradx/src/migrations.rs +++ b/runtime/hydradx/src/migrations.rs @@ -1,4 +1,7 @@ +use super::*; + use frame_support::{traits::OnRuntimeUpgrade, weights::Weight}; + #[cfg(feature = "try-runtime")] use sp_std::prelude::*; @@ -6,15 +9,19 @@ pub struct OnRuntimeUpgradeMigration; impl OnRuntimeUpgrade for OnRuntimeUpgradeMigration { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, &'static str> { + pallet_asset_registry::migration::v2::pre_migrate::(); Ok(vec![]) } fn on_runtime_upgrade() -> Weight { + pallet_asset_registry::migration::v2::migrate::(); + Weight::zero() } #[cfg(feature = "try-runtime")] fn post_upgrade(_state: Vec) -> Result<(), &'static str> { + pallet_asset_registry::migration::v2::post_migrate::(); Ok(()) } } From ff33c2d2d42cad532c25789daeade18d14feaf3a Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 12 Oct 2023 16:27:44 +0200 Subject: [PATCH 32/93] asset-registry: finished migration --- pallets/asset-registry/src/migration.rs | 77 ++++++++++++++++--------- runtime/hydradx/src/benchmarking/dca.rs | 2 +- 2 files changed, 51 insertions(+), 28 deletions(-) diff --git a/pallets/asset-registry/src/migration.rs b/pallets/asset-registry/src/migration.rs index 7107ae12a..bc7bda6e1 100644 --- a/pallets/asset-registry/src/migration.rs +++ b/pallets/asset-registry/src/migration.rs @@ -26,7 +26,6 @@ use frame_support::{ use crate::*; pub mod v1 { - use super::*; use codec::{Decode, Encode}; use frame_support::storage_alias; @@ -35,7 +34,7 @@ pub mod v1 { use sp_runtime::BoundedVec; #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, TypeInfo)] - pub struct OldAssetDetails { + pub struct AssetDetails { pub name: BoundedString, pub asset_type: AssetType, pub existential_deposit: Balance, @@ -43,7 +42,7 @@ pub mod v1 { } #[derive(Clone, Encode, Decode, Eq, PartialEq, Default, RuntimeDebug, TypeInfo)] - pub struct OldAssetMetadata { + pub struct AssetMetadata { pub(super) symbol: BoundedString, pub(super) decimals: u8, } @@ -53,7 +52,7 @@ pub mod v1 { Pallet, Twox64Concat, ::AssetId, - OldAssetDetails<::AssetId, Balance, BoundedVec::StringLimit>>, + AssetDetails<::AssetId, Balance, BoundedVec::StringLimit>>, OptionQuery, >; @@ -62,14 +61,22 @@ pub mod v1 { Pallet, Twox64Concat, ::AssetId, - OldAssetMetadata::StringLimit>>, + AssetMetadata::StringLimit>>, + OptionQuery, + >; + + #[storage_alias] + pub type AssetLocations = StorageMap< + Pallet, + Twox64Concat, + ::AssetId, + ::AssetNativeLocation, OptionQuery, >; } pub mod v2 { use super::*; - use sp_std::vec::Vec; pub fn pre_migrate() { assert_eq!(StorageVersion::get::>(), 1, "Storage version too high."); @@ -86,27 +93,25 @@ pub mod v2 { "Running migration to v2 for Asset Registry" ); + log::info!( + target: "runtime::asset-registry", + "Migrating Assets storage" + ); + let mut i = 0; - let mut details_updated = Vec::<( + let mut v2_assets_details = Vec::<( ::AssetId, AssetDetails<::AssetId, ::StringLimit>, )>::new(); - for (k, v) in v1::Assets::::iter() { - log::info!( - target: "runtime::asset-registry", - "key: {:?}, name: {:?}", k, v.name - ); - - //insert + old metada read = 2 - i += 2; + i += 1; let (symbol, decimals) = if let Some(meta) = v1::AssetMetadataMap::::get(k) { (Some(meta.symbol), Some(meta.decimals)) } else { (None, None) }; - details_updated.push(( + v2_assets_details.push(( k, AssetDetails { name: Some(v.name), @@ -115,24 +120,42 @@ pub mod v2 { symbol, decimals, xcm_rate_limit: v.xcm_rate_limit, - //All assets created until this point are sufficient + //All assets created before this are sufficient is_sufficient: true, }, )); + } - //NOTE: problem is with stablepool - probably becasue master is not merged yet - let _ = Assets::::clear(u32::MAX, None); - for (k, v) in &details_updated { - log::info!( - target: "runtime::asset-registry", - "Inserting asset: {:?}:", k - ); - Assets::::insert(k, v); - } + for (k, v) in v2_assets_details { + i += 1; + Assets::::insert(k, v); + log::info!( + target: "runtime::asset-registry", + "Migrated asset: {:?}", k + ); } - StorageVersion::new(1).put::>(); + //This assumes every asset has metadata and each metadata is touched. + i += i; + let _ = v1::AssetMetadataMap::::clear(u32::MAX, None); + + log::info!( + target: "runtime::asset-registry", + "Migrating AssetLocations storage" + ); + + for k in v1::AssetLocations::::iter_keys() { + i += 1; + + AssetLocations::::migrate_key::::AssetId>(k); + + log::info!( + target: "runtime::asset-registry", + "Migrated asset's location: {:?}", k + ); + } + StorageVersion::new(2).put::>(); T::DbWeight::get().reads_writes(i, i) } diff --git a/runtime/hydradx/src/benchmarking/dca.rs b/runtime/hydradx/src/benchmarking/dca.rs index c3da9fd87..21c42f3c6 100644 --- a/runtime/hydradx/src/benchmarking/dca.rs +++ b/runtime/hydradx/src/benchmarking/dca.rs @@ -329,7 +329,7 @@ mod tests { registered_assets: vec![(Some(DAI), Some(b"DAI".to_vec()), 1_000u128, None, None, None, false)], native_asset_name: b"HDX".to_vec(), native_existential_deposit: NativeExistentialDeposit::get(), - native_decimals: 12, + native_decimals: 12, native_symbol: b"HDX".to_vec(), } .assimilate_storage(&mut t) From 013afe719d12c8a3f9cf727e9a3e98dab3e8c040 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 12 Oct 2023 17:11:17 +0200 Subject: [PATCH 33/93] asset-registry: added post-migration assertions --- pallets/asset-registry/src/migration.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pallets/asset-registry/src/migration.rs b/pallets/asset-registry/src/migration.rs index bc7bda6e1..b9db6dffb 100644 --- a/pallets/asset-registry/src/migration.rs +++ b/pallets/asset-registry/src/migration.rs @@ -160,6 +160,16 @@ pub mod v2 { } pub fn post_migrate() { + for a in Assets::::iter_keys() { + let _ = Assets::::get(a).expect("Assets data must be valid"); + } + + for l in AssetLocations::::iter_keys() { + let _ = AssetLocations::::get(l).expect("AssetLocations data must be valid"); + } + + assert_eq!(v1::AssetMetadataMap::::iter().count(), 0); + assert_eq!(StorageVersion::get::>(), 2, "Unexpected storage version."); log::info!( From cdfc19aca97d1e0c011d28f50646ee1c07e78c3b Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 16 Oct 2023 15:24:37 +0200 Subject: [PATCH 34/93] sufficiency check: switched to sender to pay for ED and updated tests --- integration-tests/src/dca.rs | 11 +- .../src/insufficient_assets_ed.rs | 216 +++++++++++------- integration-tests/src/router.rs | 12 +- runtime/hydradx/src/assets.rs | 27 +-- 4 files changed, 161 insertions(+), 105 deletions(-) diff --git a/integration-tests/src/dca.rs b/integration-tests/src/dca.rs index 6579fa1eb..d4428b00f 100644 --- a/integration-tests/src/dca.rs +++ b/integration-tests/src/dca.rs @@ -2284,7 +2284,16 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { initial.push(AssetAmount::new(asset_id, initial_liquidity)); } - let pool_id = AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = AssetRegistry::register_sufficient_asset( + None, + Some(b"pool".as_ref()), + AssetKind::Token, + Some(1u128), + None, + None, + None, + None, + )?; let amplification = 100u16; let fee = Permill::from_percent(1); diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index bab89c38f..8e95bf598 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -16,38 +16,41 @@ use sp_runtime::FixedPointNumber; use xcm_emulator::TestExt; #[test] -fn alice_should_pay_ed_in_hdx_when_receive_insufficient_asset() { +fn sender_should_pay_ed_in_hdx_when_it_is_not_whitelisted() { TestNet::reset(); Hydra::execute_with(|| { - let doge: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_shitcoin(0_u128); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), BOB.into(), - doge, + sht1, 100_000_000 * UNITS, 0, )); let alice_balance = Currencies::free_balance(HDX, &ALICE.into()); + let bob_balance = Currencies::free_balance(HDX, &BOB.into()); let treasury_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); assert_eq!(treasury_suffyciency_lock(), 0); //Act assert_ok!(Tokens::transfer( hydra_origin::signed(BOB.into()), ALICE.into(), - doge, + sht1, 1_000_000 * UNITS )); //Assert + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_balance); + assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 1_000_000 * UNITS); + assert_eq!( - Currencies::free_balance(HDX, &ALICE.into()), - alice_balance - InsufficientEDinHDX::get() + Currencies::free_balance(HDX, &BOB.into()), + bob_balance - InsufficientEDinHDX::get() ); - assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 1_000_000 * UNITS); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), @@ -59,14 +62,14 @@ fn alice_should_pay_ed_in_hdx_when_receive_insufficient_asset() { } #[test] -fn alice_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted_to_her() { +fn reciever_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted() { TestNet::reset(); Hydra::execute_with(|| { - let doge: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_shitcoin(0_u128); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), BOB.into(), - doge, + sht1, 100_000_000 * UNITS, 0, )); @@ -74,18 +77,18 @@ fn alice_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted_to_her() { let alice_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); assert_eq!(treasury_suffyciency_lock(), 0); //Act - assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000_000 * UNITS)); + assert_ok!(Tokens::deposit(sht1, &ALICE.into(), 1_000_000 * UNITS)); //Assert assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), alice_balance - InsufficientEDinHDX::get() ); - assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 1_000_000 * UNITS); + assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 1_000_000 * UNITS); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), @@ -97,19 +100,19 @@ fn alice_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted_to_her() { } #[test] -fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_hdx() { +fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_hdx() { TestNet::reset(); Hydra::execute_with(|| { - let doge: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_shitcoin(0_u128); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), BOB.into(), - doge, + sht1, 100_000_000 * UNITS, 0, )); - assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000_000 * UNITS)); + assert_ok!(Tokens::deposit(sht1, &ALICE.into(), 1_000_000 * UNITS)); let alice_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); @@ -120,7 +123,7 @@ fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_hdx assert_ok!(Tokens::transfer( hydra_origin::signed(ALICE.into()), BOB.into(), - doge, + sht1, 1_000_000 * UNITS )); @@ -129,7 +132,7 @@ fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_hdx Currencies::free_balance(HDX, &ALICE.into()), alice_balance + InsufficientEDinHDX::get() ); - assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), @@ -141,41 +144,41 @@ fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_hdx } #[test] -fn alice_should_pay_ed_only_once_when_received_insufficient_asset() { +fn sender_should_pay_ed_only_when_dest_didnt_pay_yet() { TestNet::reset(); Hydra::execute_with(|| { - let doge: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_shitcoin(0_u128); let fee_asset = BTC; assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), BOB.into(), - doge, + sht1, 100_000_000 * UNITS, 0, )); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), - ALICE.into(), + BOB.into(), fee_asset, 1_000_000, 0, )); assert_ok!(MultiTransactionPayment::set_currency( - hydra_origin::signed(ALICE.into()), + hydra_origin::signed(BOB.into()), fee_asset )); assert_ok!(Tokens::transfer( hydra_origin::signed(BOB.into()), ALICE.into(), - doge, + sht1, 1_000_000 * UNITS )); - let alice_fee_asset_balance = Currencies::free_balance(fee_asset, &ALICE.into()); + let bob_fee_asset_balance = Currencies::free_balance(fee_asset, &BOB.into()); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); let treasury_fee_asset_balance = Currencies::free_balance(fee_asset, &TreasuryAccount::get()); @@ -184,17 +187,14 @@ fn alice_should_pay_ed_only_once_when_received_insufficient_asset() { assert_ok!(Tokens::transfer( hydra_origin::signed(BOB.into()), ALICE.into(), - doge, + sht1, 1_000_000 * UNITS )); //Assert assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); - assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 2_000_000 * UNITS); - assert_eq!( - Currencies::free_balance(fee_asset, &ALICE.into()), - alice_fee_asset_balance - ); + assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 2_000_000 * UNITS); + assert_eq!(Currencies::free_balance(fee_asset, &BOB.into()), bob_fee_asset_balance); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), @@ -213,10 +213,10 @@ fn alice_should_pay_ed_only_once_when_received_insufficient_asset() { } #[test] -fn alice_should_pay_ed_only_once_when_insufficient_asset_is_depositted_to_her() { +fn dest_should_pay_ed_only_once_when_insufficient_asset_was_depsitted() { TestNet::reset(); Hydra::execute_with(|| { - let doge: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_shitcoin(0_u128); let fee_asset = BTC; assert_ok!(Tokens::set_balance( @@ -232,7 +232,7 @@ fn alice_should_pay_ed_only_once_when_insufficient_asset_is_depositted_to_her() fee_asset )); - assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000 * UNITS)); + assert_ok!(Tokens::deposit(sht1, &ALICE.into(), 1_000 * UNITS)); let alice_fee_asset_balance = Currencies::free_balance(fee_asset, &ALICE.into()); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); @@ -240,11 +240,11 @@ fn alice_should_pay_ed_only_once_when_insufficient_asset_is_depositted_to_her() let treasury_fee_asset_balance = Currencies::free_balance(fee_asset, &TreasuryAccount::get()); //Act - assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000 * UNITS)); + assert_ok!(Tokens::deposit(sht1, &ALICE.into(), 1_000 * UNITS)); //Assert assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); - assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 2_000 * UNITS); + assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 2_000 * UNITS); assert_eq!( Currencies::free_balance(fee_asset, &ALICE.into()), alice_fee_asset_balance @@ -266,17 +266,17 @@ fn alice_should_pay_ed_only_once_when_insufficient_asset_is_depositted_to_her() } #[test] -fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_fee_asset() { +fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset() { TestNet::reset(); Hydra::execute_with(|| { - let doge: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_shitcoin(0_u128); let fee_asset = BTC; //NOTE: this is important for this tests - it basically mean that Bob already paid ED. assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), BOB.into(), - doge, + sht1, 100_000_000 * UNITS, 0, )); @@ -289,7 +289,7 @@ fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_fee 0, )); - assert_ok!(Tokens::deposit(doge, &ALICE.into(), 1_000_000 * UNITS)); + assert_ok!(Tokens::deposit(sht1, &ALICE.into(), 1_000_000 * UNITS)); assert_ok!(MultiTransactionPayment::set_currency( hydra_origin::signed(ALICE.into()), fee_asset @@ -306,7 +306,7 @@ fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_fee assert_ok!(Tokens::transfer( hydra_origin::signed(ALICE.into()), BOB.into(), - doge, + sht1, 1_000_000 * UNITS )); @@ -316,7 +316,7 @@ fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_fee Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance + InsufficientEDinHDX::get() ); - assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); assert_eq!( Currencies::free_balance(fee_asset, &ALICE.into()), alice_fee_asset_balance @@ -338,7 +338,7 @@ fn hdx_ed_should_be_released_when_alice_account_is_killed_and_ed_was_paid_in_fee fn tx_should_fail_with_keepalive_err_when_dest_account_cant_pay_ed() { TestNet::reset(); Hydra::execute_with(|| { - let doge: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_shitcoin(0_u128); let fee_asset = BTC; assert_ok!(MultiTransactionPayment::set_currency( @@ -352,53 +352,53 @@ fn tx_should_fail_with_keepalive_err_when_dest_account_cant_pay_ed() { assert!(Tokens::free_balance(fee_asset, &ALICE.into()) < ed_in_hdx); assert_noop!( - Tokens::deposit(doge, &ALICE.into(), 1_000_000 * UNITS), + Tokens::deposit(sht1, &ALICE.into(), 1_000_000 * UNITS), orml_tokens::Error::::KeepAlive ); }); } #[test] -fn alice_should_pay_ed_in_fee_asset_when_receive_insufficient_asset() { +fn sender_should_pay_ed_in_fee_asset_when_sending_insufficient_asset() { TestNet::reset(); Hydra::execute_with(|| { - let doge: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_shitcoin(0_u128); let fee_asset = BTC; assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), BOB.into(), - doge, + sht1, 100_000_000 * UNITS, 0, )); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), - ALICE.into(), + BOB.into(), fee_asset, 1_000_000, 0, )); assert_ok!(MultiTransactionPayment::set_currency( - hydra_origin::signed(ALICE.into()), + hydra_origin::signed(BOB.into()), fee_asset )); - let alice_fee_asset_balance = Currencies::free_balance(fee_asset, &ALICE.into()); + let bob_fee_asset_balance = Currencies::free_balance(fee_asset, &BOB.into()); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); let treasury_fee_asset_balance = Currencies::free_balance(fee_asset, &TreasuryAccount::get()); - assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 0); + assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); assert_eq!(treasury_suffyciency_lock(), 0); //Act assert_ok!(Tokens::transfer( hydra_origin::signed(BOB.into()), ALICE.into(), - doge, + sht1, 1_000_000 * UNITS )); @@ -406,12 +406,15 @@ fn alice_should_pay_ed_in_fee_asset_when_receive_insufficient_asset() { let ed_in_hdx: Balance = MultiTransactionPayment::price(fee_asset) .unwrap() .saturating_mul_int(InsufficientEDinHDX::get()); - assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); - assert_eq!(Currencies::free_balance(doge, &ALICE.into()), 1_000_000 * UNITS); + assert_eq!( - Currencies::free_balance(fee_asset, &ALICE.into()), - alice_fee_asset_balance - ed_in_hdx + Currencies::free_balance(sht1, &BOB.into()), + (100_000_000 - 1_000_000) * UNITS + ); + assert_eq!( + Currencies::free_balance(fee_asset, &BOB.into()), + bob_fee_asset_balance - ed_in_hdx ); assert_eq!( @@ -428,9 +431,8 @@ fn alice_should_pay_ed_in_fee_asset_when_receive_insufficient_asset() { #[test] fn grandfathered_account_should_receive_hdx_when_account_is_killed() { - //NOTE: this is case simulating old account that received insufficient asset before sufficiency - //check and didn't paid ED. This test is important because grandfathered accounts doesn't have - //incremented `sufficients`. + //NOTE: thiscase simulates old account that received insufficient asset before sufficiency + //check and didn't pay ED. TestNet::reset(); Hydra::execute_with(|| { @@ -467,14 +469,14 @@ fn grandfathered_account_should_receive_hdx_when_account_is_killed() { } #[test] -fn sufficient_asset_should_not_pay_ed_to_treasury_when_transfered_or_deposited() { +fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() { TestNet::reset(); Hydra::execute_with(|| { - let doge = register_shitcoin(0_u128); + let sht1 = register_shitcoin(0_u128); let sufficient_asset = DAI; //This pays ED. - assert_ok!(Tokens::deposit(doge, &BOB.into(), 100_000_000 * UNITS,)); + assert_ok!(Tokens::deposit(sht1, &BOB.into(), 100_000_000 * UNITS,)); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let alice_sufficient_asset_balance = Currencies::free_balance(DAI, &ALICE.into()); @@ -527,7 +529,7 @@ fn sufficient_asset_should_not_pay_ed_to_treasury_when_transfered_or_deposited() } #[test] -fn sufficient_asset_should_not_release_ed_from_treasury_when_account_is_killed() { +fn ed_should_not_be_released_when_sufficient_asset_killed_account() { TestNet::reset(); Hydra::execute_with(|| { let sufficient_asset = DAI; @@ -565,7 +567,7 @@ fn sufficient_asset_should_not_release_ed_from_treasury_when_account_is_killed() } #[test] -fn each_insufficient_asset_should_pay_ed_when_transfer_or_depositted() { +fn ed_should_be_collected_for_each_insufficient_asset_when_transfered_or_depositted() { TestNet::reset(); Hydra::execute_with(|| { let sht1: AssetId = register_shitcoin(0_u128); @@ -574,7 +576,11 @@ fn each_insufficient_asset_should_pay_ed_when_transfer_or_depositted() { let sht4: AssetId = register_shitcoin(3_u128); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); + let bob_hdx_balance = Currencies::free_balance(HDX, &BOB.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); + + assert_eq!(MultiTransactionPayment::account_currency(&ALICE.into()), HDX); + assert_eq!(MultiTransactionPayment::account_currency(&BOB.into()), HDX); assert_eq!(treasury_suffyciency_lock(), 0); assert_ok!(Tokens::set_balance( @@ -624,10 +630,18 @@ fn each_insufficient_asset_should_pay_ed_when_transfer_or_depositted() { assert_ok!(Tokens::deposit(sht4, &ALICE.into(), 1_000_000 * UNITS)); //Assert + //NOTE: Alice paid ED for deposit. assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance - InsufficientEDinHDX::get() * 4 + alice_hdx_balance - InsufficientEDinHDX::get() ); + + //NOTE: Bob paid ED for transfers. + assert_eq!( + Currencies::free_balance(HDX, &BOB.into()), + bob_hdx_balance - InsufficientEDinHDX::get() * 3 + ); + assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance + InsufficientEDinHDX::get() * 4 @@ -637,7 +651,7 @@ fn each_insufficient_asset_should_pay_ed_when_transfer_or_depositted() { } #[test] -fn each_insufficient_asset_should_release_ed_when_account_is_killed() { +fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { TestNet::reset(); Hydra::execute_with(|| { let sht1: AssetId = register_shitcoin(0_u128); @@ -887,23 +901,28 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { } #[test] -fn whitelisted_account_should_not_pay_ed_when_transferred_or_deposited() { +fn sender_should_pay_ed_when_tranferred_or_deposited_to_whitelisted_dest() { TestNet::reset(); Hydra::execute_with(|| { let sht1: AssetId = register_shitcoin(0_u128); let sht2: AssetId = register_shitcoin(1_u128); - assert_ok!(Tokens::deposit(sht1, &BOB.into(), 1_000_000 * UNITS)); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + sht1, + 1_000_000 * UNITS, + 0, + )); let treasury = TreasuryAccount::get(); assert!(DustRemovalWhitelist::contains(&treasury)); - assert_eq!(MultiTransactionPayment::account_currency(&treasury), HDX); + assert_eq!(MultiTransactionPayment::account_currency(&BOB.into()), HDX); + let bob_fee_asset_balance = Currencies::free_balance(HDX, &BOB.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &treasury); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); - //Act 1 assert_ok!(Tokens::transfer( hydra_origin::signed(BOB.into()), @@ -913,7 +932,14 @@ fn whitelisted_account_should_not_pay_ed_when_transferred_or_deposited() { )); //Assert 1 - assert_eq!(Currencies::free_balance(HDX, &treasury), treasury_hdx_balance); + assert_eq!( + Currencies::free_balance(HDX, &treasury), + treasury_hdx_balance + InsufficientEDinHDX::get() + ); + assert_eq!( + Currencies::free_balance(HDX, &BOB.into()), + bob_fee_asset_balance - InsufficientEDinHDX::get() + ); assert_eq!(Currencies::free_balance(sht1, &treasury), 10); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); @@ -921,28 +947,45 @@ fn whitelisted_account_should_not_pay_ed_when_transferred_or_deposited() { assert_ok!(Tokens::deposit(sht2, &treasury, 20)); //Assert 2 - assert_eq!(Currencies::free_balance(HDX, &treasury), treasury_hdx_balance); + assert_eq!( + Currencies::free_balance(HDX, &treasury), + treasury_hdx_balance + InsufficientEDinHDX::get() + ); assert_eq!(Currencies::free_balance(sht1, &treasury), 10); assert_eq!(Currencies::free_balance(sht2, &treasury), 20); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + //NOTE: treasury paid ED in hdx so hdx balance didn't changed but locked was increased. + assert_eq!(treasury_suffyciency_lock(), 2 * InsufficientEDinHDX::get()); }); } #[test] -fn whitelisted_account_should_not_release_ed_when_killed() { +fn ed_should_be_released_when_whitelisted_account_was_killed() { TestNet::reset(); Hydra::execute_with(|| { let sht1: AssetId = register_shitcoin(0_u128); let treasury = TreasuryAccount::get(); - assert_ok!(Tokens::deposit(sht1, &BOB.into(), 1_000_000 * UNITS)); - assert_ok!(Tokens::deposit(sht1, &treasury, 1_000_000 * UNITS)); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + sht1, + 1_000_000 * UNITS, + 0, + )); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + treasury.clone().into(), + sht1, + 1_000_000 * UNITS, + 0, + )); - assert!(DustRemovalWhitelist::contains(&treasury)); + assert!(DustRemovalWhitelist::contains(&treasury.clone().into())); assert_eq!(MultiTransactionPayment::account_currency(&treasury), HDX); let treasury_hdx_balance = Currencies::free_balance(HDX, &treasury); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + //NOTE: set_balance bypass mutation hooks so none was paid. + assert_eq!(treasury_suffyciency_lock(), 0); //Act 1 assert_ok!(Tokens::transfer( @@ -957,8 +1000,8 @@ fn whitelisted_account_should_not_release_ed_when_killed() { assert_eq!(Currencies::free_balance(sht1, &treasury), 0); assert_eq!(Currencies::free_balance(sht1, &BOB.into()), 2_000_000 * UNITS); - //BOB already paid ED for this asset - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + //NOTE: bob already holds sht1 so it means additional ed is not necessary. + assert_eq!(treasury_suffyciency_lock(), 0); assert!(orml_tokens::Accounts::::try_get(&treasury, sht1).is_err()); }); @@ -969,6 +1012,7 @@ fn tx_should_fail_with_unsupported_currency_error_when_fee_asset_price_wasn_not_ TestNet::reset(); Hydra::execute_with(|| { let sht1: AssetId = register_shitcoin(0_u128); + let sht2: AssetId = register_shitcoin(1_u128); let fee_asset = BTC; assert_ok!(Tokens::set_balance( @@ -981,14 +1025,14 @@ fn tx_should_fail_with_unsupported_currency_error_when_fee_asset_price_wasn_not_ assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), - ALICE.into(), + BOB.into(), fee_asset, 1_000_000, 0, )); assert_ok!(MultiTransactionPayment::set_currency( - hydra_origin::signed(ALICE.into()), + hydra_origin::signed(BOB.into()), fee_asset )); @@ -1004,7 +1048,7 @@ fn tx_should_fail_with_unsupported_currency_error_when_fee_asset_price_wasn_not_ //Act 2 - deposit assert_noop!( - Tokens::deposit(sht1, &ALICE.into(), 1_000_000 * UNITS), + Tokens::deposit(sht2, &BOB.into(), 1_000_000 * UNITS), pallet_transaction_multi_payment::Error::::UnsupportedCurrency ); }); diff --git a/integration-tests/src/router.rs b/integration-tests/src/router.rs index 2df6a707f..6f5de9812 100644 --- a/integration-tests/src/router.rs +++ b/integration-tests/src/router.rs @@ -9,7 +9,6 @@ use hydradx_runtime::{ AssetRegistry, BlockNumber, Currencies, Omnipool, Router, RouterWeightInfo, Runtime, RuntimeOrigin, Stableswap, LBP, XYK, }; -use hydradx_traits::Registry; use hydradx_traits::{ registry::Create, router::{PoolType, Trade}, @@ -2297,7 +2296,16 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { initial.push(AssetAmount::new(asset_id, initial_liquidity)); added_liquidity.push(AssetAmount::new(asset_id, liquidity_added)); } - let pool_id = AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = AssetRegistry::register_sufficient_asset( + None, + Some(b"pool".as_ref()), + AssetKind::Token, + Some(1u128), + None, + None, + None, + None, + )?; let amplification = 100u16; let fee = Permill::from_percent(1); diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 7364e1334..71fa3a20c 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -117,15 +117,8 @@ impl SufficiencyCheck { /// /// NOTE: Changing of ED in the `pallet_balances` requires migration of all the users with /// insufficient assets to the new ED amount. - fn on_funds(asset: AssetId, paying_account: &AccountId) -> DispatchResult { - if ::DustRemovalWhitelist::contains(paying_account) { - return Ok(()); - } - - //NOTE: account existence means it already paid ED - if orml_tokens::Accounts::::try_get(paying_account, asset).is_err() - && !AssetRegistry::is_sufficient(asset) - { + fn on_funds(asset: AssetId, paying_account: &AccountId, to: &AccountId) -> DispatchResult { + if orml_tokens::Accounts::::try_get(to, asset).is_err() && !AssetRegistry::is_sufficient(asset) { let fee_payment_asset = MultiTransactionPayment::account_currency(paying_account); let ed = MultiTransactionPayment::price(fee_payment_asset) @@ -163,14 +156,20 @@ impl SufficiencyCheck { } impl OnTransfer for SufficiencyCheck { - fn on_transfer(asset: AssetId, _from: &AccountId, to: &AccountId, _amount: Balance) -> DispatchResult { - Self::on_funds(asset, to) + fn on_transfer(asset: AssetId, from: &AccountId, to: &AccountId, _amount: Balance) -> DispatchResult { + //NOTE: `to` is paying ED if `from` is whitelisted. + //This can happen if pallet's account transfers insufficient tokens to another account. + if ::DustRemovalWhitelist::contains(from) { + Self::on_funds(asset, to, to) + } else { + Self::on_funds(asset, from, to) + } } } impl OnDeposit for SufficiencyCheck { fn on_deposit(asset: AssetId, to: &AccountId, _amount: Balance) -> DispatchResult { - Self::on_funds(asset, to) + Self::on_funds(asset, to, to) } } @@ -181,10 +180,6 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { return; } - if ::DustRemovalWhitelist::contains(who) { - return; - } - let to_lock = pallet_balances::Locks::::get(TreasuryAccount::get()) .iter() .find(|x| x.id == SUFFICIENCY_LOCK) From 1db792a312bb31ae41f15dfef175e190efeac21e Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 18 Oct 2023 13:39:03 +0200 Subject: [PATCH 35/93] asset-registry/sufficiency-check: added storage to count accounts that paid ed, added event that ed was paid, changed way how ed amount to release on account kill is calculated --- .../src/insufficient_assets_ed.rs | 379 ++++++++++++++++-- pallets/asset-registry/src/lib.rs | 15 +- runtime/hydradx/src/assets.rs | 39 +- 3 files changed, 393 insertions(+), 40 deletions(-) diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index 8e95bf598..b484d690a 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -1,13 +1,14 @@ #![cfg(test)] +use crate::assert_event_times; use crate::insufficient_assets_ed::v3::Junction::GeneralIndex; use crate::polkadot_test_net::*; use frame_support::{assert_noop, assert_ok, traits::Contains}; use frame_system::RawOrigin; use hydradx_runtime::RuntimeOrigin as hydra_origin; use hydradx_runtime::{ - AssetRegistry as Registry, Currencies, DustRemovalWhitelist, InsufficientEDinHDX, MultiTransactionPayment, Tokens, - TreasuryAccount, SUFFICIENCY_LOCK, + AssetRegistry as Registry, Currencies, DustRemovalWhitelist, InsufficientEDinHDX, MultiTransactionPayment, + RuntimeEvent, Tokens, TreasuryAccount, SUFFICIENCY_LOCK, }; use hydradx_traits::NativePriceOracle; use orml_traits::MultiCurrency; @@ -56,8 +57,21 @@ fn sender_should_pay_ed_in_hdx_when_it_is_not_whitelisted() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_balance + InsufficientEDinHDX::get() ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: BOB.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); }); } @@ -96,6 +110,20 @@ fn reciever_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted() { ); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: ALICE.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); }); } @@ -140,6 +168,20 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_hdx() { ); assert_eq!(treasury_suffyciency_lock(), 0); + + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 0_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: ALICE.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); }); } @@ -208,7 +250,22 @@ fn sender_should_pay_ed_only_when_dest_didnt_pay_yet() { let ed_in_hdx: Balance = MultiTransactionPayment::price(fee_asset) .unwrap() .saturating_mul_int(InsufficientEDinHDX::get()); - assert_eq!(treasury_suffyciency_lock(), ed_in_hdx); + + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: BOB.into(), + fee_asset, + amount: ed_in_hdx + }), + 1 + ); }); } @@ -258,10 +315,25 @@ fn dest_should_pay_ed_only_once_when_insufficient_asset_was_depsitted() { Currencies::free_balance(fee_asset, &TreasuryAccount::get()), treasury_fee_asset_balance ); - let ed_in_hdx: Balance = MultiTransactionPayment::price(fee_asset) + let ed_in_fee_asset: Balance = MultiTransactionPayment::price(fee_asset) .unwrap() .saturating_mul_int(InsufficientEDinHDX::get()); - assert_eq!(treasury_suffyciency_lock(), ed_in_hdx); + + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: ALICE.into(), + fee_asset, + amount: ed_in_fee_asset + }), + 1 + ); }); } @@ -330,7 +402,22 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset Currencies::free_balance(fee_asset, &TreasuryAccount::get()), treasury_fee_asset_balance ); + assert_eq!(treasury_suffyciency_lock(), 0); + + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 0_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: ALICE.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); }); } @@ -403,7 +490,7 @@ fn sender_should_pay_ed_in_fee_asset_when_sending_insufficient_asset() { )); //Assert - let ed_in_hdx: Balance = MultiTransactionPayment::price(fee_asset) + let ed_in_fee_asset: Balance = MultiTransactionPayment::price(fee_asset) .unwrap() .saturating_mul_int(InsufficientEDinHDX::get()); assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); @@ -414,7 +501,7 @@ fn sender_should_pay_ed_in_fee_asset_when_sending_insufficient_asset() { ); assert_eq!( Currencies::free_balance(fee_asset, &BOB.into()), - bob_fee_asset_balance - ed_in_hdx + bob_fee_asset_balance - ed_in_fee_asset ); assert_eq!( @@ -423,9 +510,24 @@ fn sender_should_pay_ed_in_fee_asset_when_sending_insufficient_asset() { ); assert_eq!( Currencies::free_balance(fee_asset, &TreasuryAccount::get()), - treasury_fee_asset_balance + ed_in_hdx + treasury_fee_asset_balance + ed_in_fee_asset + ); + + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: BOB.into(), + fee_asset, + amount: ed_in_fee_asset + }), + 1 ); - assert_eq!(treasury_suffyciency_lock(), ed_in_hdx); }); } @@ -439,6 +541,10 @@ fn grandfathered_account_should_receive_hdx_when_account_is_killed() { let dummy: AssetId = 1_000_001; assert_ok!(Tokens::deposit(dummy, &ALICE.into(), 1_000_000 * UNITS)); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); let grandfathered_balance = Currencies::free_balance(HDX, &GRANDFATHERED_UNPAID_ED.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); @@ -465,6 +571,19 @@ fn grandfathered_account_should_receive_hdx_when_account_is_killed() { //NOTE: this is zero because Alice paid ED and it was paid to grandfathered assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 0_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: ALICE.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); }); } @@ -476,13 +595,17 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() let sufficient_asset = DAI; //This pays ED. - assert_ok!(Tokens::deposit(sht1, &BOB.into(), 100_000_000 * UNITS,)); + assert_ok!(Tokens::deposit(sht1, &BOB.into(), 100_000_000 * UNITS)); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let alice_sufficient_asset_balance = Currencies::free_balance(DAI, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); //Act 1 - transfer assert_ok!(Tokens::transfer( @@ -504,6 +627,10 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() treasury_hdx_balance ); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); //Arrange 2 let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); @@ -525,6 +652,19 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() treasury_hdx_balance ); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: BOB.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); }); } @@ -532,13 +672,25 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() fn ed_should_not_be_released_when_sufficient_asset_killed_account() { TestNet::reset(); Hydra::execute_with(|| { + let sht1: AssetId = register_shitcoin(0_u128); let sufficient_asset = DAI; + //This pays ED. + assert_ok!(Tokens::deposit(sht1, &BOB.into(), 100_000_000 * UNITS)); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let alice_sufficient_asset_balance = Currencies::free_balance(DAI, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); //Act assert_ok!(Tokens::transfer( @@ -562,7 +714,20 @@ fn ed_should_not_be_released_when_sufficient_asset_killed_account() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: BOB.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); }); } @@ -647,6 +812,28 @@ fn ed_should_be_collected_for_each_insufficient_asset_when_transfered_or_deposit treasury_hdx_balance + InsufficientEDinHDX::get() * 4 ); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 4); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 4_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: BOB.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 3 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: ALICE.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); }); } @@ -670,6 +857,15 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { assert_ok!(Tokens::deposit(sht3, &ALICE.into(), 10_000 * UNITS)); assert_ok!(Tokens::deposit(sht4, &ALICE.into(), 10_000 * UNITS)); + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: ALICE.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 4 + ); + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 4); @@ -692,6 +888,10 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { treasury_hdx_balance - InsufficientEDinHDX::get() ); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 3); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 3_u128 + ); //Act 2 assert_ok!(Tokens::transfer( @@ -711,6 +911,10 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { treasury_hdx_balance - InsufficientEDinHDX::get() * 2 ); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 2); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 2_u128 + ); //Act 3 assert_ok!(Tokens::transfer( @@ -730,6 +934,10 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { treasury_hdx_balance - InsufficientEDinHDX::get() * 3 ); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); //Act 4 assert_ok!(Tokens::transfer( @@ -749,6 +957,10 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { treasury_hdx_balance - InsufficientEDinHDX::get() * 4 ); assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 0_u128 + ); }); } @@ -785,9 +997,22 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { 0 )); + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: ALICE.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 2 + ); + let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 2); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 2_u128 + ); //Act 1 assert_ok!(Tokens::transfer( @@ -807,6 +1032,10 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { treasury_hdx_balance - InsufficientEDinHDX::get() ); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); //Arrange 2 let alice_dai_balance = Currencies::free_balance(DAI, &ALICE.into()); @@ -828,6 +1057,10 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { treasury_hdx_balance ); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); //Arrange 3 let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); @@ -851,12 +1084,16 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { treasury_hdx_balance - InsufficientEDinHDX::get() ); assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 0_u128 + ); //Arrange 4 let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - //Act 4 - unlocking ED for account that doesn't paid ED + //Act 4 assert_ok!(Tokens::transfer( hydra_origin::signed(ALICE.into()), BOB.into(), @@ -864,22 +1101,23 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { 10_000 * UNITS )); - //Assert 4 - assert_eq!( - Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance + InsufficientEDinHDX::get() - ); + //Assert 4 - we used set_balance, nobody paid for this ED so nothing can be unlocked. + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_balance - InsufficientEDinHDX::get() + treasury_hdx_balance ); assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 0_u128 + ); //Arrange 5 let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - //Act 5 - unlocking ED for account that doesn't paid ED + //Act 5 - we used set_balance, nobody paid for this ED so nothing can be unlocked. assert_ok!(Tokens::transfer( hydra_origin::signed(ALICE.into()), BOB.into(), @@ -888,15 +1126,16 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { )); //Assert 5 - assert_eq!( - Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance + InsufficientEDinHDX::get() - ); + assert_eq!(Currencies::free_balance(HDX, &ALICE.into()), alice_hdx_balance); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_balance - InsufficientEDinHDX::get() + treasury_hdx_balance ); assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 0_u128 + ); }); } @@ -942,6 +1181,10 @@ fn sender_should_pay_ed_when_tranferred_or_deposited_to_whitelisted_dest() { ); assert_eq!(Currencies::free_balance(sht1, &treasury), 10); assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); //Act 2 assert_ok!(Tokens::deposit(sht2, &treasury, 20)); @@ -955,6 +1198,27 @@ fn sender_should_pay_ed_when_tranferred_or_deposited_to_whitelisted_dest() { assert_eq!(Currencies::free_balance(sht2, &treasury), 20); //NOTE: treasury paid ED in hdx so hdx balance didn't changed but locked was increased. assert_eq!(treasury_suffyciency_lock(), 2 * InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 2_u128 + ); + + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: BOB.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: treasury.clone().into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); }); } @@ -969,23 +1233,36 @@ fn ed_should_be_released_when_whitelisted_account_was_killed() { RawOrigin::Root.into(), BOB.into(), sht1, - 1_000_000 * UNITS, + 2_000_000 * UNITS, 0, )); - assert_ok!(Tokens::set_balance( - RawOrigin::Root.into(), + + assert_ok!(Tokens::transfer( + hydra_origin::signed(BOB.into()), treasury.clone().into(), sht1, - 1_000_000 * UNITS, - 0, + 1_000_000 * UNITS )); + assert_event_times!( + RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { + who: BOB.into(), + fee_asset: HDX, + amount: InsufficientEDinHDX::get() + }), + 1 + ); + assert!(DustRemovalWhitelist::contains(&treasury.clone().into())); assert_eq!(MultiTransactionPayment::account_currency(&treasury), HDX); let treasury_hdx_balance = Currencies::free_balance(HDX, &treasury); //NOTE: set_balance bypass mutation hooks so none was paid. - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 1_u128 + ); //Act 1 assert_ok!(Tokens::transfer( @@ -1002,6 +1279,10 @@ fn ed_should_be_released_when_whitelisted_account_was_killed() { //NOTE: bob already holds sht1 so it means additional ed is not necessary. assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!( + pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), + 0_u128 + ); assert!(orml_tokens::Accounts::::try_get(&treasury, sht1).is_err()); }); @@ -1073,3 +1354,37 @@ fn treasury_suffyciency_lock() -> Balance { .map(|p| p.amount) .unwrap_or_default() } + +/// Assert RuntimeEvent specified number of times. +/// +/// Parameters: +/// - `event` +/// - `times` - number of times event should occure. +#[macro_export] +macro_rules! assert_event_times { + ( $x:expr, $y: expr ) => {{ + let mut found: u32 = 0; + + let runtime_events: Vec = frame_system::Pallet::::events() + .into_iter() + .map(|e| e.event) + .collect(); + + for evt in runtime_events { + if evt == $x { + found += 1; + } + + if found > $y { + panic!("Event found more than: {:?} times.", $y); + } + } + if found != $y { + if found == 0 { + panic!("Event not found."); + } + + panic!("Event found {:?} times, expected: {:?}", found, $y); + } + }}; +} diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 823d2f3a4..10d2480e0 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -187,6 +187,11 @@ pub mod pallet { pub type LocationAssets = StorageMap<_, Blake2_128Concat, T::AssetNativeLocation, T::AssetId, OptionQuery>; + #[pallet::storage] + /// Number of accounts that paid existential deposits for insufficient assets. + /// This storage is used by `SufficiencyCheck`. + pub type ExistentialDepositCounter = StorageValue<_, u128, ValueQuery>; + #[allow(clippy::type_complexity)] #[pallet::genesis_config] pub struct GenesisConfig { @@ -274,8 +279,16 @@ pub mod pallet { } #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] + #[pallet::generate_deposit(pub fn deposit_event)] pub enum Event { + /// Existential deposit for insufficinet asset was paid. + /// `SufficiencyCheck` triggers this event. + ExistentialDepositPaid { + who: T::AccountId, + fee_asset: T::AssetId, + amount: Balance, + }, + /// Asset was registered. Registered { asset_id: T::AssetId, diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 71fa3a20c..9abf0d438 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -42,6 +42,7 @@ use primitives::constants::{ chain::OMNIPOOL_SOURCE, currency::{NATIVE_EXISTENTIAL_DEPOSIT, UNITS}, }; +use sp_runtime::DispatchError; use sp_runtime::{traits::Zero, DispatchResult, FixedPointNumber}; use core::ops::RangeInclusive; @@ -121,7 +122,7 @@ impl SufficiencyCheck { if orml_tokens::Accounts::::try_get(to, asset).is_err() && !AssetRegistry::is_sufficient(asset) { let fee_payment_asset = MultiTransactionPayment::account_currency(paying_account); - let ed = MultiTransactionPayment::price(fee_payment_asset) + let ed_in_fee_asset = MultiTransactionPayment::price(fee_payment_asset) .ok_or(pallet_transaction_multi_payment::Error::::UnsupportedCurrency)? .saturating_mul_int(InsufficientEDinHDX::get()); @@ -130,7 +131,7 @@ impl SufficiencyCheck { fee_payment_asset, paying_account, &TreasuryAccount::get(), - ed, + ed_in_fee_asset, ) .map_err(|_| orml_tokens::Error::::KeepAlive)?; @@ -139,7 +140,7 @@ impl SufficiencyCheck { .find(|x| x.id == SUFFICIENCY_LOCK) .map(|p| p.amount) .unwrap_or_default() - .saturating_add(ed); + .saturating_add(InsufficientEDinHDX::get()); >::set_lock( SUFFICIENCY_LOCK, @@ -149,6 +150,21 @@ impl SufficiencyCheck { )?; frame_system::Pallet::::inc_sufficients(paying_account); + + let _ = pallet_asset_registry::ExistentialDepositCounter::::try_mutate( + |val| -> Result<(), DispatchError> { + *val = val.saturating_add(1); + Ok(()) + }, + ); + + pallet_asset_registry::Pallet::::deposit_event( + pallet_asset_registry::Event::::ExistentialDepositPaid { + who: paying_account.clone(), + fee_asset: fee_payment_asset, + amount: ed_in_fee_asset, + }, + ); } Ok(()) @@ -180,12 +196,19 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { return; } - let to_lock = pallet_balances::Locks::::get(TreasuryAccount::get()) + let locked_ed = pallet_balances::Locks::::get(TreasuryAccount::get()) .iter() .find(|x| x.id == SUFFICIENCY_LOCK) .map(|p| p.amount) - .unwrap_or_default() - .saturating_sub(InsufficientEDinHDX::get()); + .unwrap_or_default(); + + let paid_accounts = pallet_asset_registry::ExistentialDepositCounter::::get(); + let ed_to_pay = if paid_accounts != 0 { + locked_ed.saturating_div(paid_accounts) + } else { + 0 + }; + let to_lock = locked_ed.saturating_sub(ed_to_pay); if to_lock.is_zero() { let _ = >::remove_lock( @@ -206,7 +229,7 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { NativeAssetId::get(), &TreasuryAccount::get(), who, - InsufficientEDinHDX::get(), + ed_to_pay, ); //NOTE: This is necessary because grandfathered accounts doesn't have incremented @@ -215,6 +238,8 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { if frame_system::Pallet::::account(who).sufficients > 0 { frame_system::Pallet::::dec_sufficients(who); } + + pallet_asset_registry::ExistentialDepositCounter::::set(paid_accounts.saturating_sub(1)); } } From 8bf0a52292efba713a851d704d6001259a16a33b Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 18 Oct 2023 16:41:19 +0200 Subject: [PATCH 36/93] asset-registry: wip review fixex --- pallets/asset-registry/src/benchmarking.rs | 6 +- pallets/asset-registry/src/lib.rs | 176 +++++++++---------- pallets/asset-registry/src/tests/register.rs | 14 +- pallets/asset-registry/src/tests/update.rs | 83 ++++++--- primitives/src/constants.rs | 2 - 5 files changed, 154 insertions(+), 127 deletions(-) diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index c582d02e0..bc89beee1 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -44,7 +44,7 @@ benchmarks! { }: _(RawOrigin::Root, Some(asset_id), Some(name.clone()), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient) verify { - let b_name = Pallet::::to_bounded_name(name).unwrap(); + let b_name = Pallet::::try_into_bounded(Some(name)).unwrap().unwrap(); assert!(Pallet::::asset_ids(b_name).is_some()); assert!(Pallet::::assets(asset_id).is_some()); @@ -73,8 +73,8 @@ benchmarks! { }: _(RawOrigin::Root, asset_id, Some(new_name.clone()), Some(new_type), Some(new_ed), Some(new_xcm_rate_limit), Some(new_is_sufficient), Some(new_symbol.clone()), Some(new_decimals), Some(Default::default())) verify { - let b_name = Pallet::::to_bounded_name(new_name).unwrap(); - let b_symbol = Pallet::::to_bounded_name(new_symbol).unwrap(); + let b_name = Pallet::::try_into_bounded(Some(new_name)).unwrap().unwrap(); + let b_symbol = Pallet::::try_into_bounded(Some(new_symbol)).unwrap().unwrap(); assert_eq!(Pallet::::asset_ids(&b_name), Some(asset_id)); diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 10d2480e0..14127692e 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -17,9 +17,9 @@ #![cfg_attr(not(feature = "std"), no_std)] -use frame_support::dispatch::DispatchError; use frame_support::pallet_prelude::*; use frame_support::sp_runtime::traits::CheckedAdd; +use frame_support::{dispatch::DispatchError, require_transactional}; use frame_system::pallet_prelude::*; use orml_traits::MultiCurrency; use scale_info::TypeInfo; @@ -43,11 +43,13 @@ pub use types::AssetType; pub use pallet::*; pub use crate::types::{AssetDetails, Balance}; +use frame_support::storage::with_transaction; use frame_support::BoundedVec; use hydradx_traits::{ registry::{Create, Inspect, Mutate}, AssetKind, CreateRegistry, Registry, ShareTokenRegistry, }; +use sp_runtime::TransactionOutcome; /// Default value of existential deposit. This value is used if existential deposit wasn't /// provided. @@ -226,55 +228,59 @@ pub mod pallet { #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { - // Register native asset first - // It is to make sure that native is registered as any other asset - let native_asset_name = Pallet::::to_bounded_name(self.native_asset_name.to_vec()) - .map_err(|_| panic!("Invalid native asset name!")) - .unwrap(); - - let native_symbol = Pallet::::to_bounded_name(self.native_symbol.to_vec()) - .map_err(|_| panic!("Invalid native asset symbol!")) - .unwrap(); - - AssetIds::::insert(&native_asset_name, T::NativeAssetId::get()); - let details = AssetDetails { - name: Some(native_asset_name), - asset_type: AssetType::Token, - existential_deposit: self.native_existential_deposit, - xcm_rate_limit: None, - symbol: Some(native_symbol), - decimals: Some(self.native_decimals), - is_sufficient: true, - }; - - Assets::::insert(T::NativeAssetId::get(), details); - - self.registered_assets - .iter() - .for_each(|(id, name, ed, symbol, decimals, xcm_rate_limit, is_sufficient)| { - let bounded_name = name.as_ref().map(|name| { - Pallet::::to_bounded_name(name.to_vec()) - .map_err(|_| panic!("Invalid asset name!")) - .unwrap() - }); - let bounded_symbol = symbol.as_ref().map(|symbol| { - Pallet::::to_bounded_name(symbol.to_vec()) - .map_err(|_| panic!("Invalid symbol!")) - .unwrap() - }); - - let details = AssetDetails { - name: bounded_name, - asset_type: AssetType::Token, - existential_deposit: *ed, - xcm_rate_limit: *xcm_rate_limit, - symbol: bounded_symbol, - decimals: *decimals, - is_sufficient: *is_sufficient, - }; - let _ = Pallet::::do_register_asset(*id, &details, None) - .map_err(|_| panic!("Failed to register asset")); - }) + let _ = with_transaction(|| { + // Register native asset first + // It is to make sure that native is registered as any other asset + let native_asset_name = Pallet::::try_into_bounded(Some(self.native_asset_name.to_vec())) + .expect("Invalid native asset name!"); + + let native_symbol = Pallet::::try_into_bounded(Some(self.native_symbol.to_vec())) + .expect("Invalid native asset symbol!"); + + AssetIds::::insert( + native_asset_name.as_ref().expect("Invalid native asset name!"), + T::NativeAssetId::get(), + ); + let details = AssetDetails { + name: native_asset_name, + asset_type: AssetType::Token, + existential_deposit: self.native_existential_deposit, + xcm_rate_limit: None, + symbol: native_symbol, + decimals: Some(self.native_decimals), + is_sufficient: true, + }; + + Assets::::insert(T::NativeAssetId::get(), details); + + self.registered_assets.iter().for_each( + |(id, name, ed, symbol, decimals, xcm_rate_limit, is_sufficient)| { + let bounded_name = name.as_ref().map(|name| { + Pallet::::try_into_bounded(Some(name.to_vec())) + .expect("Invalid asset name!") + .unwrap() + }); + let bounded_symbol = symbol.as_ref().map(|symbol| { + Pallet::::try_into_bounded(Some(symbol.to_vec())) + .expect("Invalid symbol!") + .unwrap() + }); + + let details = AssetDetails { + name: bounded_name, + asset_type: AssetType::Token, + existential_deposit: *ed, + xcm_rate_limit: *xcm_rate_limit, + symbol: bounded_symbol, + decimals: *decimals, + is_sufficient: *is_sufficient, + }; + let _ = Pallet::::do_register_asset(*id, &details, None).expect("Failed to register asset"); + }, + ); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); } } @@ -351,18 +357,8 @@ pub mod pallet { ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; - let bounded_name = if let Some(name) = name { - let bounded_name = Self::to_bounded_name(name)?; - Some(bounded_name) - } else { - None - }; - - let bounded_symbol = if let Some(symbol) = symbol { - Some(Self::to_bounded_name(symbol)?) - } else { - None - }; + let bounded_name = Self::try_into_bounded(name)?; + let bounded_symbol = Self::try_into_bounded(symbol)?; let details = AssetDetails::new( bounded_name, @@ -410,28 +406,19 @@ pub mod pallet { Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { let mut details = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; - let new_bounded_name = if let Some(n) = name { - let new_name = Self::to_bounded_name(n)?; - ensure!(Self::asset_ids(&new_name).is_none(), Error::::AssetAlreadyRegistered); + let new_bounded_name = Self::try_into_bounded(name)?; + if let Some(new_name) = new_bounded_name.as_ref() { + ensure!(Self::asset_ids(new_name).is_none(), Error::::AssetAlreadyRegistered); if let Some(old_name) = &details.name { AssetIds::::remove(old_name); } if Some(new_name.clone()) != details.name { - AssetIds::::insert(&new_name, asset_id); + AssetIds::::insert(new_name, asset_id); } - - Some(new_name) - } else { - None - }; - - let bounded_symbol = if let Some(s) = symbol { - Some(Self::to_bounded_name(s)?) - } else { - None }; + let bounded_symbol = Self::try_into_bounded(symbol)?; details.name = new_bounded_name.or_else(|| details.name.clone()); details.asset_type = asset_type.unwrap_or(details.asset_type); @@ -512,8 +499,14 @@ impl Pallet { /// Convert Vec to BoundedVec so it respects the max set limit, otherwise return TooLong error //TODO: remove pub - pub fn to_bounded_name(name: Vec) -> Result, Error> { - name.try_into().map_err(|_| Error::::TooLong) + pub fn try_into_bounded(name: Option>) -> Result>, Error> { + if let Some(name) = name { + TryInto::>::try_into(name) + .map_err(|_| Error::::TooLong) + .map(Some) + } else { + Ok(None) + } } fn do_set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { @@ -530,6 +523,7 @@ impl Pallet { Ok(()) } + #[require_transactional] fn do_register_asset( selected_asset_id: Option, details: &AssetDetails, @@ -586,15 +580,16 @@ impl Pallet { asset_id: Option, is_sufficient: bool, ) -> Result { - let bounded_name: BoundedVec = Self::to_bounded_name(name)?; + let bounded_name = Self::try_into_bounded(Some(name))?; - if let Some(asset_id) = AssetIds::::get(&bounded_name) { + //NOTE: this unwrap is safe. + if let Some(asset_id) = AssetIds::::get(bounded_name.as_ref().unwrap()) { Ok(asset_id) } else { Self::do_register_asset( asset_id, &AssetDetails::new( - Some(bounded_name), + bounded_name, asset_type, existential_deposit, None, @@ -624,7 +619,8 @@ impl Registry, Balance, DispatchError> for Pallet } fn retrieve_asset(name: &Vec) -> Result { - let bounded_name = Self::to_bounded_name(name.clone())?; + //NOTE: This unwrap is safe. + let bounded_name = Self::try_into_bounded(Some(name.clone()))?.unwrap(); if let Some(asset_id) = AssetIds::::get(bounded_name) { Ok(asset_id) } else { @@ -692,7 +688,7 @@ impl CreateRegistry for Pallet { type Error = DispatchError; fn create_asset(name: &[u8], kind: AssetKind, existential_deposit: Balance) -> Result { - let bounded_name = Some(Self::to_bounded_name(name.to_vec())?); + let bounded_name = Self::try_into_bounded(Some(name.to_vec()))?; Pallet::::do_register_asset( None, @@ -732,18 +728,8 @@ impl Create for Pallet { xcm_rate_limit: Option, is_sufficient: bool, ) -> Result { - let bounded_name = if let Some(name) = name { - let bounded_name = Self::to_bounded_name(name.to_vec())?; - Some(bounded_name) - } else { - None - }; - - let bounded_symbol = if let Some(symbol) = symbol { - Some(Self::to_bounded_name(symbol.to_vec())?) - } else { - None - }; + let bounded_name = Self::try_into_bounded(name.map(|x| x.to_vec()))?; + let bounded_symbol = Self::try_into_bounded(symbol.map(|x| x.to_vec()))?; let details = AssetDetails::new( bounded_name, diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index 675bf1377..d2f271d55 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -39,22 +39,22 @@ fn register_should_work_when_all_params_are_provided() { )); //Assert - let bounded_name = Pallet::::to_bounded_name(name).unwrap(); - let bounded_symbol = Pallet::::to_bounded_name(symbol).unwrap(); + let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); + let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(asset_id), Some(AssetDetails { - name: Some(bounded_name.clone()), + name: bounded_name.clone(), asset_type: AssetType::Token, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: Some(bounded_symbol.clone()), + symbol: bounded_symbol.clone(), decimals: Some(decimals), is_sufficient }) ); - assert_eq!(Registry::asset_ids(bounded_name.clone()), Some(asset_id)); + assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(asset_id)); assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); @@ -62,11 +62,11 @@ fn register_should_work_when_all_params_are_provided() { assert!(has_event( Event::::Registered { asset_id, - asset_name: Some(bounded_name), + asset_name: bounded_name, asset_type: AssetType::Token, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: Some(bounded_symbol), + symbol: bounded_symbol, decimals: Some(decimals), is_sufficient } diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index e0da8ca72..0a07c51ab 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -48,16 +48,16 @@ fn update_should_work_when_asset_exists() { )); //Assert - let bounded_name = Pallet::::to_bounded_name(name).unwrap(); - let bounded_symbol = Pallet::::to_bounded_name(symbol).unwrap(); + let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); + let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(asset_id), Some(AssetDetails { - name: Some(bounded_name.clone()), + name: bounded_name.clone(), asset_type: AssetType::External, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: Some(bounded_symbol.clone()), + symbol: bounded_symbol.clone(), decimals: Some(decimals), is_sufficient: false }) @@ -67,18 +67,18 @@ fn update_should_work_when_asset_exists() { assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location)); - let old_bounded_name = Pallet::::to_bounded_name(old_asset_name).unwrap(); - assert_eq!(Registry::asset_ids(bounded_name.clone()).unwrap(), asset_id); - assert!(Registry::asset_ids(old_bounded_name).is_none()); + let old_bounded_name = Pallet::::try_into_bounded(Some(old_asset_name)).unwrap(); + assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()).unwrap(), asset_id); + assert!(Registry::asset_ids(old_bounded_name.unwrap()).is_none()); assert_last_event!(Event::::Updated { asset_id, - asset_name: Some(bounded_name), + asset_name: bounded_name, asset_type: AssetType::External, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), decimals: Some(decimals), - symbol: Some(bounded_symbol), + symbol: bounded_symbol, is_sufficient, } .into()); @@ -129,16 +129,16 @@ fn update_should_update_provided_params_when_values_was_previously_set() { )); //Assert - let bounded_name = Pallet::::to_bounded_name(name).unwrap(); - let bounded_symbol = Pallet::::to_bounded_name(symbol).unwrap(); + let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); + let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(asset_id), Some(AssetDetails { - name: Some(bounded_name.clone()), + name: bounded_name.clone(), asset_type: AssetType::External, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: Some(bounded_symbol.clone()), + symbol: bounded_symbol.clone(), decimals: Some(decimals), is_sufficient: false }) @@ -148,18 +148,18 @@ fn update_should_update_provided_params_when_values_was_previously_set() { assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location)); - let old_bounded_name = Pallet::::to_bounded_name(old_asset_name).unwrap(); - assert_eq!(Registry::asset_ids(bounded_name.clone()).unwrap(), asset_id); - assert!(Registry::asset_ids(old_bounded_name).is_none()); + let old_bounded_name = Pallet::::try_into_bounded(Some(old_asset_name)).unwrap(); + assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()).unwrap(), asset_id); + assert!(Registry::asset_ids(old_bounded_name.unwrap()).is_none()); assert_last_event!(Event::::Updated { asset_id, - asset_name: Some(bounded_name), + asset_name: bounded_name, asset_type: AssetType::External, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), decimals: Some(decimals), - symbol: Some(bounded_symbol), + symbol: bounded_symbol, is_sufficient, } .into()); @@ -202,8 +202,8 @@ fn update_should_not_change_values_when_param_is_none() { //Assert assert_eq!(Registry::assets(asset_id).unwrap(), details_0); - let old_bounded_name = Pallet::::to_bounded_name(b"Tkn2".to_vec()).unwrap(); - assert_eq!(Registry::asset_ids(old_bounded_name).unwrap(), asset_id); + let old_bounded_name = Pallet::::try_into_bounded(Some(b"Tkn2".to_vec())).unwrap(); + assert_eq!(Registry::asset_ids(old_bounded_name.unwrap()).unwrap(), asset_id); //NOTE: location should't change assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); @@ -572,3 +572,46 @@ fn update_should_update_location_when_origin_is_registry_origin() { )); }); } + +#[test] +fn update_should_not_work_when_name_is_same_as_old() { + let old_asset_name = b"Tkn2".to_vec(); + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(old_asset_name.clone()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + let name = old_asset_name.clone(); + let ed = 10_000 * UNIT; + let xcm_rate_limit = 463; + let symbol = b"nTkn2".to_vec(); + let decimals = 23; + let is_sufficient = false; + + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::set_location(asset_id, asset_location).unwrap(); + + //Act + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol), + Some(decimals), + None + ), + Error::::AssetAlreadyRegistered + ); + }); +} diff --git a/primitives/src/constants.rs b/primitives/src/constants.rs index b727f2c6f..53f22ac52 100644 --- a/primitives/src/constants.rs +++ b/primitives/src/constants.rs @@ -23,8 +23,6 @@ pub mod currency { pub const DOLLARS: Balance = UNITS * 100; // 100 UNITS ~= 1 $ pub const CENTS: Balance = DOLLARS / 100; // 1 UNITS ~= 1 cent pub const MILLICENTS: Balance = CENTS / 1_000; - //NOTE: Changing of this value require migration. - //See `SufficiencyCheck.on_fund()` doc. pub const NATIVE_EXISTENTIAL_DEPOSIT: Balance = CENTS; pub fn deposit(items: u32, bytes: u32) -> Balance { From eb801d71d46ed1f7b0334f98385a78d69cda5046 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 18 Oct 2023 17:03:03 +0200 Subject: [PATCH 37/93] asset-registry: use max stringlimit in benmarks --- pallets/asset-registry/src/benchmarking.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index bc89beee1..eb71885fc 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -34,9 +34,9 @@ benchmarks! { register { let asset_id= T::AssetId::from(3); - let name = b"Test name".to_vec(); + let name = vec![97u8; T::StringLimit::get() as usize]; let ed = 1_000_000_u128; - let symbol = b"TKN".to_vec(); + let symbol = vec![97u8; T::StringLimit::get() as usize]; let decimals = 12_u8; let location: T::AssetNativeLocation = Default::default(); let xcm_rate_limit = 1_000_u128; @@ -52,9 +52,9 @@ benchmarks! { update { let asset_id = T::AssetId::from(3); - let name = b"Test name".to_vec(); + let name = vec![97u8; T::StringLimit::get() as usize]; let ed = 1_000_000_u128; - let symbol = b"TKN".to_vec(); + let symbol = vec![97u8; T::StringLimit::get() as usize]; let decimals = 12_u8; let location: T::AssetNativeLocation = Default::default(); let xcm_rate_limit = 1_000_u128; @@ -62,12 +62,12 @@ benchmarks! { let _ = Pallet::::register(RawOrigin::Root.into(), Some(asset_id), Some(name), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient); - let new_name= b"New name".to_vec(); + let new_name= vec![98u8; T::StringLimit::get() as usize]; let new_type = AssetType::PoolShare(T::AssetId::from(10u8),T::AssetId::from(20u8)); let new_ed = 1_000_000_u128; let new_xcm_rate_limit = 1_000_u128; let new_is_sufficient = false; - let new_symbol = b"TKNn".to_vec(); + let new_symbol = vec![98u8; T::StringLimit::get() as usize]; let new_decimals = 12_u8; From beb4446c14699e8d9f2fa5e83ea41c3c546a797f Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 18 Oct 2023 17:32:36 +0200 Subject: [PATCH 38/93] asset-registry: updated call_index of registre_external() --- pallets/asset-registry/src/benchmarking.rs | 3 ++- pallets/asset-registry/src/lib.rs | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index eb71885fc..7879a8e10 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -23,6 +23,7 @@ use crate::types::AssetDetails; use frame_benchmarking::{account, benchmarks}; use frame_system::RawOrigin; use orml_traits::MultiCurrencyExtended; +use sp_std::vec; const UNIT: u128 = 1_000_000_000_000; @@ -34,7 +35,7 @@ benchmarks! { register { let asset_id= T::AssetId::from(3); - let name = vec![97u8; T::StringLimit::get() as usize]; + let name = vec![97u8; T::StringLimit::get() as usize]; let ed = 1_000_000_u128; let symbol = vec![97u8; T::StringLimit::get() as usize]; let decimals = 12_u8; diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 14127692e..be98deaa6 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -462,7 +462,8 @@ pub mod pallet { }) } - #[pallet::call_index(3)] + //NOTE: call indices 2 and 3 were used by removed extrinsics. + #[pallet::call_index(4)] #[pallet::weight(::WeightInfo::register_external())] pub fn register_external(origin: OriginFor, location: T::AssetNativeLocation) -> DispatchResult { let who = ensure_signed(origin)?; @@ -498,8 +499,7 @@ impl Pallet { } /// Convert Vec to BoundedVec so it respects the max set limit, otherwise return TooLong error - //TODO: remove pub - pub fn try_into_bounded(name: Option>) -> Result>, Error> { + fn try_into_bounded(name: Option>) -> Result>, Error> { if let Some(name) = name { TryInto::>::try_into(name) .map_err(|_| Error::::TooLong) From 2250a3a5348aa68ce9ffef7bb66e705c925db03f Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 19 Oct 2023 10:32:16 +0200 Subject: [PATCH 39/93] sufficinecyCheck: updated docs --- pallets/asset-registry/src/lib.rs | 2 +- runtime/hydradx/src/assets.rs | 24 +++++++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index be98deaa6..8b1c4abd5 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -462,7 +462,7 @@ pub mod pallet { }) } - //NOTE: call indices 2 and 3 were used by removed extrinsics. + //NOTE: call indices 2 and 3 were used by removed extrinsics. #[pallet::call_index(4)] #[pallet::weight(::WeightInfo::register_external())] pub fn register_external(origin: OriginFor, location: T::AssetNativeLocation) -> DispatchResult { diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 9abf0d438..76329b8dd 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -108,16 +108,34 @@ pub struct SufficiencyCheck; impl SufficiencyCheck { /// This function is used by `orml-toknes` `MutationHooks` before a transaction is executed. /// It is called from `PreDeposit` and `PreTransfer`. - /// If transferred asset is not sufficient asset it calculates ED amount in user's fee asset + /// If transferred asset is not sufficient asset, it calculates ED amount in user's fee asset /// and transfers it from user to treasury account. /// Function also locks corresponding HDX amount in the treasury because returned ED to the users /// when the account is killed is in the HDX. /// + /// We assume account already paid ED if it holds transferred insufficient asset so additional + /// ED payment is not necessary. + /// /// NOTE: `OnNewTokenAccount` mutation hooks is not used because it can't fail so we would not /// be able to fail transactions e.g. if the user doesn't have enough funds to pay ED. /// - /// NOTE: Changing of ED in the `pallet_balances` requires migration of all the users with - /// insufficient assets to the new ED amount. + /// ED payment - transfer: + /// - if both sender and dest. accounts are regular accounts, sender pays ED for dest. account. + /// - if sender is whitelisted account, dest. accounts pays its own ED. + /// + /// ED payment - deposit: + /// - dest. accounts always pays its own ED no matter if it's whitelisted or not. + /// + /// ED release: + /// ED is always released on account kill to killed account, whitelisting doesn't matter. + /// Released ED amount is calculated from locked HDX divided by number of accounts that paid + /// ED. + /// + /// WARN: + /// `set_balance` - bypass `MutationHooks` so no one pays ED for these account but ED is still released + /// when account is killed. + /// + /// Emits `pallet_asset_registry::Event::ExistentialDepositPaid` when ED was paid. fn on_funds(asset: AssetId, paying_account: &AccountId, to: &AccountId) -> DispatchResult { if orml_tokens::Accounts::::try_get(to, asset).is_err() && !AssetRegistry::is_sufficient(asset) { let fee_payment_asset = MultiTransactionPayment::account_currency(paying_account); From ca681e62333dd66e746d03dc21801ce5cbf28ec8 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 19 Oct 2023 12:51:51 +0200 Subject: [PATCH 40/93] asset-registry: added test to check name and symblo length --- pallets/asset-registry/src/tests/register.rs | 60 +++++++++++++++++ pallets/asset-registry/src/tests/update.rs | 71 +++++++++++++++++++- 2 files changed, 129 insertions(+), 2 deletions(-) diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index d2f271d55..d02629a2c 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -501,3 +501,63 @@ fn register_external_asset_should_not_work_when_user_cant_pay_storage_fees() { ); }); } + +#[test] +fn register_should_fail_when_name_is_too_long() { + ExtBuilder::default().build().execute_with(|| { + let asset_id = 1; + let name = vec![97u8; ::StringLimit::get() as usize + 1]; + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_noop!(Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), Error::::TooLong); + }); +} + +#[test] +fn register_should_fail_when_symbol_is_too_long() { + ExtBuilder::default().build().execute_with(|| { + let asset_id = 1; + let name = b"Test asset".to_vec(); + let symbol = vec![97u8; ::StringLimit::get() as usize + 1]; + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_noop!(Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), Error::::TooLong); + }); +} diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index 0a07c51ab..7e726e1ba 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -243,7 +243,7 @@ fn update_origin_should_set_decimals_if_its_none() { let details_0 = Registry::assets(asset_id).unwrap(); - //NOTE: update origin is ste to ensure_signed + //NOTE: update origin is set to ensure_signed //Act assert_ok!(Registry::update( RuntimeOrigin::signed(ALICE), @@ -344,7 +344,6 @@ fn create_origin_should_always_set_decimals() { let details_0 = Registry::assets(asset_id).unwrap(); - //NOTE: update origin is ste to ensure_signed //Act assert_ok!(Registry::update( RuntimeOrigin::root(), @@ -615,3 +614,71 @@ fn update_should_not_work_when_name_is_same_as_old() { ); }); } + +#[test] +fn update_should_fail_when_name_is_too_long() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + let name = vec![97u8; ::StringLimit::get() as usize + 1]; + let ed = 10_000 * UNIT; + let xcm_rate_limit = 463; + let symbol = b"nTkn2".to_vec(); + let decimals = 23; + let is_sufficient = false; + + //Act + assert_noop!(Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + None + ), Error::::TooLong); + }); +} + +#[test] +fn update_should_fail_when_symbolis_too_long() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + let name = b"New Token Name".to_vec(); + let ed = 10_000 * UNIT; + let xcm_rate_limit = 463; + let symbol = vec![97u8; ::StringLimit::get() as usize + 1]; + let decimals = 23; + let is_sufficient = false; + + //Act + assert_noop!(Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + None + ), Error::::TooLong); + }); +} From def81dbb1d5b33c2adb549f9436c97f38ce8835a Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 19 Oct 2023 13:07:23 +0200 Subject: [PATCH 41/93] asset-registry: fixed typos and formating --- pallets/asset-registry/src/tests/register.rs | 54 +++++++++------- pallets/asset-registry/src/tests/update.rs | 68 +++++++++++--------- 2 files changed, 69 insertions(+), 53 deletions(-) diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index d02629a2c..91a9db98d 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -517,18 +517,21 @@ fn register_should_fail_when_name_is_too_long() { let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); //Act - assert_noop!(Registry::register( - RuntimeOrigin::root(), - Some(asset_id), - Some(name.clone()), - AssetType::Token, - Some(ed), - Some(symbol.clone()), - Some(decimals), - Some(asset_location.clone()), - Some(xcm_rate_limit), - is_sufficient - ), Error::::TooLong); + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + Error::::TooLong + ); }); } @@ -547,17 +550,20 @@ fn register_should_fail_when_symbol_is_too_long() { let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); //Act - assert_noop!(Registry::register( - RuntimeOrigin::root(), - Some(asset_id), - Some(name.clone()), - AssetType::Token, - Some(ed), - Some(symbol.clone()), - Some(decimals), - Some(asset_location.clone()), - Some(xcm_rate_limit), - is_sufficient - ), Error::::TooLong); + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + Error::::TooLong + ); }); } diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index 7e726e1ba..52606def0 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -144,7 +144,7 @@ fn update_should_update_provided_params_when_values_was_previously_set() { }) ); - //NOTE: location should't change + //NOTE: location shouldn't change assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location)); @@ -205,7 +205,7 @@ fn update_should_not_change_values_when_param_is_none() { let old_bounded_name = Pallet::::try_into_bounded(Some(b"Tkn2".to_vec())).unwrap(); assert_eq!(Registry::asset_ids(old_bounded_name.unwrap()).unwrap(), asset_id); - //NOTE: location should't change + //NOTE: location shouldn't change assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location)); @@ -517,6 +517,7 @@ fn update_should_update_location_when_origin_is_registry_origin() { let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + let details_0 = Registry::assets(asset_id).unwrap(); assert_ok!(Registry::update( RuntimeOrigin::root(), asset_id, @@ -530,6 +531,7 @@ fn update_should_update_location_when_origin_is_registry_origin() { Some(asset_location.clone()), )); + assert_eq!(Registry::assets(asset_id).unwrap(), details_0); assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); assert!(has_event( @@ -543,6 +545,7 @@ fn update_should_update_location_when_origin_is_registry_origin() { //Arrange - location should not be updated if it exists let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let second_location = AssetLocation(MultiLocation::new(0, X2(Parachain(400), key))); + let details_0 = Registry::assets(asset_id).unwrap(); //Act assert_ok!(Registry::update( @@ -558,6 +561,7 @@ fn update_should_update_location_when_origin_is_registry_origin() { Some(second_location.clone()) )); + assert_eq!(Registry::assets(asset_id).unwrap(), details_0); assert!(Registry::location_assets(asset_location).is_none()); assert_eq!(Registry::location_assets(second_location.clone()), Some(asset_id)); @@ -626,7 +630,7 @@ fn update_should_fail_when_name_is_too_long() { .build() .execute_with(|| { let asset_id = 2; - let name = vec![97u8; ::StringLimit::get() as usize + 1]; + let name = vec![97u8; ::StringLimit::get() as usize + 1]; let ed = 10_000 * UNIT; let xcm_rate_limit = 463; let symbol = b"nTkn2".to_vec(); @@ -634,18 +638,21 @@ fn update_should_fail_when_name_is_too_long() { let is_sufficient = false; //Act - assert_noop!(Registry::update( - RuntimeOrigin::root(), - asset_id, - Some(name.clone()), - Some(AssetType::External), - Some(ed), - Some(xcm_rate_limit), - Some(is_sufficient), - Some(symbol.clone()), - Some(decimals), - None - ), Error::::TooLong); + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + None + ), + Error::::TooLong + ); }); } @@ -660,25 +667,28 @@ fn update_should_fail_when_symbolis_too_long() { .build() .execute_with(|| { let asset_id = 2; - let name = b"New Token Name".to_vec(); + let name = b"New Token Name".to_vec(); let ed = 10_000 * UNIT; let xcm_rate_limit = 463; - let symbol = vec![97u8; ::StringLimit::get() as usize + 1]; + let symbol = vec![97u8; ::StringLimit::get() as usize + 1]; let decimals = 23; let is_sufficient = false; //Act - assert_noop!(Registry::update( - RuntimeOrigin::root(), - asset_id, - Some(name.clone()), - Some(AssetType::External), - Some(ed), - Some(xcm_rate_limit), - Some(is_sufficient), - Some(symbol.clone()), - Some(decimals), - None - ), Error::::TooLong); + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + None + ), + Error::::TooLong + ); }); } From 776f9cd759fe64bb00ca92beb03135aaf8e0265d Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 23 Oct 2023 11:21:50 +0200 Subject: [PATCH 42/93] asset-registry: removed NativeAssetId from config + make clippy happy --- pallets/asset-registry/src/benchmarking.rs | 2 +- pallets/asset-registry/src/lib.rs | 13 +++++++------ pallets/asset-registry/src/tests/mock.rs | 2 +- pallets/asset-registry/src/tests/register.rs | 12 ++++++------ pallets/asset-registry/src/tests/update.rs | 8 ++++---- pallets/xyk/src/tests/mock.rs | 2 +- runtime/hydradx/src/assets.rs | 2 +- 7 files changed, 21 insertions(+), 20 deletions(-) diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index 7879a8e10..95804aea1 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -92,7 +92,7 @@ benchmarks! { register_external { let caller: T::AccountId = account("caller", 0, 1); - T::Currency::update_balance(T::NativeAssetId::get(), &caller, (100_000 * UNIT) as i128)?; + T::Currency::update_balance(T::StorageFeesAssetId::get(), &caller, (100_000 * UNIT) as i128)?; let expected_asset_id = Pallet::::next_asset_id().unwrap(); let location: T::AssetNativeLocation = Default::default(); diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 8b1c4abd5..b16fedc35 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -93,9 +93,9 @@ pub mod pallet { #[pallet::constant] type SequentialIdStartAt: Get; - /// Native Asset Id + /// Id of the asset that is used to pay storage fees. #[pallet::constant] - type NativeAssetId: Get; + type StorageFeesAssetId: Get; /// Storage fees for external asset creation. #[pallet::constant] @@ -237,9 +237,10 @@ pub mod pallet { let native_symbol = Pallet::::try_into_bounded(Some(self.native_symbol.to_vec())) .expect("Invalid native asset symbol!"); + let native_asset_id = T::AssetId::from(0); AssetIds::::insert( native_asset_name.as_ref().expect("Invalid native asset name!"), - T::NativeAssetId::get(), + native_asset_id, ); let details = AssetDetails { name: native_asset_name, @@ -251,7 +252,7 @@ pub mod pallet { is_sufficient: true, }; - Assets::::insert(T::NativeAssetId::get(), details); + Assets::::insert(native_asset_id, details); self.registered_assets.iter().for_each( |(id, name, ed, symbol, decimals, xcm_rate_limit, is_sufficient)| { @@ -470,12 +471,12 @@ pub mod pallet { if !T::StorageFees::get().is_zero() { ensure!( - T::Currency::ensure_can_withdraw(T::NativeAssetId::get(), &who, T::StorageFees::get()).is_ok(), + T::Currency::ensure_can_withdraw(T::StorageFeesAssetId::get(), &who, T::StorageFees::get()).is_ok(), Error::::InsufficientBalance ); T::Currency::transfer( - T::NativeAssetId::get(), + T::StorageFeesAssetId::get(), &who, &T::StorageFeesBeneficiary::get(), T::StorageFees::get(), diff --git a/pallets/asset-registry/src/tests/mock.rs b/pallets/asset-registry/src/tests/mock.rs index 9dc90e806..d3aa3aa08 100644 --- a/pallets/asset-registry/src/tests/mock.rs +++ b/pallets/asset-registry/src/tests/mock.rs @@ -111,7 +111,7 @@ impl pallet_asset_registry::Config for Test { type AssetNativeLocation = AssetLocation; type StringLimit = RegistryStringLimit; type SequentialIdStartAt = SequentialIdStart; - type NativeAssetId = NativeAssetId; + type StorageFeesAssetId = NativeAssetId; type StorageFees = StoreFees; type StorageFeesBeneficiary = FeesBeneficiarry; type WeightInfo = (); diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index 91a9db98d..766af4159 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -521,12 +521,12 @@ fn register_should_fail_when_name_is_too_long() { Registry::register( RuntimeOrigin::root(), Some(asset_id), - Some(name.clone()), + Some(name), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), - Some(asset_location.clone()), + Some(asset_location), Some(xcm_rate_limit), is_sufficient ), @@ -554,12 +554,12 @@ fn register_should_fail_when_symbol_is_too_long() { Registry::register( RuntimeOrigin::root(), Some(asset_id), - Some(name.clone()), + Some(name), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), - Some(asset_location.clone()), + Some(asset_location), Some(xcm_rate_limit), is_sufficient ), diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index 52606def0..e40252a0e 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -642,12 +642,12 @@ fn update_should_fail_when_name_is_too_long() { Registry::update( RuntimeOrigin::root(), asset_id, - Some(name.clone()), + Some(name), Some(AssetType::External), Some(ed), Some(xcm_rate_limit), Some(is_sufficient), - Some(symbol.clone()), + Some(symbol), Some(decimals), None ), @@ -679,12 +679,12 @@ fn update_should_fail_when_symbolis_too_long() { Registry::update( RuntimeOrigin::root(), asset_id, - Some(name.clone()), + Some(name), Some(AssetType::External), Some(ed), Some(xcm_rate_limit), Some(is_sufficient), - Some(symbol.clone()), + Some(symbol), Some(decimals), None ), diff --git a/pallets/xyk/src/tests/mock.rs b/pallets/xyk/src/tests/mock.rs index 942cd405d..69619aa3f 100644 --- a/pallets/xyk/src/tests/mock.rs +++ b/pallets/xyk/src/tests/mock.rs @@ -115,7 +115,7 @@ impl pallet_asset_registry::Config for Test { type AssetNativeLocation = u8; type StringLimit = RegistryStringLimit; type SequentialIdStartAt = SequentialIdOffset; - type NativeAssetId = NativeAssetId; + type StorageFeesAssetId = NativeAssetId; type StorageFees = StoreFees; type StorageFeesBeneficiary = FeesBeneficiarry; type WeightInfo = (); diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 76329b8dd..6be97934a 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -349,7 +349,7 @@ impl pallet_asset_registry::Config for Runtime { type AssetNativeLocation = AssetLocation; type StringLimit = RegistryStrLimit; type SequentialIdStartAt = SequentialIdOffset; - type NativeAssetId = NativeAssetId; + type StorageFeesAssetId = NativeAssetId; type StorageFees = StoreFees; type StorageFeesBeneficiary = TreasuryAccount; type WeightInfo = weights::registry::HydraWeight; From 3c485c4bd9df61ff6730b56bf746318aa4f022d6 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 23 Oct 2023 14:33:57 +0200 Subject: [PATCH 43/93] asset-registry: regenerated default weights.rs --- pallets/asset-registry/src/weights.rs | 53 +++++++++++++-------------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/pallets/asset-registry/src/weights.rs b/pallets/asset-registry/src/weights.rs index 3e8d9e787..230427a32 100644 --- a/pallets/asset-registry/src/weights.rs +++ b/pallets/asset-registry/src/weights.rs @@ -18,7 +18,7 @@ //! Autogenerated weights for pallet_asset_registry //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-13, STEPS: 10, REPEAT: 30, LOW RANGE: [], HIGH RANGE: [] +//! DATE: 2023-10-23, STEPS: 10, REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: @@ -27,7 +27,7 @@ // pallet // --chain=dev // --steps=10 -// --repeat=30 +// --repeat=20 // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 @@ -51,36 +51,35 @@ pub trait WeightInfo { fn update() -> Weight; fn register_external() -> Weight; } - /// Weights for pallet_asset_registry using the hydraDX node and recommended hardware. pub struct HydraWeight(PhantomData); impl WeightInfo for HydraWeight { // Storage: AssetRegistry Assets (r:1 w:1) - // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(133), added: 2608, mode: MaxEncodedLen) // Storage: AssetRegistry AssetIds (r:1 w:1) // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) // Storage: AssetRegistry LocationAssets (r:1 w:1) // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry AssetLocations (r:0 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) fn register() -> Weight { - // Minimum execution time: 37_420 nanoseconds. - Weight::from_ref_time(38_232_000 as u64) + // Minimum execution time: 39_013 nanoseconds. + Weight::from_ref_time(39_795_000 as u64) .saturating_add(T::DbWeight::get().reads(3 as u64)) .saturating_add(T::DbWeight::get().writes(4 as u64)) } // Storage: AssetRegistry Assets (r:1 w:1) - // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(133), added: 2608, mode: MaxEncodedLen) // Storage: AssetRegistry AssetIds (r:1 w:2) // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) // Storage: AssetRegistry AssetLocations (r:1 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry LocationAssets (r:0 w:1) // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) fn update() -> Weight { - // Minimum execution time: 45_094 nanoseconds. - Weight::from_ref_time(46_207_000 as u64) + // Minimum execution time: 47_430 nanoseconds. + Weight::from_ref_time(47_760_000 as u64) .saturating_add(T::DbWeight::get().reads(3 as u64)) .saturating_add(T::DbWeight::get().writes(5 as u64)) } @@ -91,12 +90,12 @@ impl WeightInfo for HydraWeight { // Storage: AssetRegistry LocationAssets (r:1 w:1) // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry AssetLocations (r:0 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry Assets (r:0 w:1) - // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(133), added: 2608, mode: MaxEncodedLen) fn register_external() -> Weight { - // Minimum execution time: 62_277 nanoseconds. - Weight::from_ref_time(63_068_000 as u64) + // Minimum execution time: 63_891 nanoseconds. + Weight::from_ref_time(64_922_000 as u64) .saturating_add(T::DbWeight::get().reads(4 as u64)) .saturating_add(T::DbWeight::get().writes(6 as u64)) } @@ -104,30 +103,30 @@ impl WeightInfo for HydraWeight { impl WeightInfo for () { // Storage: AssetRegistry Assets (r:1 w:1) - // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(133), added: 2608, mode: MaxEncodedLen) // Storage: AssetRegistry AssetIds (r:1 w:1) // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) // Storage: AssetRegistry LocationAssets (r:1 w:1) // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry AssetLocations (r:0 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) fn register() -> Weight { - // Minimum execution time: 37_420 nanoseconds. - Weight::from_ref_time(38_232_000 as u64) + // Minimum execution time: 39_013 nanoseconds. + Weight::from_ref_time(39_795_000 as u64) .saturating_add(RocksDbWeight::get().reads(3 as u64)) .saturating_add(RocksDbWeight::get().writes(4 as u64)) } // Storage: AssetRegistry Assets (r:1 w:1) - // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(133), added: 2608, mode: MaxEncodedLen) // Storage: AssetRegistry AssetIds (r:1 w:2) // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) // Storage: AssetRegistry AssetLocations (r:1 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry LocationAssets (r:0 w:1) // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) fn update() -> Weight { - // Minimum execution time: 45_094 nanoseconds. - Weight::from_ref_time(46_207_000 as u64) + // Minimum execution time: 47_430 nanoseconds. + Weight::from_ref_time(47_760_000 as u64) .saturating_add(RocksDbWeight::get().reads(3 as u64)) .saturating_add(RocksDbWeight::get().writes(5 as u64)) } @@ -138,12 +137,12 @@ impl WeightInfo for () { // Storage: AssetRegistry LocationAssets (r:1 w:1) // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry AssetLocations (r:0 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry Assets (r:0 w:1) - // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(133), added: 2608, mode: MaxEncodedLen) fn register_external() -> Weight { - // Minimum execution time: 62_277 nanoseconds. - Weight::from_ref_time(63_068_000 as u64) + // Minimum execution time: 63_891 nanoseconds. + Weight::from_ref_time(64_922_000 as u64) .saturating_add(RocksDbWeight::get().reads(4 as u64)) .saturating_add(RocksDbWeight::get().writes(6 as u64)) } From 648523ee4a685285a31482ce281eb0678d3f2059 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 27 Oct 2023 11:07:01 +0200 Subject: [PATCH 44/93] Added transaction layer to integration-tests and removed proptest generated file --- integration-tests/src/bonds.rs | 134 +- integration-tests/src/dca.rs | 1821 +++++++++-------- integration-tests/src/router.rs | 912 +++++---- .../stableswap/tests/invariants.txt | 7 - 4 files changed, 1483 insertions(+), 1391 deletions(-) delete mode 100644 math/proptest-regressions/stableswap/tests/invariants.txt diff --git a/integration-tests/src/bonds.rs b/integration-tests/src/bonds.rs index ad758fc49..c3f4d2728 100644 --- a/integration-tests/src/bonds.rs +++ b/integration-tests/src/bonds.rs @@ -3,10 +3,12 @@ use crate::assert_balance; use crate::polkadot_test_net::*; +use frame_support::storage::with_transaction; use frame_support::{assert_noop, assert_ok}; use frame_system::RawOrigin; use hydradx_traits::CreateRegistry; use orml_traits::MultiCurrency; +use sp_runtime::{DispatchResult, TransactionOutcome}; use xcm_emulator::TestExt; use hydradx_runtime::{AssetRegistry, Bonds, Currencies, MultiTransactionPayment, Runtime, RuntimeOrigin, Tokens}; @@ -52,81 +54,89 @@ fn issue_bonds_should_work_when_issued_for_native_asset() { #[test] fn issue_bonds_should_work_when_issued_for_share_asset() { Hydra::execute_with(|| { - // Arrange - set_fee_asset_and_fund(ALICE.into(), BTC, 1_000_000); + let _ = with_transaction(|| { + // Arrange + set_fee_asset_and_fund(ALICE.into(), BTC, 1_000_000); + + let amount = 100 * UNITS; + let fee = ::ProtocolFee::get().mul_ceil(amount); + let amount_without_fee: Balance = amount.checked_sub(fee).unwrap(); + + let maturity = NOW + MONTH; + + let name = b"SHARED".to_vec(); + let share_asset_id = AssetRegistry::create_asset( + &name, + pallet_asset_registry::AssetType::PoolShare(HDX, DOT).into(), + 1_000, + ) + .unwrap(); + assert_ok!(Currencies::deposit(share_asset_id, &ALICE.into(), amount,)); + + // Act + let bond_id = AssetRegistry::next_asset_id().unwrap(); + assert_ok!(Bonds::issue( + RuntimeOrigin::signed(ALICE.into()), + share_asset_id, + amount, + maturity + )); - let amount = 100 * UNITS; - let fee = ::ProtocolFee::get().mul_ceil(amount); - let amount_without_fee: Balance = amount.checked_sub(fee).unwrap(); + // Assert + assert_eq!(Bonds::bond(bond_id).unwrap(), (share_asset_id, maturity)); - let maturity = NOW + MONTH; + let bond_asset_details = AssetRegistry::assets(bond_id).unwrap(); - let name = b"SHARED".to_vec(); - let share_asset_id = AssetRegistry::create_asset( - &name, - pallet_asset_registry::AssetType::PoolShare(HDX, DOT).into(), - 1_000, - ) - .unwrap(); - assert_ok!(Currencies::deposit(share_asset_id, &ALICE.into(), amount,)); + assert_eq!(bond_asset_details.asset_type, pallet_asset_registry::AssetType::Bond); + assert_eq!( + bond_asset_details.name.unwrap().into_inner(), + Bonds::bond_name(share_asset_id, maturity) + ); + assert_eq!(bond_asset_details.existential_deposit, 1_000); - // Act - let bond_id = AssetRegistry::next_asset_id().unwrap(); - assert_ok!(Bonds::issue( - RuntimeOrigin::signed(ALICE.into()), - share_asset_id, - amount, - maturity - )); + assert_balance!(&ALICE.into(), share_asset_id, 0); + assert_balance!(&ALICE.into(), bond_id, amount_without_fee); - // Assert - assert_eq!(Bonds::bond(bond_id).unwrap(), (share_asset_id, maturity)); + assert_balance!( + &::FeeReceiver::get(), + share_asset_id, + fee + ); - let bond_asset_details = AssetRegistry::assets(bond_id).unwrap(); + assert_balance!(&Bonds::pallet_account_id(), share_asset_id, amount_without_fee); - assert_eq!(bond_asset_details.asset_type, pallet_asset_registry::AssetType::Bond); - assert_eq!( - bond_asset_details.name.unwrap().into_inner(), - Bonds::bond_name(share_asset_id, maturity) - ); - assert_eq!(bond_asset_details.existential_deposit, 1_000); - - assert_balance!(&ALICE.into(), share_asset_id, 0); - assert_balance!(&ALICE.into(), bond_id, amount_without_fee); - - assert_balance!( - &::FeeReceiver::get(), - share_asset_id, - fee - ); - - assert_balance!(&Bonds::pallet_account_id(), share_asset_id, amount_without_fee); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } #[test] fn issue_bonds_should_not_work_when_issued_for_bond_asset() { Hydra::execute_with(|| { - // Arrange - let amount = 100 * UNITS; - let maturity = NOW + MONTH; - - let name = b"BOND".to_vec(); - let underlying_asset_id = - AssetRegistry::create_asset(&name, pallet_asset_registry::AssetType::::Bond.into(), 1_000) - .unwrap(); - assert_ok!(Currencies::deposit(underlying_asset_id, &ALICE.into(), amount,)); - - // Act & Assert - assert_noop!( - Bonds::issue( - RuntimeOrigin::signed(ALICE.into()), - underlying_asset_id, - amount, - maturity - ), - pallet_bonds::Error::::DisallowedAsset - ); + let _ = with_transaction(|| { + // Arrange + let amount = 100 * UNITS; + let maturity = NOW + MONTH; + + let name = b"BOND".to_vec(); + let underlying_asset_id = + AssetRegistry::create_asset(&name, pallet_asset_registry::AssetType::::Bond.into(), 1_000) + .unwrap(); + assert_ok!(Currencies::deposit(underlying_asset_id, &ALICE.into(), amount,)); + + // Act & Assert + assert_noop!( + Bonds::issue( + RuntimeOrigin::signed(ALICE.into()), + underlying_asset_id, + amount, + maturity + ), + pallet_bonds::Error::::DisallowedAsset + ); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } diff --git a/integration-tests/src/dca.rs b/integration-tests/src/dca.rs index d4428b00f..6c288a2c2 100644 --- a/integration-tests/src/dca.rs +++ b/integration-tests/src/dca.rs @@ -5,6 +5,7 @@ use crate::polkadot_test_net::*; use frame_support::assert_ok; use crate::{assert_balance, assert_reserved_balance}; +use frame_support::storage::with_transaction; use frame_system::RawOrigin; use hydradx_runtime::{ AssetRegistry, Balances, Currencies, Omnipool, Router, Runtime, RuntimeEvent, RuntimeOrigin, Stableswap, Tokens, @@ -26,6 +27,7 @@ use sp_runtime::traits::ConstU32; use sp_runtime::DispatchError; use sp_runtime::Permill; use sp_runtime::{BoundedVec, FixedU128}; +use sp_runtime::{DispatchResult, TransactionOutcome}; use xcm_emulator::TestExt; const TREASURY_ACCOUNT_INIT_BALANCE: Balance = 1000 * UNITS; @@ -1070,66 +1072,70 @@ mod stableswap { fn sell_should_work_when_two_stableassets_swapped() { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, asset_a, asset_b) = init_stableswap().unwrap(); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - asset_a, - FixedU128::from_rational(88, 100), - )); - - let alice_init_asset_a_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - asset_a, - alice_init_asset_a_balance as i128, - )); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - asset_a, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - asset_a, - asset_b, - 100 * UNITS, - 0u128, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule1 = schedule_fake_with_sell_order( - ALICE, - PoolType::Stableswap(pool_id), - dca_budget, - asset_a, - asset_b, - amount_to_sell, - ); - set_relaychain_block_number(10); - - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, 0); - assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget); - assert_balance!(&Treasury::account_id(), asset_a, 0); - - //Act - set_relaychain_block_number(11); - - //Assert - let fee = Currencies::free_balance(asset_a, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, 98999999706917); - assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget - amount_to_sell - fee); + let _ = with_transaction(|| { + //Arrange + let (pool_id, asset_a, asset_b) = init_stableswap().unwrap(); + + assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( + RuntimeOrigin::root(), + asset_a, + FixedU128::from_rational(88, 100), + )); + + let alice_init_asset_a_balance = 5000 * UNITS; + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + ALICE.into(), + asset_a, + alice_init_asset_a_balance as i128, + )); + + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + asset_a, + 5000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + asset_a, + asset_b, + 100 * UNITS, + 0u128, + )); + + let dca_budget = 1100 * UNITS; + let amount_to_sell = 100 * UNITS; + let schedule1 = schedule_fake_with_sell_order( + ALICE, + PoolType::Stableswap(pool_id), + dca_budget, + asset_a, + asset_b, + amount_to_sell, + ); + set_relaychain_block_number(10); + + create_schedule(ALICE, schedule1); + + assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); + assert_balance!(ALICE.into(), asset_b, 0); + assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget); + assert_balance!(&Treasury::account_id(), asset_a, 0); + + //Act + set_relaychain_block_number(11); + + //Assert + let fee = Currencies::free_balance(asset_a, &Treasury::account_id()); + assert!(fee > 0, "The treasury did not receive the fee"); + assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); + assert_balance!(ALICE.into(), asset_b, 98999999706917); + assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget - amount_to_sell - fee); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -1137,67 +1143,72 @@ mod stableswap { fn two_stableswap_asssets_should_be_swapped_when_they_have_different_decimals() { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, asset_a, asset_b) = init_stableswap_with_three_assets_having_different_decimals().unwrap(); - - //Populate oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - asset_b, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - asset_a, - asset_b, - 10_000_000, - 0u128, - )); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - asset_a, - FixedU128::from_rational(88, 100), - )); - - let alice_init_asset_a_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - asset_a, - alice_init_asset_a_balance as i128, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_sell = 100 * UNITS; - let schedule1 = schedule_fake_with_sell_order( - ALICE, - PoolType::Stableswap(pool_id), - dca_budget, - asset_a, - asset_b, - amount_to_sell, - ); - set_relaychain_block_number(10); - - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, 0); - assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget); - assert_balance!(&Treasury::account_id(), asset_a, 0); - - //Act - set_relaychain_block_number(11); - - //Assert - let fee = Currencies::free_balance(asset_a, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, 93176719400532); - assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget - amount_to_sell - fee); + let _ = with_transaction(|| { + //Arrange + let (pool_id, asset_a, asset_b) = + init_stableswap_with_three_assets_having_different_decimals().unwrap(); + + //Populate oracle + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + asset_b, + 5000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + asset_a, + asset_b, + 10_000_000, + 0u128, + )); + + assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( + RuntimeOrigin::root(), + asset_a, + FixedU128::from_rational(88, 100), + )); + + let alice_init_asset_a_balance = 5000 * UNITS; + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + ALICE.into(), + asset_a, + alice_init_asset_a_balance as i128, + )); + + let dca_budget = 1100 * UNITS; + let amount_to_sell = 100 * UNITS; + let schedule1 = schedule_fake_with_sell_order( + ALICE, + PoolType::Stableswap(pool_id), + dca_budget, + asset_a, + asset_b, + amount_to_sell, + ); + set_relaychain_block_number(10); + + create_schedule(ALICE, schedule1); + + assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); + assert_balance!(ALICE.into(), asset_b, 0); + assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget); + assert_balance!(&Treasury::account_id(), asset_a, 0); + + //Act + set_relaychain_block_number(11); + + //Assert + let fee = Currencies::free_balance(asset_a, &Treasury::account_id()); + assert!(fee > 0, "The treasury did not receive the fee"); + assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); + assert_balance!(ALICE.into(), asset_b, 93176719400532); + assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget - amount_to_sell - fee); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -1208,240 +1219,252 @@ mod stableswap { //With DCA TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 10000 * UNITS, - 0, - )); - - init_omnipol(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 10000 * UNITS as i128, - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - set_relaychain_block_number(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - 0, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - let dca_budget = 1100 * UNITS; + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_1, + 10000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + stable_asset_1, + stable_asset_2, + 10000 * UNITS, + 0, + )); + + init_omnipol(); + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 10000 * UNITS as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); + do_trade_to_populate_oracle(DAI, HDX, UNITS); + + set_relaychain_block_number(10); + + let alice_init_hdx_balance = 5000 * UNITS; + assert_ok!(Balances::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + alice_init_hdx_balance, + 0, + )); + + let trades = vec![ + Trade { + pool: PoolType::Omnipool, + asset_in: HDX, + asset_out: pool_id, + }, + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: pool_id, + asset_out: stable_asset_1, + }, + ]; + let dca_budget = 1100 * UNITS; + + let schedule = Schedule { + owner: AccountId::from(ALICE), + period: 3u32, + total_amount: dca_budget, + max_retries: None, + stability_threshold: None, + slippage: Some(Permill::from_percent(10)), + order: Order::Sell { + asset_in: HDX, + asset_out: stable_asset_1, + amount_in: amount_to_sell, + min_amount_out: Balance::MIN, + route: create_bounded_vec(trades), + }, + }; - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: 3u32, - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Sell { - asset_in: HDX, - asset_out: stable_asset_1, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(trades), - }, - }; + create_schedule(ALICE, schedule); - create_schedule(ALICE, schedule); + assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); + assert_balance!(ALICE.into(), stable_asset_1, 0); + assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); + assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, 0); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); + //Act + set_relaychain_block_number(11); - //Act - set_relaychain_block_number(11); + //Assert + let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; + assert!(fee > 0, "The treasury did not receive the fee"); + assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); + assert_balance!(ALICE.into(), stable_asset_1, amount_to_receive); - //Assert - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_receive); + assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - amount_to_sell - fee); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget - amount_to_sell - fee); + let treasury_balance = Currencies::free_balance(HDX, &Treasury::account_id()); + assert!(treasury_balance > TREASURY_ACCOUNT_INIT_BALANCE); - let treasury_balance = Currencies::free_balance(HDX, &Treasury::account_id()); - assert!(treasury_balance > TREASURY_ACCOUNT_INIT_BALANCE); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); //Do the same in with pool trades TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 10000 * UNITS, - 0, - )); - - init_omnipol(); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 10000 * UNITS as i128, - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - set_relaychain_block_number(10); - - //Act - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(ALICE.into()), - HDX, - pool_id, - amount_to_sell, - 0, - )); - - let pool_id_balance = Currencies::free_balance(pool_id, &AccountId::from(ALICE)); - - assert_ok!(Stableswap::remove_liquidity_one_asset( - RuntimeOrigin::signed(ALICE.into()), - pool_id, - stable_asset_1, - pool_id_balance, - 0 - )); - - //Assert - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - amount_to_sell); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_receive); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_1, + 10000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + stable_asset_1, + stable_asset_2, + 10000 * UNITS, + 0, + )); + + init_omnipol(); + + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 10000 * UNITS as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); + + do_trade_to_populate_oracle(DAI, HDX, UNITS); + + set_relaychain_block_number(10); + + //Act + assert_ok!(Omnipool::sell( + RuntimeOrigin::signed(ALICE.into()), + HDX, + pool_id, + amount_to_sell, + 0, + )); + + let pool_id_balance = Currencies::free_balance(pool_id, &AccountId::from(ALICE)); + + assert_ok!(Stableswap::remove_liquidity_one_asset( + RuntimeOrigin::signed(ALICE.into()), + pool_id, + stable_asset_1, + pool_id_balance, + 0 + )); + + //Assert + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - amount_to_sell); + assert_balance!(ALICE.into(), stable_asset_1, amount_to_receive); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); //Do the same with plain router TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 10000 * UNITS, - 0, - )); - - init_omnipol(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 10000 * UNITS as i128, - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - set_relaychain_block_number(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - 0, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - - assert_ok!(Router::sell( - RuntimeOrigin::signed(ALICE.into()), - HDX, - stable_asset_1, - amount_to_sell, - 0, - trades - )); - - //Assert - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - amount_to_sell); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_receive); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_1, + 10000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + stable_asset_1, + stable_asset_2, + 10000 * UNITS, + 0, + )); + + init_omnipol(); + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 10000 * UNITS as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); + do_trade_to_populate_oracle(DAI, HDX, UNITS); + + set_relaychain_block_number(10); + + let alice_init_hdx_balance = 5000 * UNITS; + assert_ok!(Balances::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + alice_init_hdx_balance, + 0, + )); + + let trades = vec![ + Trade { + pool: PoolType::Omnipool, + asset_in: HDX, + asset_out: pool_id, + }, + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: pool_id, + asset_out: stable_asset_1, + }, + ]; + + assert_ok!(Router::sell( + RuntimeOrigin::signed(ALICE.into()), + HDX, + stable_asset_1, + amount_to_sell, + 0, + trades + )); + + //Assert + assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - amount_to_sell); + assert_balance!(ALICE.into(), stable_asset_1, amount_to_receive); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -1451,316 +1474,328 @@ mod stableswap { let amount_to_receive = 70868187814642; TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //To populate stableswap oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 100 * UNITS, - 0, - )); - - //Set stable asset 1 as accepted payment currency - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(50, 100), - )); - - //Init omnipool and add pool id as token - init_omnipol(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS as i128, - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - - //Populate oracle with omnipool source - assert_ok!(Tokens::set_balance( - RawOrigin::Root.into(), - CHARLIE.into(), - pool_id, - 1000 * UNITS, - 0, - )); - - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - HDX, - 500 * UNITS, - Balance::MIN - )); - - set_relaychain_block_number(1000); - - let alice_init_stable1_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance as i128, - )); - - let trades = vec![ - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Omnipool, - asset_in: pool_id, - asset_out: HDX, - }, - ]; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: 3u32, - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Sell { - asset_in: stable_asset_1, - asset_out: HDX, - amount_in: amount_to_sell, - min_amount_out: Balance::MIN, - route: create_bounded_vec(trades), - }, - }; - - create_schedule(ALICE, schedule); - - assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget); - assert_balance!(&Treasury::account_id(), stable_asset_1, 0); - - //Act - set_relaychain_block_number(1001); - - //Assert - let fee = Currencies::free_balance(stable_asset_1, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_receive); - - assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget - amount_to_sell - fee); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + + //To populate stableswap oracle + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_1, + 10000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + stable_asset_1, + stable_asset_2, + 100 * UNITS, + 0, + )); + + //Set stable asset 1 as accepted payment currency + assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( + RuntimeOrigin::root(), + stable_asset_1, + FixedU128::from_rational(50, 100), + )); + + //Init omnipool and add pool id as token + init_omnipol(); + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 3000 * UNITS as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); + + //Populate oracle with omnipool source + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + CHARLIE.into(), + pool_id, + 1000 * UNITS, + 0, + )); + + assert_ok!(Omnipool::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + HDX, + 500 * UNITS, + Balance::MIN + )); + + set_relaychain_block_number(1000); + + let alice_init_stable1_balance = 5000 * UNITS; + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + ALICE.into(), + stable_asset_1, + alice_init_stable1_balance as i128, + )); + + let trades = vec![ + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: stable_asset_1, + asset_out: pool_id, + }, + Trade { + pool: PoolType::Omnipool, + asset_in: pool_id, + asset_out: HDX, + }, + ]; + let dca_budget = 1100 * UNITS; + + let schedule = Schedule { + owner: AccountId::from(ALICE), + period: 3u32, + total_amount: dca_budget, + max_retries: None, + stability_threshold: None, + slippage: Some(Permill::from_percent(10)), + order: Order::Sell { + asset_in: stable_asset_1, + asset_out: HDX, + amount_in: amount_to_sell, + min_amount_out: Balance::MIN, + route: create_bounded_vec(trades), + }, + }; + + create_schedule(ALICE, schedule); + + assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); + assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget); + assert_balance!(&Treasury::account_id(), stable_asset_1, 0); + + //Act + set_relaychain_block_number(1001); + + //Assert + let fee = Currencies::free_balance(stable_asset_1, &Treasury::account_id()); + assert!(fee > 0, "The treasury did not receive the fee"); + assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_receive); + + assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget - amount_to_sell - fee); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); //Do the same in with pool trades TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //To populate stableswap oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 100 * UNITS, - 0, - )); - - init_omnipol(); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS as i128, - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - - //Populate oracle with omnipool source - assert_ok!(Tokens::set_balance( - RawOrigin::Root.into(), - CHARLIE.into(), - pool_id, - 1000 * UNITS, - 0, - )); - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - HDX, - 500 * UNITS, - Balance::MIN - )); - - let alice_init_stable1_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance as i128, - )); - - assert_balance!(ALICE.into(), pool_id, 0); - - set_relaychain_block_number(10); - - //Act - assert_ok!(Stableswap::add_liquidity( - RuntimeOrigin::signed(ALICE.into()), - pool_id, - vec![AssetAmount { - asset_id: stable_asset_1, - amount: amount_to_sell, - }], - )); - let alice_pool_id_balance = Currencies::free_balance(pool_id, &AccountId::from(ALICE)); - - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(ALICE.into()), - pool_id, - HDX, - alice_pool_id_balance, - 0, - )); - - //Assert - assert_balance!( - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance - amount_to_sell - ); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_receive); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + + //To populate stableswap oracle + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_1, + 10000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + stable_asset_1, + stable_asset_2, + 100 * UNITS, + 0, + )); + + init_omnipol(); + + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 3000 * UNITS as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); + + //Populate oracle with omnipool source + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + CHARLIE.into(), + pool_id, + 1000 * UNITS, + 0, + )); + assert_ok!(Omnipool::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + HDX, + 500 * UNITS, + Balance::MIN + )); + + let alice_init_stable1_balance = 5000 * UNITS; + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + ALICE.into(), + stable_asset_1, + alice_init_stable1_balance as i128, + )); + + assert_balance!(ALICE.into(), pool_id, 0); + + set_relaychain_block_number(10); + + //Act + assert_ok!(Stableswap::add_liquidity( + RuntimeOrigin::signed(ALICE.into()), + pool_id, + vec![AssetAmount { + asset_id: stable_asset_1, + amount: amount_to_sell, + }], + )); + let alice_pool_id_balance = Currencies::free_balance(pool_id, &AccountId::from(ALICE)); + + assert_ok!(Omnipool::sell( + RuntimeOrigin::signed(ALICE.into()), + pool_id, + HDX, + alice_pool_id_balance, + 0, + )); + + //Assert + assert_balance!( + ALICE.into(), + stable_asset_1, + alice_init_stable1_balance - amount_to_sell + ); + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_receive); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); //Do the same with plain router TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //To populate stableswap oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 100 * UNITS, - 0, - )); - - init_omnipol(); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS as i128, - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - - //Populate oracle with omnipool source - assert_ok!(Tokens::set_balance( - RawOrigin::Root.into(), - CHARLIE.into(), - pool_id, - 1000 * UNITS, - 0, - )); - assert_ok!(Omnipool::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - HDX, - 500 * UNITS, - Balance::MIN - )); - - let alice_init_stable1_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance as i128, - )); - - assert_balance!(ALICE.into(), pool_id, 0); - - set_relaychain_block_number(10); - - //Act - let trades = vec![ - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Omnipool, - asset_in: pool_id, - asset_out: HDX, - }, - ]; - assert_ok!(Router::sell( - RuntimeOrigin::signed(ALICE.into()), - stable_asset_1, - HDX, - amount_to_sell, - 0, - trades - )); - - //Assert - assert_balance!( - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance - amount_to_sell - ); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_receive); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + + //To populate stableswap oracle + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_1, + 10000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + stable_asset_1, + stable_asset_2, + 100 * UNITS, + 0, + )); + + init_omnipol(); + + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 3000 * UNITS as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); + + //Populate oracle with omnipool source + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + CHARLIE.into(), + pool_id, + 1000 * UNITS, + 0, + )); + assert_ok!(Omnipool::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + HDX, + 500 * UNITS, + Balance::MIN + )); + + let alice_init_stable1_balance = 5000 * UNITS; + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + ALICE.into(), + stable_asset_1, + alice_init_stable1_balance as i128, + )); + + assert_balance!(ALICE.into(), pool_id, 0); + + set_relaychain_block_number(10); + + //Act + let trades = vec![ + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: stable_asset_1, + asset_out: pool_id, + }, + Trade { + pool: PoolType::Omnipool, + asset_in: pool_id, + asset_out: HDX, + }, + ]; + assert_ok!(Router::sell( + RuntimeOrigin::signed(ALICE.into()), + stable_asset_1, + HDX, + amount_to_sell, + 0, + trades + )); + + //Assert + assert_balance!( + ALICE.into(), + stable_asset_1, + alice_init_stable1_balance - amount_to_sell + ); + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_receive); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -1770,97 +1805,101 @@ mod stableswap { //With DCA TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //To populate stableswap oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 10000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 3000 * UNITS, - 0, - )); - - init_omnipol(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS as i128, - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - do_trade_to_populate_oracle(DAI, HDX, UNITS); - - set_relaychain_block_number(10); - - let alice_init_hdx_balance = 5000 * UNITS; - assert_ok!(Balances::set_balance( - RawOrigin::Root.into(), - ALICE.into(), - alice_init_hdx_balance, - 0, - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: 3u32, - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(10)), - order: Order::Buy { - asset_in: HDX, - asset_out: stable_asset_1, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(trades), - }, - }; - - create_schedule(ALICE, schedule); - - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, 0); - assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); - assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); - - //Act - set_relaychain_block_number(11); - - //Assert - let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_buy); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + + //To populate stableswap oracle + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_1, + 10000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + stable_asset_1, + stable_asset_2, + 3000 * UNITS, + 0, + )); + + init_omnipol(); + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 3000 * UNITS as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); + do_trade_to_populate_oracle(DAI, HDX, UNITS); + + set_relaychain_block_number(10); + + let alice_init_hdx_balance = 5000 * UNITS; + assert_ok!(Balances::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + alice_init_hdx_balance, + 0, + )); + + let trades = vec![ + Trade { + pool: PoolType::Omnipool, + asset_in: HDX, + asset_out: pool_id, + }, + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: pool_id, + asset_out: stable_asset_1, + }, + ]; + let dca_budget = 1100 * UNITS; + + let schedule = Schedule { + owner: AccountId::from(ALICE), + period: 3u32, + total_amount: dca_budget, + max_retries: None, + stability_threshold: None, + slippage: Some(Permill::from_percent(10)), + order: Order::Buy { + asset_in: HDX, + asset_out: stable_asset_1, + amount_out: amount_to_buy, + max_amount_in: Balance::MAX, + route: create_bounded_vec(trades), + }, + }; + + create_schedule(ALICE, schedule); + + assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); + assert_balance!(ALICE.into(), stable_asset_1, 0); + assert_reserved_balance!(&ALICE.into(), HDX, dca_budget); + assert_balance!(&Treasury::account_id(), HDX, TREASURY_ACCOUNT_INIT_BALANCE); + + //Act + set_relaychain_block_number(11); + + //Assert + let fee = Currencies::free_balance(HDX, &Treasury::account_id()) - TREASURY_ACCOUNT_INIT_BALANCE; + assert!(fee > 0, "The treasury did not receive the fee"); + assert_balance!(ALICE.into(), HDX, alice_init_hdx_balance - dca_budget); + assert_balance!(ALICE.into(), stable_asset_1, amount_to_buy); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -1868,64 +1907,68 @@ mod stableswap { fn buy_should_work_when_two_stableassets_swapped() { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, asset_a, asset_b) = init_stableswap().unwrap(); - - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - asset_a, - FixedU128::from_rational(88, 100), - )); - - let alice_init_asset_a_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - asset_a, - alice_init_asset_a_balance as i128, - )); - - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - asset_a, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - asset_a, - asset_b, - 100 * UNITS, - 0u128, - )); - - let dca_budget = 1100 * UNITS; - let amount_to_buy = 100 * UNITS; - let schedule1 = schedule_fake_with_buy_order( - PoolType::Stableswap(pool_id), - asset_a, - asset_b, - amount_to_buy, - dca_budget, - ); - set_relaychain_block_number(10); - - create_schedule(ALICE, schedule1); - - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, 0); - assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget); - assert_balance!(&Treasury::account_id(), asset_a, 0); - - //Act - set_relaychain_block_number(11); - - //Assert - let fee = Currencies::free_balance(asset_a, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); - assert_balance!(ALICE.into(), asset_b, amount_to_buy); + let _ = with_transaction(|| { + //Arrange + let (pool_id, asset_a, asset_b) = init_stableswap().unwrap(); + + assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( + RuntimeOrigin::root(), + asset_a, + FixedU128::from_rational(88, 100), + )); + + let alice_init_asset_a_balance = 5000 * UNITS; + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + ALICE.into(), + asset_a, + alice_init_asset_a_balance as i128, + )); + + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + asset_a, + 5000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + asset_a, + asset_b, + 100 * UNITS, + 0u128, + )); + + let dca_budget = 1100 * UNITS; + let amount_to_buy = 100 * UNITS; + let schedule1 = schedule_fake_with_buy_order( + PoolType::Stableswap(pool_id), + asset_a, + asset_b, + amount_to_buy, + dca_budget, + ); + set_relaychain_block_number(10); + + create_schedule(ALICE, schedule1); + + assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); + assert_balance!(ALICE.into(), asset_b, 0); + assert_reserved_balance!(&ALICE.into(), asset_a, dca_budget); + assert_balance!(&Treasury::account_id(), asset_a, 0); + + //Act + set_relaychain_block_number(11); + + //Assert + let fee = Currencies::free_balance(asset_a, &Treasury::account_id()); + assert!(fee > 0, "The treasury did not receive the fee"); + assert_balance!(ALICE.into(), asset_a, alice_init_asset_a_balance - dca_budget); + assert_balance!(ALICE.into(), asset_b, amount_to_buy); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -1934,106 +1977,110 @@ mod stableswap { let amount_to_buy = 100 * UNITS; TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - //Set stable asset 1 as accepted payment currency - assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( - RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_rational(50, 100), - )); - - //For populating oracle - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - CHARLIE.into(), - stable_asset_1, - 5000 * UNITS as i128, - )); - assert_ok!(Stableswap::sell( - RuntimeOrigin::signed(CHARLIE.into()), - pool_id, - stable_asset_1, - stable_asset_2, - 1000 * UNITS, - 0u128, - )); - - //Init omnipool and add pool id as token - init_omnipol(); - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS as i128, - )); - - assert_ok!(Omnipool::add_token( - RuntimeOrigin::root(), - pool_id, - FixedU128::from_rational(50, 100), - Permill::from_percent(100), - AccountId::from(BOB), - )); - - do_trade_to_populate_oracle(pool_id, HDX, 100 * UNITS); - - set_relaychain_block_number(10); - - let alice_init_stable1_balance = 5000 * UNITS; - assert_ok!(Currencies::update_balance( - RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - alice_init_stable1_balance as i128, - )); - - let trades = vec![ - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Omnipool, - asset_in: pool_id, - asset_out: HDX, - }, - ]; - let dca_budget = 1100 * UNITS; - - let schedule = Schedule { - owner: AccountId::from(ALICE), - period: 3u32, - total_amount: dca_budget, - max_retries: None, - stability_threshold: None, - slippage: Some(Permill::from_percent(70)), - order: Order::Buy { - asset_in: stable_asset_1, - asset_out: HDX, - amount_out: amount_to_buy, - max_amount_in: Balance::MAX, - route: create_bounded_vec(trades), - }, - }; - - create_schedule(ALICE, schedule); - - assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget); - assert_balance!(&Treasury::account_id(), stable_asset_1, 0); - - //Act - set_relaychain_block_number(11); - - //Assert - let fee = Currencies::free_balance(stable_asset_1, &Treasury::account_id()); - assert!(fee > 0, "The treasury did not receive the fee"); - assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_buy); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + + //Set stable asset 1 as accepted payment currency + assert_ok!(hydradx_runtime::MultiTransactionPayment::add_currency( + RuntimeOrigin::root(), + stable_asset_1, + FixedU128::from_rational(50, 100), + )); + + //For populating oracle + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + CHARLIE.into(), + stable_asset_1, + 5000 * UNITS as i128, + )); + assert_ok!(Stableswap::sell( + RuntimeOrigin::signed(CHARLIE.into()), + pool_id, + stable_asset_1, + stable_asset_2, + 1000 * UNITS, + 0u128, + )); + + //Init omnipool and add pool id as token + init_omnipol(); + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 3000 * UNITS as i128, + )); + + assert_ok!(Omnipool::add_token( + RuntimeOrigin::root(), + pool_id, + FixedU128::from_rational(50, 100), + Permill::from_percent(100), + AccountId::from(BOB), + )); + + do_trade_to_populate_oracle(pool_id, HDX, 100 * UNITS); + + set_relaychain_block_number(10); + + let alice_init_stable1_balance = 5000 * UNITS; + assert_ok!(Currencies::update_balance( + RuntimeOrigin::root(), + ALICE.into(), + stable_asset_1, + alice_init_stable1_balance as i128, + )); + + let trades = vec![ + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: stable_asset_1, + asset_out: pool_id, + }, + Trade { + pool: PoolType::Omnipool, + asset_in: pool_id, + asset_out: HDX, + }, + ]; + let dca_budget = 1100 * UNITS; + + let schedule = Schedule { + owner: AccountId::from(ALICE), + period: 3u32, + total_amount: dca_budget, + max_retries: None, + stability_threshold: None, + slippage: Some(Permill::from_percent(70)), + order: Order::Buy { + asset_in: stable_asset_1, + asset_out: HDX, + amount_out: amount_to_buy, + max_amount_in: Balance::MAX, + route: create_bounded_vec(trades), + }, + }; + + create_schedule(ALICE, schedule); + + assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); + assert_reserved_balance!(&ALICE.into(), stable_asset_1, dca_budget); + assert_balance!(&Treasury::account_id(), stable_asset_1, 0); + + //Act + set_relaychain_block_number(11); + + //Assert + let fee = Currencies::free_balance(stable_asset_1, &Treasury::account_id()); + assert!(fee > 0, "The treasury did not receive the fee"); + assert_balance!(ALICE.into(), stable_asset_1, alice_init_stable1_balance - dca_budget); + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_buy); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } } diff --git a/integration-tests/src/router.rs b/integration-tests/src/router.rs index 6f5de9812..8231c8f3d 100644 --- a/integration-tests/src/router.rs +++ b/integration-tests/src/router.rs @@ -26,9 +26,11 @@ use primitives::AssetId; use frame_support::{assert_noop, assert_ok}; use xcm_emulator::TestExt; +use frame_support::storage::with_transaction; use pallet_stableswap::types::AssetAmount; use pallet_stableswap::MAX_ASSETS_IN_POOL; use sp_runtime::{traits::ConstU32, DispatchError, FixedU128, Permill}; +use sp_runtime::{DispatchResult, TransactionOutcome}; use orml_traits::MultiCurrency; @@ -100,66 +102,70 @@ mod router_different_pools_tests { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (stable_pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - create_lbp_pool(DAI, HDX); + let _ = with_transaction(|| { + //Arrange + let (stable_pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + create_lbp_pool(DAI, HDX); + + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + ALICE.into(), + stable_asset_1, + 3000 * UNITS as i128, + )); + + create_xyk_pool(HDX, stable_asset_1); + + let amount_to_sell = UNITS / 100; + let limit = 0; + let trades = vec![ + Trade { + pool: PoolType::LBP, + asset_in: DAI, + asset_out: HDX, + }, + Trade { + pool: PoolType::XYK, + asset_in: HDX, + asset_out: stable_asset_1, + }, + Trade { + pool: PoolType::Stableswap(stable_pool_id), + asset_in: stable_asset_1, + asset_out: stable_asset_2, + }, + ]; + + start_lbp_campaign(); + + //Act + assert_ok!(Router::sell( + RuntimeOrigin::signed(BOB.into()), + DAI, + stable_asset_2, + amount_to_sell, + limit, + trades + )); - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - 3000 * UNITS as i128, - )); + //Assert + let amount_out = 2_783_595_233; - create_xyk_pool(HDX, stable_asset_1); + assert_balance!(BOB.into(), DAI, 1_000_000_000 * UNITS - amount_to_sell); + assert_balance!(BOB.into(), HDX, BOB_INITIAL_NATIVE_BALANCE); + assert_balance!(BOB.into(), stable_asset_1, 0); + assert_balance!(BOB.into(), stable_asset_2, amount_out); - let amount_to_sell = UNITS / 100; - let limit = 0; - let trades = vec![ - Trade { - pool: PoolType::LBP, + expect_hydra_events(vec![pallet_route_executor::Event::RouteExecuted { asset_in: DAI, - asset_out: HDX, - }, - Trade { - pool: PoolType::XYK, - asset_in: HDX, - asset_out: stable_asset_1, - }, - Trade { - pool: PoolType::Stableswap(stable_pool_id), - asset_in: stable_asset_1, asset_out: stable_asset_2, - }, - ]; - - start_lbp_campaign(); - - //Act - assert_ok!(Router::sell( - RuntimeOrigin::signed(BOB.into()), - DAI, - stable_asset_2, - amount_to_sell, - limit, - trades - )); - - //Assert - let amount_out = 2_783_595_233; - - assert_balance!(BOB.into(), DAI, 1_000_000_000 * UNITS - amount_to_sell); - assert_balance!(BOB.into(), HDX, BOB_INITIAL_NATIVE_BALANCE); - assert_balance!(BOB.into(), stable_asset_1, 0); - assert_balance!(BOB.into(), stable_asset_2, amount_out); + amount_in: amount_to_sell, + amount_out, + } + .into()]); - expect_hydra_events(vec![pallet_route_executor::Event::RouteExecuted { - asset_in: DAI, - asset_out: stable_asset_2, - amount_in: amount_to_sell, - amount_out, - } - .into()]); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -225,66 +231,70 @@ mod router_different_pools_tests { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (stable_pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - create_lbp_pool(DAI, HDX); + let _ = with_transaction(|| { + //Arrange + let (stable_pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + create_lbp_pool(DAI, HDX); + + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + ALICE.into(), + stable_asset_1, + 3000 * UNITS as i128, + )); + + create_xyk_pool(HDX, stable_asset_1); + + let amount_to_buy = UNITS; + let limit = 100 * UNITS; + let trades = vec![ + Trade { + pool: PoolType::LBP, + asset_in: DAI, + asset_out: HDX, + }, + Trade { + pool: PoolType::XYK, + asset_in: HDX, + asset_out: stable_asset_1, + }, + Trade { + pool: PoolType::Stableswap(stable_pool_id), + asset_in: stable_asset_1, + asset_out: stable_asset_2, + }, + ]; + + start_lbp_campaign(); + + //Act + assert_ok!(Router::buy( + RuntimeOrigin::signed(BOB.into()), + DAI, + stable_asset_2, + amount_to_buy, + limit, + trades + )); - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - 3000 * UNITS as i128, - )); + //Assert + let amount_in = 3_753_549_142_038; - create_xyk_pool(HDX, stable_asset_1); + assert_balance!(BOB.into(), DAI, 1_000_000_000 * UNITS - amount_in); + assert_balance!(BOB.into(), HDX, BOB_INITIAL_NATIVE_BALANCE); + assert_balance!(BOB.into(), stable_asset_1, 0); + assert_balance!(BOB.into(), stable_asset_2, amount_to_buy); - let amount_to_buy = UNITS; - let limit = 100 * UNITS; - let trades = vec![ - Trade { - pool: PoolType::LBP, + expect_hydra_events(vec![pallet_route_executor::Event::RouteExecuted { asset_in: DAI, - asset_out: HDX, - }, - Trade { - pool: PoolType::XYK, - asset_in: HDX, - asset_out: stable_asset_1, - }, - Trade { - pool: PoolType::Stableswap(stable_pool_id), - asset_in: stable_asset_1, asset_out: stable_asset_2, - }, - ]; - - start_lbp_campaign(); + amount_in, + amount_out: amount_to_buy, + } + .into()]); - //Act - assert_ok!(Router::buy( - RuntimeOrigin::signed(BOB.into()), - DAI, - stable_asset_2, - amount_to_buy, - limit, - trades - )); - - //Assert - let amount_in = 3_753_549_142_038; - - assert_balance!(BOB.into(), DAI, 1_000_000_000 * UNITS - amount_in); - assert_balance!(BOB.into(), HDX, BOB_INITIAL_NATIVE_BALANCE); - assert_balance!(BOB.into(), stable_asset_1, 0); - assert_balance!(BOB.into(), stable_asset_2, amount_to_buy); - - expect_hydra_events(vec![pallet_route_executor::Event::RouteExecuted { - asset_in: DAI, - asset_out: stable_asset_2, - amount_in, - amount_out: amount_to_buy, - } - .into()]); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -293,55 +303,59 @@ mod router_different_pools_tests { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); - - init_omnipool(); - - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - Omnipool::protocol_account(), - stable_asset_1, - 3000 * UNITS as i128, - )); - - assert_ok!(hydradx_runtime::Omnipool::add_token( - hydradx_runtime::RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_inner(25_650_000_000_000_000), - Permill::from_percent(1), - AccountId::from(BOB), - )); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, stable_asset_2) = init_stableswap().unwrap(); + + init_omnipool(); + + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + Omnipool::protocol_account(), + stable_asset_1, + 3000 * UNITS as i128, + )); + + assert_ok!(hydradx_runtime::Omnipool::add_token( + hydradx_runtime::RuntimeOrigin::root(), + stable_asset_1, + FixedU128::from_inner(25_650_000_000_000_000), + Permill::from_percent(1), + AccountId::from(BOB), + )); + + let trades = vec![ + Trade { + pool: PoolType::Omnipool, + asset_in: HDX, + asset_out: stable_asset_1, + }, + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: stable_asset_1, + asset_out: stable_asset_2, + }, + ]; + + //Act + let amount_to_sell = 100 * UNITS; + assert_ok!(Router::sell( + hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), + HDX, + stable_asset_2, + amount_to_sell, + 0, + trades + )); - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: stable_asset_1, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: stable_asset_2, - }, - ]; + //Assert + assert_eq!( + hydradx_runtime::Balances::free_balance(&AccountId::from(ALICE)), + ALICE_INITIAL_NATIVE_BALANCE - amount_to_sell + ); - //Act - let amount_to_sell = 100 * UNITS; - assert_ok!(Router::sell( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - HDX, - stable_asset_2, - amount_to_sell, - 0, - trades - )); - - //Assert - assert_eq!( - hydradx_runtime::Balances::free_balance(&AccountId::from(ALICE)), - ALICE_INITIAL_NATIVE_BALANCE - amount_to_sell - ); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -350,59 +364,63 @@ mod router_different_pools_tests { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); - - init_omnipool(); - - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - Omnipool::protocol_account(), - stable_asset_1, - 3000 * UNITS as i128, - )); - - assert_ok!(hydradx_runtime::Omnipool::add_token( - hydradx_runtime::RuntimeOrigin::root(), - stable_asset_1, - FixedU128::from_inner(25_650_000_000_000_000), - Permill::from_percent(1), - AccountId::from(BOB), - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: stable_asset_1, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }, - ]; + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); + + init_omnipool(); + + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + Omnipool::protocol_account(), + stable_asset_1, + 3000 * UNITS as i128, + )); + + assert_ok!(hydradx_runtime::Omnipool::add_token( + hydradx_runtime::RuntimeOrigin::root(), + stable_asset_1, + FixedU128::from_inner(25_650_000_000_000_000), + Permill::from_percent(1), + AccountId::from(BOB), + )); + + let trades = vec![ + Trade { + pool: PoolType::Omnipool, + asset_in: HDX, + asset_out: stable_asset_1, + }, + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: stable_asset_1, + asset_out: pool_id, + }, + ]; + + assert_balance!(ALICE.into(), pool_id, 0); + + //Act + let amount_to_sell = 100 * UNITS; + assert_ok!(Router::sell( + hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), + HDX, + pool_id, + amount_to_sell, + 0, + trades + )); - assert_balance!(ALICE.into(), pool_id, 0); + //Assert + assert_eq!( + hydradx_runtime::Balances::free_balance(&AccountId::from(ALICE)), + ALICE_INITIAL_NATIVE_BALANCE - amount_to_sell + ); - //Act - let amount_to_sell = 100 * UNITS; - assert_ok!(Router::sell( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - HDX, - pool_id, - amount_to_sell, - 0, - trades - )); + assert_balance!(ALICE.into(), pool_id, 4638992258357); - //Assert - assert_eq!( - hydradx_runtime::Balances::free_balance(&AccountId::from(ALICE)), - ALICE_INITIAL_NATIVE_BALANCE - amount_to_sell - ); - - assert_balance!(ALICE.into(), pool_id, 4638992258357); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -411,57 +429,61 @@ mod router_different_pools_tests { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); - - init_omnipool(); - - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS as i128, - )); - - assert_ok!(hydradx_runtime::Omnipool::add_token( - hydradx_runtime::RuntimeOrigin::root(), - pool_id, - FixedU128::from_inner(25_650_000_000_000_000), - Permill::from_percent(1), - AccountId::from(BOB), - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - - assert_balance!(ALICE.into(), pool_id, 0); - - //Act - let amount_to_sell = 100 * UNITS; + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); + + init_omnipool(); + + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 3000 * UNITS as i128, + )); + + assert_ok!(hydradx_runtime::Omnipool::add_token( + hydradx_runtime::RuntimeOrigin::root(), + pool_id, + FixedU128::from_inner(25_650_000_000_000_000), + Permill::from_percent(1), + AccountId::from(BOB), + )); + + let trades = vec![ + Trade { + pool: PoolType::Omnipool, + asset_in: HDX, + asset_out: pool_id, + }, + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: pool_id, + asset_out: stable_asset_1, + }, + ]; + + assert_balance!(ALICE.into(), pool_id, 0); + + //Act + let amount_to_sell = 100 * UNITS; + + assert_ok!(Router::sell( + hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), + HDX, + stable_asset_1, + amount_to_sell, + 0, + trades + )); - assert_ok!(Router::sell( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - HDX, - stable_asset_1, - amount_to_sell, - 0, - trades - )); + //Assert + assert_balance!(ALICE.into(), pool_id, 0); + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - amount_to_sell); + assert_balance!(ALICE.into(), stable_asset_1, 2899390145403); - //Assert - assert_balance!(ALICE.into(), pool_id, 0); - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE - amount_to_sell); - assert_balance!(ALICE.into(), stable_asset_1, 2899390145403); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -470,56 +492,60 @@ mod router_different_pools_tests { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); - - init_omnipool(); - - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS as i128, - )); - - assert_ok!(hydradx_runtime::Omnipool::add_token( - hydradx_runtime::RuntimeOrigin::root(), - pool_id, - FixedU128::from_inner(25_650_000_000_000_000), - Permill::from_percent(1), - AccountId::from(BOB), - )); - - let trades = vec![ - Trade { - pool: PoolType::Omnipool, - asset_in: HDX, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }, - ]; - - assert_balance!(ALICE.into(), pool_id, 0); - - //Act - let amount_to_buy = UNITS / 1000; + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); + + init_omnipool(); + + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 3000 * UNITS as i128, + )); + + assert_ok!(hydradx_runtime::Omnipool::add_token( + hydradx_runtime::RuntimeOrigin::root(), + pool_id, + FixedU128::from_inner(25_650_000_000_000_000), + Permill::from_percent(1), + AccountId::from(BOB), + )); + + let trades = vec![ + Trade { + pool: PoolType::Omnipool, + asset_in: HDX, + asset_out: pool_id, + }, + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: pool_id, + asset_out: stable_asset_1, + }, + ]; + + assert_balance!(ALICE.into(), pool_id, 0); + + //Act + let amount_to_buy = UNITS / 1000; + + assert_ok!(Router::buy( + hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), + HDX, + stable_asset_1, + amount_to_buy, + u128::MAX, + trades + )); - assert_ok!(Router::buy( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - HDX, - stable_asset_1, - amount_to_buy, - u128::MAX, - trades - )); + //Assert + //assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); + assert_balance!(ALICE.into(), stable_asset_1, amount_to_buy); - //Assert - //assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - assert_balance!(ALICE.into(), stable_asset_1, amount_to_buy); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -528,62 +554,66 @@ mod router_different_pools_tests { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); - - init_omnipool(); - - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - Omnipool::protocol_account(), - pool_id, - 3000 * UNITS as i128, - )); - - assert_ok!(hydradx_runtime::Omnipool::add_token( - hydradx_runtime::RuntimeOrigin::root(), - pool_id, - FixedU128::from_inner(25_650_000_000_000_000), - Permill::from_percent(1), - AccountId::from(BOB), - )); - - let trades = vec![ - Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }, - Trade { - pool: PoolType::Omnipool, - asset_in: pool_id, - asset_out: HDX, - }, - ]; - - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - - //Act - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - 3000 * UNITS as i128, - )); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); + + init_omnipool(); + + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + Omnipool::protocol_account(), + pool_id, + 3000 * UNITS as i128, + )); + + assert_ok!(hydradx_runtime::Omnipool::add_token( + hydradx_runtime::RuntimeOrigin::root(), + pool_id, + FixedU128::from_inner(25_650_000_000_000_000), + Permill::from_percent(1), + AccountId::from(BOB), + )); + + let trades = vec![ + Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: stable_asset_1, + asset_out: pool_id, + }, + Trade { + pool: PoolType::Omnipool, + asset_in: pool_id, + asset_out: HDX, + }, + ]; + + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); + + //Act + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + ALICE.into(), + stable_asset_1, + 3000 * UNITS as i128, + )); + + let amount_to_buy = 100 * UNITS; + + assert_ok!(Router::buy( + hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), + stable_asset_1, + HDX, + amount_to_buy, + u128::MAX, + trades + )); - let amount_to_buy = 100 * UNITS; + //Assert + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_buy); - assert_ok!(Router::buy( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - stable_asset_1, - HDX, - amount_to_buy, - u128::MAX, - trades - )); - - //Assert - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE + amount_to_buy); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -2091,42 +2121,46 @@ mod omnipool_stableswap_router_tests { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); - init_omnipool(); + init_omnipool(); - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - 3000 * UNITS as i128, - )); + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + ALICE.into(), + stable_asset_1, + 3000 * UNITS as i128, + )); - let trades = vec![Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }]; + let trades = vec![Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: stable_asset_1, + asset_out: pool_id, + }]; - assert_balance!(ALICE.into(), pool_id, 0); + assert_balance!(ALICE.into(), pool_id, 0); - //Act - let amount_to_sell = 100 * UNITS; - assert_ok!(Router::sell( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - stable_asset_1, - pool_id, - amount_to_sell, - 0, - trades - )); + //Act + let amount_to_sell = 100 * UNITS; + assert_ok!(Router::sell( + hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), + stable_asset_1, + pool_id, + amount_to_sell, + 0, + trades + )); - //Assert - assert_eq!( - hydradx_runtime::Currencies::free_balance(stable_asset_1, &AccountId::from(ALICE)), - 3000 * UNITS - amount_to_sell - ); + //Assert + assert_eq!( + hydradx_runtime::Currencies::free_balance(stable_asset_1, &AccountId::from(ALICE)), + 3000 * UNITS - amount_to_sell + ); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -2135,35 +2169,39 @@ mod omnipool_stableswap_router_tests { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); - let trades = vec![Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: stable_asset_1, - asset_out: pool_id, - }]; + let trades = vec![Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: stable_asset_1, + asset_out: pool_id, + }]; - assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); + assert_balance!(ALICE.into(), HDX, ALICE_INITIAL_NATIVE_BALANCE); - //Act - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - ALICE.into(), - stable_asset_1, - 3000 * UNITS as i128, - )); + //Act + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + ALICE.into(), + stable_asset_1, + 3000 * UNITS as i128, + )); - let amount_to_buy = 100 * UNITS; + let amount_to_buy = 100 * UNITS; - assert_ok!(Router::buy( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - stable_asset_1, - pool_id, - amount_to_buy, - u128::MAX, - trades - )); + assert_ok!(Router::buy( + hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), + stable_asset_1, + pool_id, + amount_to_buy, + u128::MAX, + trades + )); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } @@ -2172,33 +2210,37 @@ mod omnipool_stableswap_router_tests { TestNet::reset(); Hydra::execute_with(|| { - //Arrange - let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); - - let trades = vec![Trade { - pool: PoolType::Stableswap(pool_id), - asset_in: pool_id, - asset_out: stable_asset_1, - }]; - - //Act - assert_ok!(Currencies::update_balance( - hydradx_runtime::RuntimeOrigin::root(), - ALICE.into(), - pool_id, - 3000 * UNITS as i128, - )); + let _ = with_transaction(|| { + //Arrange + let (pool_id, stable_asset_1, _) = init_stableswap().unwrap(); - let amount_to_buy = 100 * UNITS; + let trades = vec![Trade { + pool: PoolType::Stableswap(pool_id), + asset_in: pool_id, + asset_out: stable_asset_1, + }]; + + //Act + assert_ok!(Currencies::update_balance( + hydradx_runtime::RuntimeOrigin::root(), + ALICE.into(), + pool_id, + 3000 * UNITS as i128, + )); + + let amount_to_buy = 100 * UNITS; + + assert_ok!(Router::buy( + hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), + pool_id, + stable_asset_1, + amount_to_buy, + u128::MAX, + trades + )); - assert_ok!(Router::buy( - hydradx_runtime::RuntimeOrigin::signed(ALICE.into()), - pool_id, - stable_asset_1, - amount_to_buy, - u128::MAX, - trades - )); + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); }); } } diff --git a/math/proptest-regressions/stableswap/tests/invariants.txt b/math/proptest-regressions/stableswap/tests/invariants.txt deleted file mode 100644 index d2755f390..000000000 --- a/math/proptest-regressions/stableswap/tests/invariants.txt +++ /dev/null @@ -1,7 +0,0 @@ -# Seeds for failure cases proptest has generated in the past. It is -# automatically read and these particular cases re-run before any -# novel cases are generated. -# -# It is recommended to check this file in to source control so that -# everyone who runs the test benefits from these saved cases. -cc dfba9d405ba61bbd3bc1917de4383fc12c9b7ad4707420aa05918f7bd2952d8c # shrinks to pool = [AssetReserve { amount: 10000000000, decimals: 6 }, AssetReserve { amount: 160124693000000, decimals: 6 }], amount = 1257, amp = 2 From 7cccc6808051d82e4d4cbcb4cab3b4f3b303c458 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 27 Oct 2023 13:52:29 +0200 Subject: [PATCH 45/93] assert-registry,sufficiencyCheck: fixed PR comments --- .../src/insufficient_assets_ed.rs | 4 +-- pallets/asset-registry/src/lib.rs | 4 +++ runtime/hydradx/src/assets.rs | 26 ++++++++++--------- 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index b484d690a..9eb574d6f 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -422,7 +422,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset } #[test] -fn tx_should_fail_with_keepalive_err_when_dest_account_cant_pay_ed() { +fn tx_should_fail_with_existential_deposit_err_when_dest_account_cant_pay_ed() { TestNet::reset(); Hydra::execute_with(|| { let sht1: AssetId = register_shitcoin(0_u128); @@ -440,7 +440,7 @@ fn tx_should_fail_with_keepalive_err_when_dest_account_cant_pay_ed() { assert_noop!( Tokens::deposit(sht1, &ALICE.into(), 1_000_000 * UNITS), - orml_tokens::Error::::KeepAlive + orml_tokens::Error::::ExistentialDeposit ); }); } diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index b16fedc35..be34a5af6 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -153,6 +153,10 @@ pub mod pallet { /// Balance too low InsufficientBalance, + + //NOTE: This error is triggered from `SufficiencyCheck`. + /// Existential deposit can't be zero. + ZeroExistentialDeposit, } #[pallet::type_value] diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 6be97934a..1cd32b83a 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -42,12 +42,11 @@ use primitives::constants::{ chain::OMNIPOOL_SOURCE, currency::{NATIVE_EXISTENTIAL_DEPOSIT, UNITS}, }; -use sp_runtime::DispatchError; use sp_runtime::{traits::Zero, DispatchResult, FixedPointNumber}; use core::ops::RangeInclusive; use frame_support::{ - parameter_types, + ensure, parameter_types, sp_runtime::app_crypto::sp_core::crypto::UncheckedFrom, sp_runtime::traits::{One, PhantomData}, sp_runtime::{FixedU128, Perbill, Permill}, @@ -137,6 +136,8 @@ impl SufficiencyCheck { /// /// Emits `pallet_asset_registry::Event::ExistentialDepositPaid` when ED was paid. fn on_funds(asset: AssetId, paying_account: &AccountId, to: &AccountId) -> DispatchResult { + //NOTE: To prevent duplicate ED collection we assume account already paid ED + //if it has any amount of `asset`(exists in the storage). if orml_tokens::Accounts::::try_get(to, asset).is_err() && !AssetRegistry::is_sufficient(asset) { let fee_payment_asset = MultiTransactionPayment::account_currency(paying_account); @@ -144,6 +145,12 @@ impl SufficiencyCheck { .ok_or(pallet_transaction_multi_payment::Error::::UnsupportedCurrency)? .saturating_mul_int(InsufficientEDinHDX::get()); + //NOTE: Not tested, this should never happen. + ensure!( + !ed_in_fee_asset.is_zero(), + pallet_asset_registry::Error::::ZeroExistentialDeposit + ); + //NOTE: Account doesn't have enough funds to pay ED if this fail. >::transfer( fee_payment_asset, @@ -151,7 +158,7 @@ impl SufficiencyCheck { &TreasuryAccount::get(), ed_in_fee_asset, ) - .map_err(|_| orml_tokens::Error::::KeepAlive)?; + .map_err(|_| orml_tokens::Error::::ExistentialDeposit)?; let to_lock = pallet_balances::Locks::::get(TreasuryAccount::get()) .iter() @@ -169,12 +176,7 @@ impl SufficiencyCheck { frame_system::Pallet::::inc_sufficients(paying_account); - let _ = pallet_asset_registry::ExistentialDepositCounter::::try_mutate( - |val| -> Result<(), DispatchError> { - *val = val.saturating_add(1); - Ok(()) - }, - ); + pallet_asset_registry::ExistentialDepositCounter::::mutate(|v| *v = v.saturating_add(1)); pallet_asset_registry::Pallet::::deposit_event( pallet_asset_registry::Event::::ExistentialDepositPaid { @@ -221,12 +223,12 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { .unwrap_or_default(); let paid_accounts = pallet_asset_registry::ExistentialDepositCounter::::get(); - let ed_to_pay = if paid_accounts != 0 { + let ed_to_refund = if paid_accounts != 0 { locked_ed.saturating_div(paid_accounts) } else { 0 }; - let to_lock = locked_ed.saturating_sub(ed_to_pay); + let to_lock = locked_ed.saturating_sub(ed_to_refund); if to_lock.is_zero() { let _ = >::remove_lock( @@ -247,7 +249,7 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { NativeAssetId::get(), &TreasuryAccount::get(), who, - ed_to_pay, + ed_to_refund, ); //NOTE: This is necessary because grandfathered accounts doesn't have incremented From 297316146b7a1bf6284b98e1bcdd662e7a70ec13 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 27 Oct 2023 17:03:34 +0200 Subject: [PATCH 46/93] fix benchmarks --- runtime/hydradx/src/benchmarking/duster.rs | 2 +- runtime/hydradx/src/benchmarking/mod.rs | 53 +++++++++++-------- runtime/hydradx/src/benchmarking/omnipool.rs | 30 +++++------ .../src/benchmarking/route_executor.rs | 2 +- 4 files changed, 46 insertions(+), 41 deletions(-) diff --git a/runtime/hydradx/src/benchmarking/duster.rs b/runtime/hydradx/src/benchmarking/duster.rs index c48a60d6c..2a6a8a01c 100644 --- a/runtime/hydradx/src/benchmarking/duster.rs +++ b/runtime/hydradx/src/benchmarking/duster.rs @@ -42,7 +42,7 @@ runtime_benchmarks! { update_balance(asset_id, &to_dust_account, min_deposit); - update_asset(asset_id, b"TST".to_vec(), 110u128).map_err(|_| BenchmarkError::Stop("Failed to update asset"))?; + update_asset(asset_id, None, 110u128).map_err(|_| BenchmarkError::Stop("Failed to update asset"))?; assert_eq!(Tokens::free_balance(asset_id, &to_dust_account), dust_amount); let current_balance = Tokens::free_balance(asset_id, &dest_account.clone().unwrap()); diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index 7927c2b75..306a45c54 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -19,34 +19,41 @@ use sp_std::vec::Vec; pub const BSX: Balance = primitives::constants::currency::UNITS; +use frame_support::storage::with_transaction; +use sp_runtime::TransactionOutcome; + pub fn register_asset(name: Vec, deposit: Balance) -> Result { - AssetRegistry::register_insufficient_asset( - None, - Some(&name), - AssetKind::Token, - Some(deposit), - None, - None, - None, - None, - ) + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + None, + Some(&name), + AssetKind::Token, + Some(deposit), + None, + None, + None, + None, + )) + }) .map_err(|_| ()) } #[allow(dead_code)] -pub fn update_asset(asset_id: AssetId, name: Vec, deposit: Balance) -> Result<(), ()> { - AssetRegistry::update( - RawOrigin::Root.into(), - asset_id, - Some(name), - None, - Some(deposit), - None, - None, - None, - None, - None, - ) +pub fn update_asset(asset_id: AssetId, name: Option>, deposit: Balance) -> Result<(), ()> { + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::update( + RawOrigin::Root.into(), + asset_id, + name, + None, + Some(deposit), + None, + None, + None, + None, + None, + )) + }) .map_err(|_| ()) } diff --git a/runtime/hydradx/src/benchmarking/omnipool.rs b/runtime/hydradx/src/benchmarking/omnipool.rs index bffd4019d..d1c8290e3 100644 --- a/runtime/hydradx/src/benchmarking/omnipool.rs +++ b/runtime/hydradx/src/benchmarking/omnipool.rs @@ -1,8 +1,9 @@ -use crate::{AccountId, AssetId, AssetRegistry, Balance, EmaOracle, Omnipool, Runtime, RuntimeOrigin, System}; +use crate::{AccountId, AssetId, Balance, EmaOracle, Omnipool, Runtime, RuntimeOrigin, System}; use super::*; use frame_benchmarking::account; +use frame_benchmarking::BenchmarkError; use frame_support::{ assert_ok, sp_runtime::{ @@ -12,10 +13,7 @@ use frame_support::{ traits::{OnFinalize, OnInitialize}, }; use frame_system::RawOrigin; -use hydradx_traits::{ - router::{PoolType, TradeExecution}, - Registry, -}; +use hydradx_traits::router::{PoolType, TradeExecution}; use orml_benchmarking::runtime_benchmarks; use orml_traits::{MultiCurrency, MultiCurrencyExtended}; use pallet_omnipool::types::Tradability; @@ -89,7 +87,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), Balance::one())?; + let token_id = register_asset(b"FCK".to_vec(), Balance::one()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -126,7 +124,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; //Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), Balance::one())?; + let token_id = register_asset(b"FCK".to_vec(), Balance::one()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -172,7 +170,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1u128)?; + let token_id = register_asset(b"FCK".to_vec(), 1_u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -230,7 +228,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1u128)?; + let token_id = register_asset(b"FCK".to_vec(), 1_u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -288,7 +286,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1_u128)?; + let token_id = register_asset(b"FCK".to_vec(), 1_u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -354,7 +352,7 @@ runtime_benchmarks! { refund_refused_asset { let recipient: AccountId = account("recipient", 3, 1); - let asset_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1_u128)?; + let asset_id = register_asset(b"FCK".to_vec(), 1_u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; let amount = 1_000_000_000_000_000_u128; update_balance(asset_id, &Omnipool::protocol_account(), amount); @@ -383,7 +381,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price, Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), Balance::one())?; + let token_id = register_asset(b"FCK".to_vec(), Balance::one()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -458,7 +456,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1u128)?; + let token_id = register_asset(b"FCK".to_vec(), 1_u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -528,7 +526,7 @@ runtime_benchmarks! { Omnipool::initialize_pool(RawOrigin::Root.into(), stable_price, native_price,Permill::from_percent(100), Permill::from_percent(100))?; // Register new asset in asset registry - let token_id = AssetRegistry::create_asset(&b"FCK".to_vec(), 1_u128)?; + let token_id = register_asset(b"FCK".to_vec(), 1_u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; // Create account for token provider and set balance let owner: AccountId = account("owner", 0, 1); @@ -590,8 +588,8 @@ mod tests { pallet_asset_registry::GenesisConfig:: { registered_assets: vec![ - (Some(1), Some(b"LRNA".to_vec()), 1_000u128, None, None, None, false), - (Some(2), Some(b"DAI".to_vec()), 1_000u128, None, None, None, false), + (Some(1), Some(b"LRNA".to_vec()), 1_000u128, None, None, None, true), + (Some(2), Some(b"DAI".to_vec()), 1_000u128, None, None, None, true), ], native_asset_name: b"HDX".to_vec(), native_existential_deposit: NativeExistentialDeposit::get(), diff --git a/runtime/hydradx/src/benchmarking/route_executor.rs b/runtime/hydradx/src/benchmarking/route_executor.rs index e432e0a9a..89aeaff02 100644 --- a/runtime/hydradx/src/benchmarking/route_executor.rs +++ b/runtime/hydradx/src/benchmarking/route_executor.rs @@ -184,7 +184,7 @@ mod tests { pallet_asset_registry::GenesisConfig:: { registered_assets: vec![ - (None, Some(b"LRNA".to_vec()), 1_000u128, None, None, None, true), + (Some(1), Some(b"LRNA".to_vec()), 1_000u128, None, None, None, true), (None, Some(b"DAI".to_vec()), 1_000u128, None, None, None, true), ], native_asset_name: b"HDX".to_vec(), From e483825df6e6e9109e351bfe5534c12a78718bca Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 31 Oct 2023 16:14:48 +0100 Subject: [PATCH 47/93] pallet-xyk: fixed benchmakrks --- pallets/xyk/src/benchmarking.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pallets/xyk/src/benchmarking.rs b/pallets/xyk/src/benchmarking.rs index 6b6acc765..122ddfea3 100644 --- a/pallets/xyk/src/benchmarking.rs +++ b/pallets/xyk/src/benchmarking.rs @@ -32,6 +32,9 @@ const SEED: u32 = 1; fn funded_account(name: &'static str, index: u32) -> T::AccountId { let caller: T::AccountId = account(name, index, SEED); + //Necessary for ED for insufficien assets. + T::Currency::update_balance(0, &caller, 1_000_000_000_000_000).unwrap(); + T::Currency::update_balance(1, &caller, 1_000_000_000_000_000).unwrap(); T::Currency::update_balance(2, &caller, 1_000_000_000_000_000).unwrap(); caller From 91d0fb758ed95577c973b7ac8172d77a9544139f Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 31 Oct 2023 17:04:05 +0100 Subject: [PATCH 48/93] router-executor: fixed benchmarks --- runtime/hydradx/src/benchmarking/route_executor.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime/hydradx/src/benchmarking/route_executor.rs b/runtime/hydradx/src/benchmarking/route_executor.rs index 89aeaff02..a4e3e1cde 100644 --- a/runtime/hydradx/src/benchmarking/route_executor.rs +++ b/runtime/hydradx/src/benchmarking/route_executor.rs @@ -18,6 +18,7 @@ use crate::{AccountId, AssetId, Balance, Currencies, Router, Runtime, System, LBP}; +use crate::InsufficientEDinHDX; use frame_benchmarking::account; use frame_support::dispatch::DispatchResult; use frame_support::{assert_ok, ensure}; @@ -128,7 +129,7 @@ runtime_benchmarks! { assert_eq!(>::free_balance( asset_in, &seller, - ), INITIAL_BALANCE - amount_to_sell); + ), INITIAL_BALANCE - amount_to_sell - InsufficientEDinHDX::get()); } } From 354768a753e0f88e666200c7b0a8ca559c009e94 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 8 Nov 2023 13:57:40 +0100 Subject: [PATCH 49/93] asset-registry: implemented new Registry traits --- Cargo.lock | 2 +- pallets/asset-registry/src/lib.rs | 137 ++--- .../asset-registry/src/tests/create_trait.rs | 527 ++++++++++++++++++ .../asset-registry/src/tests/inspect_trait.rs | 133 +++++ pallets/asset-registry/src/tests/mod.rs | 3 + .../asset-registry/src/tests/mutate_trait.rs | 85 +++ pallets/lbp/src/types.rs | 67 +++ traits/Cargo.toml | 2 +- traits/src/registry.rs | 86 ++- 9 files changed, 954 insertions(+), 88 deletions(-) create mode 100644 pallets/asset-registry/src/tests/create_trait.rs create mode 100644 pallets/asset-registry/src/tests/inspect_trait.rs create mode 100644 pallets/asset-registry/src/tests/mutate_trait.rs create mode 100644 pallets/lbp/src/types.rs diff --git a/Cargo.lock b/Cargo.lock index 53eed1662..4e14fe8cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3937,7 +3937,7 @@ dependencies = [ [[package]] name = "hydradx-traits" -version = "2.7.0" +version = "3.0.0" dependencies = [ "frame-support", "impl-trait-for-tuples", diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index be34a5af6..794a0242e 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -47,7 +47,7 @@ use frame_support::storage::with_transaction; use frame_support::BoundedVec; use hydradx_traits::{ registry::{Create, Inspect, Mutate}, - AssetKind, CreateRegistry, Registry, ShareTokenRegistry, + AssetKind, }; use sp_runtime::TransactionOutcome; @@ -139,21 +139,25 @@ pub mod pallet { /// Incorrect number of assets provided to create shared asset. InvalidSharedAssetLen, - /// Cannot update asset location + /// Cannot update asset location. CannotUpdateLocation, /// Selected asset id is out of reserved range. NotInReservedRange, - /// Location already registered with different asset + /// Location already registered with different asset. LocationAlreadyRegistered, - /// Origin is forbidden to set/update value + /// Origin is forbidden to set/update value. Forbidden, - /// Balance too low + /// Balance too low. InsufficientBalance, + //NOTE: This error should be never triggered. + /// Provided asset name is not valid. + InvalidAssetname, + //NOTE: This error is triggered from `SufficiencyCheck`. /// Existential deposit can't be zero. ZeroExistentialDeposit, @@ -618,53 +622,6 @@ impl Pallet { } } -impl Registry, Balance, DispatchError> for Pallet { - fn exists(asset_id: T::AssetId) -> bool { - Assets::::contains_key(asset_id) - } - - fn retrieve_asset(name: &Vec) -> Result { - //NOTE: This unwrap is safe. - let bounded_name = Self::try_into_bounded(Some(name.clone()))?.unwrap(); - if let Some(asset_id) = AssetIds::::get(bounded_name) { - Ok(asset_id) - } else { - Err(Error::::AssetNotFound.into()) - } - } - - fn retrieve_asset_type(asset_id: T::AssetId) -> Result { - let asset_details = - Assets::::get(asset_id).ok_or_else(|| Into::::into(Error::::AssetNotFound))?; - Ok(asset_details.asset_type.into()) - } - - fn create_asset(name: &Vec, existential_deposit: Balance) -> Result { - Self::get_or_create_asset(name.clone(), AssetType::Token, existential_deposit, None, false) - } -} - -impl ShareTokenRegistry, Balance, DispatchError> for Pallet { - fn retrieve_shared_asset(name: &Vec, _assets: &[T::AssetId]) -> Result { - Self::retrieve_asset(name) - } - - fn create_shared_asset( - name: &Vec, - assets: &[T::AssetId], - existential_deposit: Balance, - ) -> Result { - ensure!(assets.len() == 2, Error::::InvalidSharedAssetLen); - Self::get_or_create_asset( - name.clone(), - AssetType::PoolShare(assets[0], assets[1]), - existential_deposit, - None, - false, - ) - } -} - use orml_traits::GetByKey; // Return Existential deposit of an asset @@ -689,22 +646,7 @@ impl GetByKey> for XcmRateLimitsInRegistr } } -impl CreateRegistry for Pallet { - type Error = DispatchError; - - fn create_asset(name: &[u8], kind: AssetKind, existential_deposit: Balance) -> Result { - let bounded_name = Self::try_into_bounded(Some(name.to_vec()))?; - - Pallet::::do_register_asset( - None, - &AssetDetails::new(bounded_name, kind.into(), existential_deposit, None, None, None, false), - None, - ) - } -} - impl Inspect for Pallet { - type Error = DispatchError; type AssetId = T::AssetId; fn is_sufficient(id: Self::AssetId) -> bool { @@ -713,15 +655,33 @@ impl Inspect for Pallet { None => false, } } + + fn exists(id: Self::AssetId) -> bool { + Assets::::try_get(id).is_ok() + } + + fn decimals(id: Self::AssetId) -> Option { + Self::assets(id).map_or(None, |a| a.decimals) + } + + fn asset_type(id: Self::AssetId) -> Option { + Self::assets(id).map_or(None, |a| Some(a.asset_type.into())) + } } -impl Mutate for Pallet { +impl Mutate for Pallet { + type Error = DispatchError; + fn set_location(asset_id: Self::AssetId, location: T::AssetNativeLocation) -> Result<(), Self::Error> { + ensure!(Self::exists(asset_id), Error::::AssetNotFound); + Self::do_set_location(asset_id, location) } } impl Create for Pallet { + type Error = DispatchError; + fn register_asset( asset_id: Option, name: Option<&[u8]>, @@ -748,15 +708,40 @@ impl Create for Pallet { Self::do_register_asset(asset_id, &details, location) } -} -use hydradx_traits::InspectRegistry; -impl InspectRegistry for Pallet { - fn exists(asset_id: T::AssetId) -> bool { - Assets::::contains_key(asset_id) - } + fn get_or_register_asset( + name: &[u8], + kind: AssetKind, + existential_deposit: Option, + symbol: Option<&[u8]>, + decimals: Option, + location: Option, + xcm_rate_limit: Option, + is_sufficient: bool, + ) -> Result { + //NOTE: in this case `try_into_bounded()` should never return None. + let bounded_name = match Self::try_into_bounded(Some(name.to_vec()))? { + Some(n) => n, + None => return Err(Error::::InvalidAssetname.into()), + }; + + match Self::asset_ids(bounded_name.clone()) { + Some(id) => Ok(id), + None => { + let bounded_symbol = Self::try_into_bounded(symbol.map(|x| x.to_vec()))?; + + let details = AssetDetails::new( + Some(bounded_name), + kind.into(), + existential_deposit.unwrap_or(DEFAULT_ED), + bounded_symbol, + decimals, + xcm_rate_limit, + is_sufficient, + ); - fn decimals(asset_id: T::AssetId) -> Option { - Assets::::get(asset_id)?.decimals + Self::do_register_asset(None, &details, location) + } + } } } diff --git a/pallets/asset-registry/src/tests/create_trait.rs b/pallets/asset-registry/src/tests/create_trait.rs new file mode 100644 index 000000000..507c8724e --- /dev/null +++ b/pallets/asset-registry/src/tests/create_trait.rs @@ -0,0 +1,527 @@ +use super::*; + +use hydradx_traits::registry::Create; +use mock::Registry; + +use frame_support::storage::with_transaction; +use polkadot_xcm::v3::{ + Junction::{self, Parachain}, + Junctions::X2, + MultiLocation, +}; +use sp_runtime::{DispatchResult, TransactionOutcome}; + +#[test] +fn register_asset_should_work() { + ExtBuilder::default().build().execute_with(|| { + let _ = with_transaction(|| { + let asset_id = 1; + let name = b"Test asset".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!(>::register_asset( + Some(asset_id), + Some(&name.clone()), + AssetKind::XYK, + Some(ed), + Some(&symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + )); + + //Assert + let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); + let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); + assert_eq!( + Registry::assets(asset_id), + Some(AssetDetails { + name: bounded_name.clone(), + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol.clone(), + decimals: Some(decimals), + is_sufficient + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(asset_id)); + + assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id, + asset_name: bounded_name, + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol, + decimals: Some(decimals), + is_sufficient + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id, + location: asset_location + } + .into() + )); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} + +#[test] +fn register_insufficient_asset_should_work() { + ExtBuilder::default().build().execute_with(|| { + let _ = with_transaction(|| { + let asset_id = 1; + let name = b"Test asset".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!( + >::register_insufficient_asset( + Some(asset_id), + Some(&name.clone()), + AssetKind::XYK, + Some(ed), + Some(&symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + ) + ); + + //Assert + let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); + let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); + assert_eq!( + Registry::assets(asset_id), + Some(AssetDetails { + name: bounded_name.clone(), + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol.clone(), + decimals: Some(decimals), + is_sufficient: false + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(asset_id)); + + assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id, + asset_name: bounded_name, + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol, + decimals: Some(decimals), + is_sufficient: false + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id, + location: asset_location + } + .into() + )); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} + +#[test] +fn register_sufficient_asset_should_work() { + ExtBuilder::default().build().execute_with(|| { + let _ = with_transaction(|| { + let asset_id = 1; + let name = b"Test asset".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!(>::register_sufficient_asset( + Some(asset_id), + Some(&name.clone()), + AssetKind::XYK, + ed, + Some(&symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + )); + + //Assert + let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); + let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); + assert_eq!( + Registry::assets(asset_id), + Some(AssetDetails { + name: bounded_name.clone(), + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol.clone(), + decimals: Some(decimals), + is_sufficient: true + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(asset_id)); + + assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id, + asset_name: bounded_name, + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol, + decimals: Some(decimals), + is_sufficient: true + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id, + location: asset_location + } + .into() + )); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} + +#[test] +fn get_or_register_asset_should_register_asset_when_does_not_exists() { + ExtBuilder::default().build().execute_with(|| { + let _ = with_transaction(|| { + let new_asset_id = Registry::next_asset_id().unwrap(); + let name = b"Test asset".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; + + let key = Junction::from(BoundedVec::try_from(new_asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!( + >::get_or_register_asset( + &name.clone(), + AssetKind::XYK, + Some(ed), + Some(&symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + new_asset_id + ); + + //Assert + let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); + let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); + assert_eq!( + Registry::assets(new_asset_id), + Some(AssetDetails { + name: bounded_name.clone(), + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol.clone(), + decimals: Some(decimals), + is_sufficient + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(new_asset_id)); + + assert_eq!(Registry::location_assets(asset_location.clone()), Some(new_asset_id)); + assert_eq!(Registry::locations(new_asset_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id: new_asset_id, + asset_name: bounded_name, + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol, + decimals: Some(decimals), + is_sufficient + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id: new_asset_id, + location: asset_location + } + .into() + )); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} + +#[test] +fn get_or_register_asset_should_return_asset_id_when_asset_exists() { + let existing_asset_id = 1_u32; + ExtBuilder::default() + .with_assets(vec![( + Some(existing_asset_id), + Some(b"Asset".to_vec()), + UNIT, + None, + None, + None, + false, + )]) + .build() + .execute_with(|| { + let _ = with_transaction(|| { + let name = b"Asset".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; + + let key = Junction::from(BoundedVec::try_from(1_000.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!( + >::get_or_register_asset( + &name.clone(), + AssetKind::XYK, + Some(ed), + Some(&symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + existing_asset_id + ); + + //Assert + let bounded_name = Pallet::::try_into_bounded(Some(b"Asset".to_vec())).unwrap(); + assert_eq!( + Registry::assets(existing_asset_id), + Some(AssetDetails { + name: bounded_name.clone(), + asset_type: AssetType::Token, + existential_deposit: UNIT, + xcm_rate_limit: None, + symbol: None, + decimals: None, + is_sufficient: false + }) + ); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} + +#[test] +fn get_or_register_sufficient_asset_should_work() { + ExtBuilder::default().build().execute_with(|| { + let _ = with_transaction(|| { + let new_asset_id = Registry::next_asset_id().unwrap(); + let name = b"Test asset".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + + let key = Junction::from(BoundedVec::try_from(new_asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!( + >::get_or_register_sufficient_asset( + &name.clone(), + AssetKind::XYK, + ed, + Some(&symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + ), + ); + + //Assert + let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); + let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); + assert_eq!( + Registry::assets(new_asset_id), + Some(AssetDetails { + name: bounded_name.clone(), + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol.clone(), + decimals: Some(decimals), + is_sufficient: true + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(new_asset_id)); + + assert_eq!(Registry::location_assets(asset_location.clone()), Some(new_asset_id)); + assert_eq!(Registry::locations(new_asset_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id: new_asset_id, + asset_name: bounded_name, + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol, + decimals: Some(decimals), + is_sufficient: true + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id: new_asset_id, + location: asset_location + } + .into() + )); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} + +#[test] +fn get_or_register_insufficient_asset_should_work() { + ExtBuilder::default().build().execute_with(|| { + let _ = with_transaction(|| { + let new_asset_id = Registry::next_asset_id().unwrap(); + let name = b"Test asset".to_vec(); + let symbol = b"TKN".to_vec(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + + let key = Junction::from(BoundedVec::try_from(new_asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_ok!( + >::get_or_register_insufficient_asset( + &name.clone(), + AssetKind::XYK, + Some(ed), + Some(&symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + ), + ); + + //Assert + let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); + let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); + assert_eq!( + Registry::assets(new_asset_id), + Some(AssetDetails { + name: bounded_name.clone(), + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol.clone(), + decimals: Some(decimals), + is_sufficient: false + }) + ); + + assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(new_asset_id)); + + assert_eq!(Registry::location_assets(asset_location.clone()), Some(new_asset_id)); + assert_eq!(Registry::locations(new_asset_id), Some(asset_location.clone())); + + assert!(has_event( + Event::::Registered { + asset_id: new_asset_id, + asset_name: bounded_name, + asset_type: AssetType::XYK, + existential_deposit: ed, + xcm_rate_limit: Some(xcm_rate_limit), + symbol: bounded_symbol, + decimals: Some(decimals), + is_sufficient: false + } + .into() + )); + + assert!(has_event( + Event::::LocationSet { + asset_id: new_asset_id, + location: asset_location + } + .into() + )); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} diff --git a/pallets/asset-registry/src/tests/inspect_trait.rs b/pallets/asset-registry/src/tests/inspect_trait.rs new file mode 100644 index 000000000..82f5b1422 --- /dev/null +++ b/pallets/asset-registry/src/tests/inspect_trait.rs @@ -0,0 +1,133 @@ +use super::*; + +use frame_support::storage::with_transaction; +use hydradx_traits::registry::{AssetKind, Inspect}; +use mock::Registry; + +use pretty_assertions::assert_eq; +use sp_runtime::{DispatchResult, TransactionOutcome}; + +#[test] +fn is_sufficient_should_work() { + let suff_asset_id = 1_u32; + let insuff_asset_id = 2_u32; + let non_existing_id = 3_u32; + + ExtBuilder::default() + .with_assets(vec![ + ( + Some(suff_asset_id), + Some(b"Suff".to_vec()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(insuff_asset_id), + Some(b"Insuff".to_vec()), + UNIT, + None, + None, + None, + false, + ), + ]) + .build() + .execute_with(|| { + assert_eq!(::is_sufficient(suff_asset_id), true); + + assert_eq!(::is_sufficient(insuff_asset_id), false); + + assert_eq!(::is_sufficient(non_existing_id), false); + }); +} + +#[test] +fn exists_should_work() { + let asset_id = 2_u32; + let non_existing_id = 3_u32; + + ExtBuilder::default() + .with_assets(vec![( + Some(asset_id), + Some(b"Suff".to_vec()), + UNIT, + None, + None, + None, + true, + )]) + .build() + .execute_with(|| { + assert_eq!(::exists(asset_id), true); + + assert_eq!(::exists(non_existing_id), false); + }); +} + +#[test] +fn decimals_should_work() { + let non_existing_id = 543_u32; + + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"TKN1".to_vec()), UNIT, None, Some(5_u8), None, true), + (Some(2), Some(b"TKN2".to_vec()), UNIT, None, Some(0_u8), None, true), + (Some(3), Some(b"TKN3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + assert_eq!(::decimals(1), Some(5)); + + assert_eq!(::decimals(2), Some(0)); + + assert_eq!(::decimals(3), None); + + assert_eq!(::decimals(non_existing_id), None); + }); +} + +#[test] +fn asset_type_should_work() { + let non_existing_id = 543_u32; + + ExtBuilder::default().build().execute_with(|| { + let _ = with_transaction(|| { + //Arrange + let token_type_id = + Registry::register_insufficient_asset(None, None, AssetKind::Token, None, None, None, None, None) + .unwrap(); + let xyk_type_id = + Registry::register_insufficient_asset(None, None, AssetKind::XYK, None, None, None, None, None) + .unwrap(); + let stableswap_type_id = + Registry::register_insufficient_asset(None, None, AssetKind::StableSwap, None, None, None, None, None) + .unwrap(); + let bond_type_id = + Registry::register_insufficient_asset(None, None, AssetKind::Bond, None, None, None, None, None) + .unwrap(); + let external_type_id = + Registry::register_insufficient_asset(None, None, AssetKind::External, None, None, None, None, None) + .unwrap(); + + //Assert + assert_eq!(::asset_type(token_type_id), Some(AssetKind::Token)); + assert_eq!(::asset_type(xyk_type_id), Some(AssetKind::XYK)); + assert_eq!( + ::asset_type(stableswap_type_id), + Some(AssetKind::StableSwap) + ); + assert_eq!(::asset_type(bond_type_id), Some(AssetKind::Bond)); + assert_eq!( + ::asset_type(external_type_id), + Some(AssetKind::External) + ); + + assert_eq!(::asset_type(non_existing_id), None); + + TransactionOutcome::Commit(DispatchResult::Ok(())) + }); + }); +} diff --git a/pallets/asset-registry/src/tests/mod.rs b/pallets/asset-registry/src/tests/mod.rs index f85c48bcb..16d7c4489 100644 --- a/pallets/asset-registry/src/tests/mod.rs +++ b/pallets/asset-registry/src/tests/mod.rs @@ -3,7 +3,10 @@ use mock::*; use crate::*; use frame_support::{assert_noop, assert_ok}; +mod create_trait; +mod inspect_trait; pub(crate) mod mock; +mod mutate_trait; mod register; mod update; diff --git a/pallets/asset-registry/src/tests/mutate_trait.rs b/pallets/asset-registry/src/tests/mutate_trait.rs new file mode 100644 index 000000000..b84c16b51 --- /dev/null +++ b/pallets/asset-registry/src/tests/mutate_trait.rs @@ -0,0 +1,85 @@ +use super::*; + +use hydradx_traits::registry::Mutate; +use mock::Registry; + +use polkadot_xcm::v3::{ + Junction::{self, Parachain}, + Junctions::X2, + MultiLocation, +}; + +#[test] +fn set_location_should_work_when_location_was_not_set_yet() { + let asset_id = 1_u32; + ExtBuilder::default() + .with_assets(vec![( + Some(asset_id), + Some(b"Suff".to_vec()), + UNIT, + None, + None, + None, + true, + )]) + .build() + .execute_with(|| { + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + assert_eq!(Registry::locations(asset_id), None); + + //Act + assert_ok!(>::set_location( + asset_id, + location.clone() + )); + + //Assert + assert_eq!(Registry::location_assets(location.clone()), Some(asset_id)); + assert_eq!(Registry::locations(asset_id), Some(location)); + }); +} + +#[test] +fn set_location_should_not_work_when_location_was_not() { + let asset_id = 1_u32; + ExtBuilder::default() + .with_assets(vec![( + Some(asset_id), + Some(b"Suff".to_vec()), + UNIT, + None, + None, + None, + true, + )]) + .build() + .execute_with(|| { + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::set_location(asset_id, location.clone()).unwrap(); + + //Act + assert_noop!( + >::set_location(asset_id, location), + Error::::LocationAlreadyRegistered + ); + }); +} + +#[test] +fn set_location_should_not_work_when_asset_does_not_exists() { + let non_existing_id = 190_u32; + ExtBuilder::default().build().execute_with(|| { + //Arrange + let key = Junction::from(BoundedVec::try_from(non_existing_id.encode()).unwrap()); + let location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_noop!( + >::set_location(non_existing_id, location), + Error::::AssetNotFound + ); + }); +} diff --git a/pallets/lbp/src/types.rs b/pallets/lbp/src/types.rs new file mode 100644 index 000000000..fbf9eaa58 --- /dev/null +++ b/pallets/lbp/src/types.rs @@ -0,0 +1,67 @@ +// This file is part of Basilisk-node. + +// Copyright (C) 2020-2022 Intergalactic, Limited (GIB). +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub type AssetId = u32; +pub type Balance = u128; +pub type Amount = i128; + +use codec::{Decode, Encode}; +use scale_info::TypeInfo; +use sp_std::vec::Vec; + +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; + +/// Asset Pair representation for AMM trades +/// ( asset_a, asset_b ) combination where asset_a is meant to be exchanged for asset_b +/// +/// asset_in represents asset coming into the pool +/// asset_out represents asset coming out of the pool +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +#[derive(Debug, Encode, Decode, Copy, Clone, PartialEq, Eq, Default, TypeInfo)] +pub struct AssetPair { + pub asset_in: AssetId, + pub asset_out: AssetId, +} + +impl AssetPair { + pub fn new(asset_in: AssetId, asset_out: AssetId) -> Self { + Self { asset_in, asset_out } + } + + /// Return ordered asset tuple (A,B) where A < B + /// Used in storage + pub fn ordered_pair(&self) -> (AssetId, AssetId) { + match self.asset_in <= self.asset_out { + true => (self.asset_in, self.asset_out), + false => (self.asset_out, self.asset_in), + } + } + + /// Return share token name + pub fn name(&self) -> Vec { + let mut buf: Vec = Vec::new(); + + let (asset_a, asset_b) = self.ordered_pair(); + + buf.extend_from_slice(&asset_a.to_le_bytes()); + buf.extend_from_slice(b"HDT"); + buf.extend_from_slice(&asset_b.to_le_bytes()); + + buf + } +} diff --git a/traits/Cargo.toml b/traits/Cargo.toml index 8a236ed39..a1797f0b0 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-traits" -version = "2.7.0" +version = "3.0.0" description = "Shared traits" authors = ["GalacticCouncil"] edition = "2021" diff --git a/traits/src/registry.rs b/traits/src/registry.rs index d4f4eb1b9..7e400756c 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -1,5 +1,6 @@ use sp_std::vec::Vec; +#[deprecated(since = "3.0.0", note = "Please use `registry::Create` trait instead")] pub trait Registry { fn exists(name: AssetId) -> bool; @@ -19,6 +20,7 @@ pub trait Registry { } // Use CreateRegistry if possible +#[deprecated(since = "3.0.0", note = "Please use `registry::Create` trait instead")] pub trait ShareTokenRegistry: Registry { fn retrieve_shared_asset(name: &AssetName, assets: &[AssetId]) -> Result; @@ -41,12 +43,13 @@ pub trait ShareTokenRegistry: Registry { fn exists(asset_id: AssetId) -> bool; fn decimals(asset_id: AssetId) -> Option; } -#[derive(Eq, PartialEq, Copy, Clone)] +#[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum AssetKind { Token, XYK, @@ -55,6 +58,7 @@ pub enum AssetKind { External, } +#[deprecated(since = "3.0.0", note = "Please use `registry::Create` trait instead")] pub trait CreateRegistry { type Error; fn create_asset(name: &[u8], kind: AssetKind, existential_deposit: Balance) -> Result; @@ -81,14 +85,21 @@ pub trait AccountIdFor { use frame_support::dispatch::Parameter; pub trait Inspect { - type Error; type AssetId: Parameter; fn is_sufficient(id: Self::AssetId) -> bool; + + fn exists(id: Self::AssetId) -> bool; + + fn decimals(id: Self::AssetId) -> Option; + + fn asset_type(id: Self::AssetId) -> Option; } #[allow(clippy::too_many_arguments)] -pub trait Create: Inspect { +pub trait Create: Inspect { + type Error; + fn register_asset( asset_id: Option, name: Option<&[u8]>, @@ -96,7 +107,7 @@ pub trait Create: Inspect { existential_deposit: Option, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, is_sufficient: bool, ) -> Result; @@ -108,7 +119,7 @@ pub trait Create: Inspect { existential_deposit: Option, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, ) -> Result { Self::register_asset( @@ -128,17 +139,49 @@ pub trait Create: Inspect { asset_id: Option, name: Option<&[u8]>, kind: AssetKind, - existential_deposit: Option, + existential_deposit: Balance, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, ) -> Result { Self::register_asset( asset_id, name, kind, - existential_deposit, + Some(existential_deposit), + symbol, + decimals, + location, + xcm_rate_limit, + true, + ) + } + + fn get_or_register_asset( + name: &[u8], + kind: AssetKind, + existential_deposit: Option, + symbol: Option<&[u8]>, + decimals: Option, + location: Option, + xcm_rate_limit: Option, + is_sufficient: bool, + ) -> Result; + + fn get_or_register_sufficient_asset( + name: &[u8], + kind: AssetKind, + existential_deposit: Balance, + symbol: Option<&[u8]>, + decimals: Option, + location: Option, + xcm_rate_limit: Option, + ) -> Result { + Self::get_or_register_asset( + name, + kind, + Some(existential_deposit), symbol, decimals, location, @@ -146,9 +189,32 @@ pub trait Create: Inspect { true, ) } + + fn get_or_register_insufficient_asset( + name: &[u8], + kind: AssetKind, + existential_deposit: Option, + symbol: Option<&[u8]>, + decimals: Option, + location: Option, + xcm_rate_limit: Option, + ) -> Result { + Self::get_or_register_asset( + name, + kind, + existential_deposit, + symbol, + decimals, + location, + xcm_rate_limit, + false, + ) + } } -pub trait Mutate: Inspect { +pub trait Mutate: Inspect { + type Error; + /// Set location for existing asset id if it wasn't set yet. - fn set_location(asset_id: Self::AssetId, location: AssetNativeLocation) -> Result<(), Self::Error>; + fn set_location(asset_id: Self::AssetId, location: Location) -> Result<(), Self::Error>; } From 928b5e4b6fca9701c5e5f2a9fa7cf8e1ea5e2e26 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 8 Nov 2023 16:08:37 +0100 Subject: [PATCH 50/93] pallet-xyk: refactor to use new Registry traits --- Cargo.lock | 2 +- pallets/asset-registry/src/lib.rs | 2 +- pallets/asset-registry/src/types.rs | 1 + pallets/xyk/Cargo.toml | 2 +- pallets/xyk/src/lib.rs | 22 ++++++++++++++++------ pallets/xyk/src/tests/creation.rs | 17 +++++++++++------ pallets/xyk/src/tests/mock.rs | 5 ++++- 7 files changed, 35 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4e14fe8cd..d640b85a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7781,7 +7781,7 @@ dependencies = [ [[package]] name = "pallet-xyk" -version = "6.3.0" +version = "6.4.0" dependencies = [ "frame-benchmarking", "frame-support", diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 794a0242e..bcd053426 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -508,7 +508,7 @@ impl Pallet { } /// Convert Vec to BoundedVec so it respects the max set limit, otherwise return TooLong error - fn try_into_bounded(name: Option>) -> Result>, Error> { + pub fn try_into_bounded(name: Option>) -> Result>, Error> { if let Some(name) = name { TryInto::>::try_into(name) .map_err(|_| Error::::TooLong) diff --git a/pallets/asset-registry/src/types.rs b/pallets/asset-registry/src/types.rs index 606722b89..63e191e7f 100644 --- a/pallets/asset-registry/src/types.rs +++ b/pallets/asset-registry/src/types.rs @@ -28,6 +28,7 @@ use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub enum AssetType { Token, + #[deprecated] PoolShare(AssetId, AssetId), // Use XYX instead XYK, StableSwap, diff --git a/pallets/xyk/Cargo.toml b/pallets/xyk/Cargo.toml index 0bb2fac5d..32aa28c38 100644 --- a/pallets/xyk/Cargo.toml +++ b/pallets/xyk/Cargo.toml @@ -1,6 +1,6 @@ [package] name = 'pallet-xyk' -version = "6.3.0" +version = "6.4.0" description = 'XYK automated market maker' authors = ['GalacticCouncil'] edition = '2021' diff --git a/pallets/xyk/src/lib.rs b/pallets/xyk/src/lib.rs index a53812719..cdb521410 100644 --- a/pallets/xyk/src/lib.rs +++ b/pallets/xyk/src/lib.rs @@ -64,7 +64,10 @@ pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::OriginFor; - use hydradx_traits::{pools::DustRemovalAccountWhitelist, registry::ShareTokenRegistry}; + use hydradx_traits::{ + pools::DustRemovalAccountWhitelist, + registry::{AssetKind, Create}, + }; #[pallet::pallet] pub struct Pallet(_); @@ -77,7 +80,7 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Registry support - type AssetRegistry: ShareTokenRegistry, Balance, DispatchError>; + type AssetRegistry: Create; /// Share token support type AssetPairAccountId: AssetPairAccountIdFor; @@ -129,6 +132,9 @@ pub mod pallet { /// Account whitelist manager to exclude pool accounts from dusting mechanism. type NonDustableWhitelistHandler: DustRemovalAccountWhitelist; + + /// Asset location type + type AssetLocation: Parameter + Member + Default + MaxEncodedLen; } #[pallet::error] @@ -344,10 +350,14 @@ pub mod pallet { let token_name = asset_pair.name(); - let share_token = T::AssetRegistry::get_or_create_shared_asset( - token_name, - vec![asset_a, asset_b], - T::MinPoolLiquidity::get(), + let share_token = T::AssetRegistry::get_or_register_insufficient_asset( + &token_name, + AssetKind::XYK, + None, + None, + None, + None, + None, )?; let _ = T::AMMHandler::on_create_pool(asset_pair.asset_in, asset_pair.asset_out); diff --git a/pallets/xyk/src/tests/creation.rs b/pallets/xyk/src/tests/creation.rs index bb79457e4..d5e6ad95f 100644 --- a/pallets/xyk/src/tests/creation.rs +++ b/pallets/xyk/src/tests/creation.rs @@ -1,7 +1,6 @@ pub use super::mock::*; use crate::{Error, Event}; use frame_support::{assert_noop, assert_ok, BoundedVec}; -use hydradx_traits::Registry; use hydradx_traits::AMM as AmmPool; use orml_traits::MultiCurrency; use pallet_asset_registry::AssetType; @@ -45,8 +44,8 @@ fn create_pool_should_work() { pallet_asset_registry::Event::Registered { asset_id: share_token, asset_name: Some(bounded_name), - asset_type: AssetType::PoolShare(HDX, ACA), - existential_deposit: ::MinPoolLiquidity::get(), + asset_type: AssetType::XYK, + existential_deposit: pallet_asset_registry::DEFAULT_ED, xcm_rate_limit: None, symbol: None, decimals: None, @@ -381,7 +380,7 @@ fn share_asset_id_should_be_offset() { RuntimeOrigin::signed(ALICE), Some(next_asset_id), Some(asset_pair.name()), - AssetType::PoolShare(HDX, ACA), + AssetType::XYK, Some(::MinPoolLiquidity::get()), None, None, @@ -403,7 +402,10 @@ fn share_asset_id_should_be_offset() { let share_token = XYK::share_token(pair_account); assert_eq!(share_token, next_asset_id); - assert_eq!(AssetRegistry::retrieve_asset(&asset_pair.name()).unwrap(), share_token); + let bounded_name = AssetRegistry::try_into_bounded(Some(asset_pair.name())) + .unwrap() + .unwrap(); + assert_eq!(AssetRegistry::asset_ids(bounded_name).unwrap(), share_token); // Act let next_asset_id = AssetRegistry::next_asset_id().unwrap(); @@ -427,6 +429,9 @@ fn share_asset_id_should_be_offset() { // Assert assert_eq!(share_token, next_asset_id); - assert_eq!(AssetRegistry::retrieve_asset(&asset_pair.name()).unwrap(), share_token); + let bounded_name = AssetRegistry::try_into_bounded(Some(asset_pair.name())) + .unwrap() + .unwrap(); + assert_eq!(AssetRegistry::asset_ids(bounded_name).unwrap(), share_token); }); } diff --git a/pallets/xyk/src/tests/mock.rs b/pallets/xyk/src/tests/mock.rs index c339dd8c9..6c66a04d4 100644 --- a/pallets/xyk/src/tests/mock.rs +++ b/pallets/xyk/src/tests/mock.rs @@ -54,6 +54,8 @@ pub const ONE: Balance = 1_000_000_000_000; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; +type AssetLocation = u8; + frame_support::construct_runtime!( pub enum Test where Block = Block, @@ -112,7 +114,7 @@ impl pallet_asset_registry::Config for Test { type Currency = Currency; type UpdateOrigin = EnsureSigned; type AssetId = AssetId; - type AssetNativeLocation = u8; + type AssetNativeLocation = AssetLocation; type StringLimit = RegistryStringLimit; type SequentialIdStartAt = SequentialIdOffset; type StorageFeesAssetId = NativeAssetId; @@ -216,6 +218,7 @@ impl Config for Test { type DiscountedFee = DiscountedFeeRate; type NonDustableWhitelistHandler = Whitelist; type OracleSource = OracleSourceIdentifier; + type AssetLocation = AssetLocation; } pub struct ExtBuilder { From 537e6f814283759060cbb7929544b2f10b768f6b Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 9 Nov 2023 09:43:14 +0100 Subject: [PATCH 51/93] pallet-stableswap: refactor to use latest registry traits --- Cargo.lock | 2 +- pallets/stableswap/Cargo.toml | 2 +- pallets/stableswap/src/lib.rs | 4 ++-- pallets/stableswap/src/tests/mock.rs | 14 ++++++++++++-- 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d640b85a8..00f717474 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7389,7 +7389,7 @@ dependencies = [ [[package]] name = "pallet-stableswap" -version = "3.3.1" +version = "3.4.0" dependencies = [ "bitflags", "frame-benchmarking", diff --git a/pallets/stableswap/Cargo.toml b/pallets/stableswap/Cargo.toml index 3025cbcc1..54e1a085d 100644 --- a/pallets/stableswap/Cargo.toml +++ b/pallets/stableswap/Cargo.toml @@ -1,6 +1,6 @@ [package] name = 'pallet-stableswap' -version = '3.3.1' +version = '3.4.0' description = 'AMM for correlated assets' authors = ['GalacticCouncil'] edition = '2021' diff --git a/pallets/stableswap/src/lib.rs b/pallets/stableswap/src/lib.rs index 77f98ddaf..415f6e842 100644 --- a/pallets/stableswap/src/lib.rs +++ b/pallets/stableswap/src/lib.rs @@ -44,7 +44,7 @@ extern crate core; use frame_support::pallet_prelude::{DispatchResult, Get}; use frame_support::{ensure, require_transactional, transactional}; -use hydradx_traits::{registry::InspectRegistry, AccountIdFor}; +use hydradx_traits::{registry::Inspect, AccountIdFor}; pub use pallet::*; use sp_runtime::traits::{BlockNumberProvider, Zero}; use sp_runtime::{ArithmeticError, DispatchError, Permill, SaturatedConversion}; @@ -126,7 +126,7 @@ pub mod pallet { type ShareAccountId: AccountIdFor; /// Asset registry mechanism - type AssetInspection: InspectRegistry; + type AssetInspection: Inspect; /// The origin which can create a new pool type AuthorityOrigin: EnsureOrigin; diff --git a/pallets/stableswap/src/tests/mock.rs b/pallets/stableswap/src/tests/mock.rs index c357cc019..9d6f15635 100644 --- a/pallets/stableswap/src/tests/mock.rs +++ b/pallets/stableswap/src/tests/mock.rs @@ -311,12 +311,14 @@ impl ExtBuilder { use crate::types::BenchmarkHelper; use crate::types::{AssetAmount, PoolInfo, PoolState, StableswapHooks}; use hydradx_traits::pools::DustRemovalAccountWhitelist; -use hydradx_traits::{AccountIdFor, InspectRegistry}; +use hydradx_traits::{AccountIdFor, Inspect}; use sp_runtime::traits::Zero; pub struct DummyRegistry; -impl InspectRegistry for DummyRegistry { +impl Inspect for DummyRegistry { + type AssetId = AssetId; + fn exists(asset_id: AssetId) -> bool { let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&asset_id).copied()); matches!(asset, Some(_)) @@ -326,6 +328,14 @@ impl InspectRegistry for DummyRegistry { let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&asset_id).copied())?; Some(asset.1) } + + fn is_sufficient(_id: Self::AssetId) -> bool { + unimplemented!() + } + + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() + } } #[cfg(feature = "runtime-benchmarks")] From a9e016f6b8eba81f02192b8a8409a45080f3b83a Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 9 Nov 2023 10:17:52 +0100 Subject: [PATCH 52/93] pallet-bonds: refactor to use latest registry traits --- Cargo.lock | 2 +- pallets/bonds/Cargo.toml | 2 +- pallets/bonds/src/lib.rs | 30 ++++++++++---- pallets/bonds/src/tests/issue.rs | 2 +- pallets/bonds/src/tests/mock.rs | 68 ++++++++++++++++++++++++-------- 5 files changed, 76 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 00f717474..87c092f1c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6389,7 +6389,7 @@ dependencies = [ [[package]] name = "pallet-bonds" -version = "2.0.0" +version = "2.1.0" dependencies = [ "frame-benchmarking", "frame-support", diff --git a/pallets/bonds/Cargo.toml b/pallets/bonds/Cargo.toml index aeb4cbf7f..0f806a0e5 100644 --- a/pallets/bonds/Cargo.toml +++ b/pallets/bonds/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-bonds" -version = "2.0.0" +version = "2.1.0" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/bonds/src/lib.rs b/pallets/bonds/src/lib.rs index bc064be8e..ca75526a4 100644 --- a/pallets/bonds/src/lib.rs +++ b/pallets/bonds/src/lib.rs @@ -55,7 +55,10 @@ use frame_system::{ensure_signed, pallet_prelude::OriginFor}; use sp_core::MaxEncodedLen; use sp_std::vec::Vec; -use hydradx_traits::{AssetKind, CreateRegistry, Registry}; +use hydradx_traits::{ + registry::{Create, Inspect}, + AssetKind, +}; use orml_traits::{GetByKey, MultiCurrency}; use primitives::{AssetId, Moment}; @@ -101,8 +104,8 @@ pub mod pallet { type Currency: MultiCurrency; /// Asset Registry mechanism - used to register bonds in the asset registry. - type AssetRegistry: Registry, Self::Balance, DispatchError> - + CreateRegistry; + type AssetRegistry: Inspect + + Create; /// Provider for existential deposits of assets. type ExistentialDeposits: GetByKey; @@ -128,6 +131,9 @@ pub mod pallet { #[pallet::constant] type FeeReceiver: Get; + /// Asset location type + type AssetLocation: Parameter + Member + Default + MaxEncodedLen; + /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } @@ -180,6 +186,8 @@ pub mod pallet { InvalidMaturity, /// Asset type not allowed for underlying asset DisallowedAsset, + /// Asset is not registered in `AssetRegistry` + AssetNotFound, } #[pallet::call] @@ -211,7 +219,9 @@ pub mod pallet { let who = T::IssueOrigin::ensure_origin(origin)?; ensure!( - T::AssetTypeWhitelist::contains(&T::AssetRegistry::retrieve_asset_type(asset_id)?), + T::AssetTypeWhitelist::contains( + &T::AssetRegistry::asset_type(asset_id).ok_or(Error::::AssetNotFound)? + ), Error::::DisallowedAsset ); @@ -226,11 +236,15 @@ pub mod pallet { ensure!(maturity >= T::TimestampProvider::now(), Error::::InvalidMaturity); let ed = T::ExistentialDeposits::get(&asset_id); - - let bond_id = >::create_asset( - &Self::bond_name(asset_id, maturity), + let bond_id = T::AssetRegistry::register_insufficient_asset( + None, + Some(&Self::bond_name(asset_id, maturity)), AssetKind::Bond, - ed, + Some(ed), + None, + None, + None, + None, )?; Bonds::::insert(bond_id, (asset_id, maturity)); diff --git a/pallets/bonds/src/tests/issue.rs b/pallets/bonds/src/tests/issue.rs index 79a071686..42569a292 100644 --- a/pallets/bonds/src/tests/issue.rs +++ b/pallets/bonds/src/tests/issue.rs @@ -494,7 +494,7 @@ fn issue_bonds_should_fail_when_underlying_asset_not_registered() { let asset_id = next_asset_id(); assert_noop!( Bonds::issue(RuntimeOrigin::signed(ALICE), asset_id, ONE, NOW + MONTH), - DispatchError::Other("AssetNotFound") + Error::::AssetNotFound ); }); } diff --git a/pallets/bonds/src/tests/mock.rs b/pallets/bonds/src/tests/mock.rs index da070395a..374afd05f 100644 --- a/pallets/bonds/src/tests/mock.rs +++ b/pallets/bonds/src/tests/mock.rs @@ -30,7 +30,7 @@ use frame_system::EnsureSignedBy; use sp_core::H256; use std::{cell::RefCell, collections::HashMap}; -use hydradx_traits::CreateRegistry; +use hydradx_traits::registry::{Create, Inspect}; use orml_traits::parameter_type_with_key; pub use primitives::constants::{ currency::NATIVE_EXISTENTIAL_DEPOSIT, @@ -43,6 +43,8 @@ pub use primitives::constants::{ type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; +type AssetLocation = u8; + pub type AccountId = u64; pub type Balance = u128; @@ -115,6 +117,7 @@ impl Config for Test { type AssetTypeWhitelist = AssetTypeWhitelist; type ProtocolFee = ProtocolFee; type FeeReceiver = TreasuryAccount; + type AssetLocation = AssetLocation; type WeightInfo = (); } @@ -172,40 +175,71 @@ impl pallet_timestamp::Config for Test { pub struct DummyRegistry(sp_std::marker::PhantomData); -impl CreateRegistry for DummyRegistry { +impl Create for DummyRegistry { type Error = DispatchError; - fn create_asset(_name: &[u8], _kind: AssetKind, existential_deposit: Balance) -> Result { + fn register_asset( + _asset_id: Option, + _name: Option<&[u8]>, + _kind: AssetKind, + _existential_deposit: Option, + _symbol: Option<&[u8]>, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + _is_sufficient: bool, + ) -> Result { + unimplemented!() + } + + fn register_insufficient_asset( + _asset_id: Option, + _name: Option<&[u8]>, + _kind: AssetKind, + existential_deposit: Option, + _symbol: Option<&[u8]>, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { let l = v.borrow().len(); - v.borrow_mut().insert(l as u32, (existential_deposit, AssetKind::Bond)); + v.borrow_mut() + .insert(l as u32, (existential_deposit.unwrap(), AssetKind::Bond)); l as u32 }); Ok(assigned) } -} - -impl Registry, Balance, DispatchError> for DummyRegistry { - fn exists(_name: AssetId) -> bool { + fn get_or_register_asset( + _name: &[u8], + _kind: AssetKind, + _existential_deposit: Option, + _symbol: Option<&[u8]>, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + _is_sufficient: bool, + ) -> Result { unimplemented!() } +} + +impl Inspect for DummyRegistry { + type AssetId = AssetId; - fn retrieve_asset(_name: &Vec) -> Result { + fn is_sufficient(_id: Self::AssetId) -> bool { unimplemented!() } - fn retrieve_asset_type(asset_id: AssetId) -> Result { - REGISTERED_ASSETS - .with(|v| v.borrow().get(&asset_id).cloned()) - .map(|v| v.1) - .ok_or(DispatchError::Other("AssetNotFound")) + fn decimals(_id: Self::AssetId) -> Option { + unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { - unimplemented!() + fn asset_type(id: Self::AssetId) -> Option { + REGISTERED_ASSETS.with(|v| v.borrow().get(&id).cloned()).map(|v| v.1) } - fn get_or_create_asset(_name: Vec, _existential_deposit: Balance) -> Result { + fn exists(_name: AssetId) -> bool { unimplemented!() } } From e04940dec98fb10684b91de1479bfdd2c919f29d Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 9 Nov 2023 10:29:33 +0100 Subject: [PATCH 53/93] pallet-omnipool: refactor to use latest registry traits --- Cargo.lock | 2 +- pallets/omnipool/Cargo.toml | 2 +- pallets/omnipool/src/lib.rs | 4 ++-- pallets/omnipool/src/tests/mock.rs | 25 +++++++++++-------------- 4 files changed, 15 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 87c092f1c..12538352a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7120,7 +7120,7 @@ dependencies = [ [[package]] name = "pallet-omnipool" -version = "3.2.3" +version = "3.3.0" dependencies = [ "bitflags", "frame-benchmarking", diff --git a/pallets/omnipool/Cargo.toml b/pallets/omnipool/Cargo.toml index 7bf8a892d..dd64f492b 100644 --- a/pallets/omnipool/Cargo.toml +++ b/pallets/omnipool/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-omnipool" -version = "3.2.3" +version = "3.3.0" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/omnipool/src/lib.rs b/pallets/omnipool/src/lib.rs index 586ff528e..aaf807def 100644 --- a/pallets/omnipool/src/lib.rs +++ b/pallets/omnipool/src/lib.rs @@ -79,7 +79,7 @@ use sp_std::prelude::*; use frame_support::traits::tokens::nonfungibles::{Create, Inspect, Mutate}; use hydra_dx_math::omnipool::types::{AssetStateChange, BalanceUpdate, I129}; -use hydradx_traits::Registry; +use hydradx_traits::registry::Inspect as RegistryInspect; use orml_traits::{GetByKey, MultiCurrency}; use scale_info::TypeInfo; use sp_runtime::{ArithmeticError, DispatchError, FixedPointNumber, FixedU128, Permill}; @@ -145,7 +145,7 @@ pub mod pallet { type TechnicalOrigin: EnsureOrigin; /// Asset Registry mechanism - used to check if asset is correctly registered in asset registry - type AssetRegistry: Registry, Balance, DispatchError>; + type AssetRegistry: RegistryInspect; /// Native Asset ID #[pallet::constant] diff --git a/pallets/omnipool/src/tests/mock.rs b/pallets/omnipool/src/tests/mock.rs index 637d50797..f6e6b85e0 100644 --- a/pallets/omnipool/src/tests/mock.rs +++ b/pallets/omnipool/src/tests/mock.rs @@ -31,7 +31,7 @@ use frame_support::{ traits::{ConstU32, ConstU64}, }; use frame_system::EnsureRoot; -use hydradx_traits::{AssetKind, Registry}; +use hydradx_traits::{registry::Inspect as InspectRegistry, AssetKind}; use orml_traits::parameter_type_with_key; use primitive_types::{U128, U256}; use sp_core::H256; @@ -515,30 +515,27 @@ impl + Into + Copy> Mutate for DummyNFT { pub struct DummyRegistry(sp_std::marker::PhantomData); -impl Registry, Balance, DispatchError> for DummyRegistry +impl InspectRegistry for DummyRegistry where T::AssetId: Into + From, { + type AssetId = T::AssetId; + + fn is_sufficient(_id: Self::AssetId) -> bool { + unimplemented!() + } + fn exists(asset_id: T::AssetId) -> bool { let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); matches!(asset, Some(_)) } - fn retrieve_asset(_name: &Vec) -> Result { - Ok(T::AssetId::default()) - } - - fn retrieve_asset_type(_asset_id: T::AssetId) -> Result { + fn decimals(_id: Self::AssetId) -> Option { unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { - let assigned = REGISTERED_ASSETS.with(|v| { - let l = v.borrow().len(); - v.borrow_mut().insert(l as u32, l as u32); - l as u32 - }); - Ok(T::AssetId::from(assigned)) + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() } } From c14a4e1560da996c191393ce9095002e0f9a3291 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 9 Nov 2023 10:38:09 +0100 Subject: [PATCH 54/93] pallet-dca: refactor to use latest registry traits --- Cargo.lock | 2 +- pallets/dca/Cargo.toml | 2 +- pallets/dca/src/tests/mock.rs | 27 ++++++++++++--------------- 3 files changed, 14 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 12538352a..15e5ff4c8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6600,7 +6600,7 @@ dependencies = [ [[package]] name = "pallet-dca" -version = "1.2.0" +version = "1.2.1" dependencies = [ "cumulus-pallet-parachain-system", "cumulus-primitives-core", diff --git a/pallets/dca/Cargo.toml b/pallets/dca/Cargo.toml index 00e5aef6a..29ae58192 100644 --- a/pallets/dca/Cargo.toml +++ b/pallets/dca/Cargo.toml @@ -1,6 +1,6 @@ [package] name = 'pallet-dca' -version = "1.2.0" +version = "1.2.1" description = 'A pallet to manage DCA scheduling' authors = ['GalacticCouncil'] edition = '2021' diff --git a/pallets/dca/src/tests/mock.rs b/pallets/dca/src/tests/mock.rs index 2cec929fc..ed52a1168 100644 --- a/pallets/dca/src/tests/mock.rs +++ b/pallets/dca/src/tests/mock.rs @@ -28,7 +28,7 @@ use frame_support::BoundedVec; use frame_support::{assert_ok, parameter_types}; use frame_system as system; use frame_system::{ensure_signed, EnsureRoot}; -use hydradx_traits::{AssetKind, NativePriceOracle, OraclePeriod, PriceOracle, Registry}; +use hydradx_traits::{registry::Inspect as InspectRegistry, AssetKind, NativePriceOracle, OraclePeriod, PriceOracle}; use orml_traits::{parameter_type_with_key, GetByKey}; use pallet_currencies::BasicCurrencyAdapter; use primitive_types::U128; @@ -716,30 +716,27 @@ impl + Into + Copy> Mutate for DummyNFT { pub struct DummyRegistry(sp_std::marker::PhantomData); -impl Registry, Balance, DispatchError> for DummyRegistry +impl InspectRegistry for DummyRegistry where T::AssetId: Into + From, { - fn exists(asset_id: T::AssetId) -> bool { - let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); - matches!(asset, Some(_)) + type AssetId = T::AssetId; + + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() } - fn retrieve_asset(_name: &Vec) -> Result { - Ok(1.into()) + fn is_sufficient(_id: Self::AssetId) -> bool { + unimplemented!() } - fn retrieve_asset_type(_asset_id: T::AssetId) -> Result { + fn decimals(_id: Self::AssetId) -> Option { unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { - let assigned = REGISTERED_ASSETS.with(|v| { - let l = v.borrow().len(); - v.borrow_mut().insert(l as u32, l as u32); - l as u32 - }); - Ok(T::AssetId::from(assigned)) + fn exists(asset_id: T::AssetId) -> bool { + let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); + matches!(asset, Some(_)) } } From b51cd6db1b2e00e140f40299468aea4afe749c43 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 9 Nov 2023 10:57:31 +0100 Subject: [PATCH 55/93] pallet-liquidity-minin: refactor to use latest registry traits --- Cargo.lock | 2 +- pallets/liquidity-mining/Cargo.toml | 4 ++- pallets/liquidity-mining/src/lib.rs | 4 +-- pallets/liquidity-mining/src/tests/mock.rs | 34 ++++++++++------------ 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 15e5ff4c8..32206941d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6940,7 +6940,7 @@ dependencies = [ [[package]] name = "pallet-liquidity-mining" -version = "4.2.4" +version = "4.3.0" dependencies = [ "fixed", "frame-support", diff --git a/pallets/liquidity-mining/Cargo.toml b/pallets/liquidity-mining/Cargo.toml index f49cd3f62..b4b5337bb 100644 --- a/pallets/liquidity-mining/Cargo.toml +++ b/pallets/liquidity-mining/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-liquidity-mining" -version = "4.2.4" +version = "4.3.0" description = "Liquidity mining" authors = ["GalacticCouncil"] edition = "2021" @@ -55,5 +55,7 @@ std = [ "sp-runtime/std", "scale-info/std", "hydra-dx-math/std", + "pallet-balances/std", + "orml-tokens/std", ] try-runtime = ["frame-support/try-runtime"] diff --git a/pallets/liquidity-mining/src/lib.rs b/pallets/liquidity-mining/src/lib.rs index 70384b119..55e0d99c6 100644 --- a/pallets/liquidity-mining/src/lib.rs +++ b/pallets/liquidity-mining/src/lib.rs @@ -115,7 +115,7 @@ use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::ArithmeticError; use hydra_dx_math::liquidity_mining as math; -use hydradx_traits::{liquidity_mining::PriceAdjustment, pools::DustRemovalAccountWhitelist, registry::Registry}; +use hydradx_traits::{liquidity_mining::PriceAdjustment, pools::DustRemovalAccountWhitelist, registry::Inspect}; use orml_traits::{GetByKey, MultiCurrency}; use scale_info::TypeInfo; use sp_arithmetic::{ @@ -209,7 +209,7 @@ pub mod pallet { /// Asset Registry - used to check if asset is correctly registered in asset registry and /// provides information about existential deposit of the asset. - type AssetRegistry: Registry, Balance, DispatchError> + GetByKey; + type AssetRegistry: Inspect + GetByKey; /// Account whitelist manager to exclude pool accounts from dusting mechanism. type NonDustableWhitelistHandler: DustRemovalAccountWhitelist; diff --git a/pallets/liquidity-mining/src/tests/mock.rs b/pallets/liquidity-mining/src/tests/mock.rs index f958404b3..270ff6715 100644 --- a/pallets/liquidity-mining/src/tests/mock.rs +++ b/pallets/liquidity-mining/src/tests/mock.rs @@ -27,7 +27,7 @@ use frame_support::{ PalletId, }; use frame_system as system; -use hydradx_traits::{pools::DustRemovalAccountWhitelist, registry::Registry, AssetKind, AMM}; +use hydradx_traits::{pools::DustRemovalAccountWhitelist, registry::Inspect, AssetKind, AMM}; use orml_traits::GetByKey; use sp_core::H256; use sp_runtime::{ @@ -293,7 +293,7 @@ impl Config for Test { type MaxFarmEntriesPerDeposit = MaxEntriesPerDeposit; type MaxYieldFarmsPerGlobalFarm = MaxYieldFarmsPerGlobalFarm; type NonDustableWhitelistHandler = Whitelist; - type AssetRegistry = AssetRegistry; + type AssetRegistry = DummyRegistry; type PriceAdjustment = DefaultPriceAdjustment; } @@ -317,7 +317,7 @@ impl Config for Test { type MaxFarmEntriesPerDeposit = MaxEntriesPerDeposit2; type MaxYieldFarmsPerGlobalFarm = MaxYieldFarmsPerGlobalFarm; type NonDustableWhitelistHandler = Whitelist; - type AssetRegistry = AssetRegistry; + type AssetRegistry = DummyRegistry; type PriceAdjustment = DefaultPriceAdjustment; } @@ -337,7 +337,7 @@ impl Config for Test { type MaxFarmEntriesPerDeposit = MaxEntriesPerDeposit; type MaxYieldFarmsPerGlobalFarm = MaxYieldFarmsPerGlobalFarm; type NonDustableWhitelistHandler = Whitelist; - type AssetRegistry = AssetRegistry; + type AssetRegistry = DummyRegistry; type PriceAdjustment = DummyOraclePriceAdjustment; } @@ -365,7 +365,7 @@ impl orml_tokens::Config for Test { type Amount = Amount; type CurrencyId = AssetId; type WeightInfo = (); - type ExistentialDeposits = AssetRegistry; + type ExistentialDeposits = DummyRegistry; type MaxLocks = MaxLocks; type DustRemovalWhitelist = Whitelist; type MaxReserves = ConstU32<100_000>; @@ -429,31 +429,29 @@ impl DustRemovalAccountWhitelist for Whitelist { } } -pub struct AssetRegistry; +pub struct DummyRegistry; -impl Registry, Balance, DispatchError> for AssetRegistry { - fn exists(name: AssetId) -> bool { - name != UNKNOWN_ASSET - } +impl Inspect for DummyRegistry { + type AssetId = AssetId; - fn retrieve_asset(_name: &Vec) -> Result { - Err(sp_runtime::DispatchError::Other("NotImplemented")) + fn is_sufficient(_id: Self::AssetId) -> bool { + unimplemented!() } - fn retrieve_asset_type(_asset_id: AssetId) -> Result { + fn decimals(_id: Self::AssetId) -> Option { unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { - Err(sp_runtime::DispatchError::Other("NotImplemented")) + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() } - fn get_or_create_asset(_name: Vec, _existential_deposit: Balance) -> Result { - Err(sp_runtime::DispatchError::Other("NotImplemented")) + fn exists(name: AssetId) -> bool { + name != UNKNOWN_ASSET } } -impl GetByKey for AssetRegistry { +impl GetByKey for DummyRegistry { fn get(_key: &AssetId) -> Balance { 1_000_u128 } From 4280f1c2df9d4e7e7ee1b4a9025ac9214b2710d0 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 9 Nov 2023 13:29:14 +0100 Subject: [PATCH 56/93] pallet-otc: refactor to use latest registry traits --- Cargo.lock | 2 +- pallets/otc/Cargo.toml | 2 +- pallets/otc/src/lib.rs | 11 ++++------- pallets/otc/src/tests/mock.rs | 28 ++++++++++++---------------- 4 files changed, 18 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 32206941d..3c47dfd7b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7176,7 +7176,7 @@ dependencies = [ [[package]] name = "pallet-otc" -version = "1.0.2" +version = "1.1.0" dependencies = [ "frame-benchmarking", "frame-support", diff --git a/pallets/otc/Cargo.toml b/pallets/otc/Cargo.toml index 37ef5ef91..accc98eb6 100644 --- a/pallets/otc/Cargo.toml +++ b/pallets/otc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = 'pallet-otc' -version = '1.0.2' +version = '1.1.0' description = 'A pallet for trustless over-the-counter trading' authors = ['GalacticCouncil'] edition = '2021' diff --git a/pallets/otc/src/lib.rs b/pallets/otc/src/lib.rs index 0926af109..09cd45333 100644 --- a/pallets/otc/src/lib.rs +++ b/pallets/otc/src/lib.rs @@ -36,14 +36,11 @@ use codec::MaxEncodedLen; use frame_support::{pallet_prelude::*, require_transactional}; use frame_system::{ensure_signed, pallet_prelude::OriginFor}; -use hydradx_traits::Registry; +use hydradx_traits::Inspect; use orml_traits::{GetByKey, MultiCurrency, NamedMultiReservableCurrency}; use sp_core::U256; -use sp_runtime::{ - traits::{One, Zero}, - DispatchError, -}; -use sp_std::vec::Vec; +use sp_runtime::traits::{One, Zero}; + #[cfg(test)] mod tests; @@ -88,7 +85,7 @@ pub mod pallet { type AssetId: Member + Parameter + Copy + HasCompact + MaybeSerializeDeserialize + MaxEncodedLen; /// Asset Registry mechanism - used to check if asset is correctly registered in asset registry - type AssetRegistry: Registry, Balance, DispatchError>; + type AssetRegistry: Inspect; /// Named reservable multi currency type Currency: NamedMultiReservableCurrency< diff --git a/pallets/otc/src/tests/mock.rs b/pallets/otc/src/tests/mock.rs index 04651cf11..38a0af4af 100644 --- a/pallets/otc/src/tests/mock.rs +++ b/pallets/otc/src/tests/mock.rs @@ -20,14 +20,13 @@ use frame_support::{ traits::{Everything, GenesisBuild, Nothing}, }; use frame_system as system; -use hydradx_traits::{AssetKind, Registry}; +use hydradx_traits::{registry::Inspect, AssetKind}; use orml_tokens::AccountData; use orml_traits::parameter_type_with_key; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - DispatchError, }; use std::{cell::RefCell, collections::HashMap}; @@ -138,27 +137,24 @@ impl orml_tokens::Config for Test { pub struct DummyRegistry(sp_std::marker::PhantomData); -impl Registry, Balance, DispatchError> for DummyRegistry { - fn exists(asset_id: AssetId) -> bool { - let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id)).copied()); - matches!(asset, Some(_)) +impl Inspect for DummyRegistry { + type AssetId = AssetId; + + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() } - fn retrieve_asset(_name: &Vec) -> Result { - Ok(0) + fn decimals(_id: Self::AssetId) -> Option { + unimplemented!() } - fn retrieve_asset_type(_asset_id: AssetId) -> Result { + fn is_sufficient(_id: Self::AssetId) -> bool { unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { - let assigned = REGISTERED_ASSETS.with(|v| { - let l = v.borrow().len(); - v.borrow_mut().insert(l as u32, l as u32); - l as u32 - }); - Ok(assigned) + fn exists(asset_id: AssetId) -> bool { + let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id)).copied()); + matches!(asset, Some(_)) } } From a2f0f3f73752811b435b54d1a63d8a8419322a74 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 9 Nov 2023 14:09:54 +0100 Subject: [PATCH 57/93] pallet-omnipool-liquidity-mining: refactor to use latest registry traits --- Cargo.lock | 3 +- pallets/omnipool-liquidity-mining/Cargo.toml | 10 +++--- .../src/tests/mock.rs | 32 +++++++------------ 3 files changed, 19 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3c47dfd7b..a4cbf797a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7147,9 +7147,8 @@ dependencies = [ [[package]] name = "pallet-omnipool-liquidity-mining" -version = "2.0.11" +version = "2.1.0" dependencies = [ - "bitflags", "frame-benchmarking", "frame-support", "frame-system", diff --git a/pallets/omnipool-liquidity-mining/Cargo.toml b/pallets/omnipool-liquidity-mining/Cargo.toml index a327bf927..c8c9d55b8 100644 --- a/pallets/omnipool-liquidity-mining/Cargo.toml +++ b/pallets/omnipool-liquidity-mining/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-omnipool-liquidity-mining" -version = "2.0.11" +version = "2.1.0" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" @@ -40,7 +40,6 @@ hydra-dx-math = { workspace = true } # third party primitive-types = { version = "0.12.0", default-features = false } -bitflags = "1.3.2" # Optional imports for benchmarking frame-benchmarking = { workspace = true, optional = true } @@ -60,17 +59,20 @@ test-utils = { workspace = true } default = ["std"] std = [ "codec/std", + "scale-info/std", "sp-runtime/std", "sp-std/std", "frame-support/std", "frame-system/std", - "scale-info/std", "sp-core/std", "sp-io/std", "pallet-balances/std", "orml-tokens/std", - "pallet-omnipool/std", + "pallet-omnipool/std", "pallet-liquidity-mining/std", + "pallet-ema-oracle/std", + "hydra-dx-math/std", + "primitives/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/pallets/omnipool-liquidity-mining/src/tests/mock.rs b/pallets/omnipool-liquidity-mining/src/tests/mock.rs index d1627a73d..dad46445c 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mock.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mock.rs @@ -636,39 +636,31 @@ impl Transfer for DummyNFT { } } -use hydradx_traits::Registry; +use hydradx_traits::Inspect as InspectRegistry; pub struct DummyRegistry(sp_std::marker::PhantomData); -impl Registry, Balance, DispatchError> for DummyRegistry +impl InspectRegistry for DummyRegistry where T::AssetId: Into + From, { - fn exists(asset_id: T::AssetId) -> bool { - let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); - matches!(asset, Some(_)) + type AssetId = T::AssetId; + + fn is_sufficient(_id: Self::AssetId) -> bool { + unimplemented!() } - fn retrieve_asset(_name: &Vec) -> Result { - Ok(T::AssetId::default()) + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() } - fn retrieve_asset_type(_asset_id: T::AssetId) -> Result { + fn decimals(_id: Self::AssetId) -> Option { unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { - let assigned = REGISTERED_ASSETS.with(|v| { - //NOTE: This is to have same ids as real AssetRegistry which is used in the benchmarks. - //1_000_000 - offset of the reals AssetRegistry - // - 3 - remove assets reagistered by default for the vec.len() - // +1 - first reg asset start with 1 not 0 - // => 1-th asset id == 1_000_001 - let l = 1_000_000 - 3 + 1 + v.borrow().len(); - v.borrow_mut().insert(l as u32, l as u32); - l as u32 - }); - Ok(T::AssetId::from(assigned)) + fn exists(asset_id: T::AssetId) -> bool { + let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); + matches!(asset, Some(_)) } } From ff08f1d657e1eacc0e533bf9ea4add217b9c7e0e Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 9 Nov 2023 14:46:51 +0100 Subject: [PATCH 58/93] fix integration-tests and missing AssetLocation to runtime configs --- integration-tests/src/bonds.rs | 30 ++++++++++++++++++++++-------- integration-tests/src/dca.rs | 22 ++++++++++++++-------- integration-tests/src/router.rs | 4 ++-- runtime/hydradx/src/assets.rs | 2 ++ 4 files changed, 40 insertions(+), 18 deletions(-) diff --git a/integration-tests/src/bonds.rs b/integration-tests/src/bonds.rs index c3f4d2728..dfcd93a64 100644 --- a/integration-tests/src/bonds.rs +++ b/integration-tests/src/bonds.rs @@ -6,7 +6,7 @@ use crate::polkadot_test_net::*; use frame_support::storage::with_transaction; use frame_support::{assert_noop, assert_ok}; use frame_system::RawOrigin; -use hydradx_traits::CreateRegistry; +use hydradx_traits::registry::{AssetKind, Create}; use orml_traits::MultiCurrency; use sp_runtime::{DispatchResult, TransactionOutcome}; use xcm_emulator::TestExt; @@ -65,10 +65,15 @@ fn issue_bonds_should_work_when_issued_for_share_asset() { let maturity = NOW + MONTH; let name = b"SHARED".to_vec(); - let share_asset_id = AssetRegistry::create_asset( - &name, - pallet_asset_registry::AssetType::PoolShare(HDX, DOT).into(), - 1_000, + let share_asset_id = AssetRegistry::register_insufficient_asset( + None, + Some(&name), + AssetKind::XYK, + Some(1_000), + None, + None, + None, + None, ) .unwrap(); assert_ok!(Currencies::deposit(share_asset_id, &ALICE.into(), amount,)); @@ -119,9 +124,18 @@ fn issue_bonds_should_not_work_when_issued_for_bond_asset() { let maturity = NOW + MONTH; let name = b"BOND".to_vec(); - let underlying_asset_id = - AssetRegistry::create_asset(&name, pallet_asset_registry::AssetType::::Bond.into(), 1_000) - .unwrap(); + let underlying_asset_id = AssetRegistry::register_insufficient_asset( + None, + Some(&name), + AssetKind::Bond, + Some(1_000), + None, + None, + None, + None, + ) + .unwrap(); + assert_ok!(Currencies::deposit(underlying_asset_id, &ALICE.into(), amount,)); // Act & Assert diff --git a/integration-tests/src/dca.rs b/integration-tests/src/dca.rs index 6c288a2c2..7481e6501 100644 --- a/integration-tests/src/dca.rs +++ b/integration-tests/src/dca.rs @@ -11,11 +11,8 @@ use hydradx_runtime::{ AssetRegistry, Balances, Currencies, Omnipool, Router, Runtime, RuntimeEvent, RuntimeOrigin, Stableswap, Tokens, Treasury, DCA, }; +use hydradx_traits::registry::{AssetKind, Create}; use hydradx_traits::router::{PoolType, Trade}; -use hydradx_traits::{ - registry::{AssetKind, Create}, - Registry, -}; use orml_traits::MultiCurrency; use orml_traits::MultiReservableCurrency; use pallet_dca::types::{Order, Schedule}; @@ -2314,7 +2311,7 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { None, Some(name.as_ref()), AssetKind::Token, - Some(1u128), + 1u128, Some(b"xDUM".as_ref()), Some(18u8), None, @@ -2335,7 +2332,7 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { None, Some(b"pool".as_ref()), AssetKind::Token, - Some(1u128), + 1u128, None, None, None, @@ -2372,7 +2369,7 @@ pub fn init_stableswap_with_three_assets_having_different_decimals( None, Some(name.as_ref()), AssetKind::Token, - Some(1u128), + 1u128, Some(b"xDUM".as_ref()), Some(decimals_for_each_asset[idx as usize]), None, @@ -2395,7 +2392,16 @@ pub fn init_stableswap_with_three_assets_having_different_decimals( initial.push(AssetAmount::new(asset_id, initial_liquidity)); added_liquidity.push(AssetAmount::new(asset_id, liquidity_added)); } - let pool_id = AssetRegistry::create_asset(&b"pool".to_vec(), 1u128)?; + let pool_id = AssetRegistry::register_insufficient_asset( + None, + Some(&b"pool".to_vec()), + AssetKind::Token, + Some(1u128), + None, + None, + None, + None, + )?; let amplification = 100u16; let fee = Permill::from_percent(1); diff --git a/integration-tests/src/router.rs b/integration-tests/src/router.rs index 8231c8f3d..62cb21cbe 100644 --- a/integration-tests/src/router.rs +++ b/integration-tests/src/router.rs @@ -2314,7 +2314,7 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { None, Some(name.as_ref()), AssetKind::Token, - Some(1u128), + 1u128, Some(b"xDUM".as_ref()), Some(18u8), None, @@ -2342,7 +2342,7 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { None, Some(b"pool".as_ref()), AssetKind::Token, - Some(1u128), + 1u128, None, None, None, diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 716fcd184..c71a2ad89 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -985,6 +985,7 @@ impl pallet_bonds::Config for Runtime { type AssetTypeWhitelist = AssetTypeWhitelist; type ProtocolFee = ProtocolFee; type FeeReceiver = TreasuryAccount; + type AssetLocation = AssetLocation; type WeightInfo = weights::bonds::HydraWeight; } @@ -1100,4 +1101,5 @@ impl pallet_xyk::Config for Runtime { type DiscountedFee = DiscountedFee; type NonDustableWhitelistHandler = Duster; type OracleSource = XYKOracleSourceIdentifier; + type AssetLocation = AssetLocation; } From 92b940fc2b3b684d2d7f23f25bca1fa817773ad3 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 10 Nov 2023 16:14:55 +0100 Subject: [PATCH 59/93] refactor benchmarks to use use latest registry traits --- pallets/circuit-breaker/Cargo.toml | 3 ++ pallets/circuit-breaker/src/tests/mock.rs | 28 +++++----- .../src/benchmarks.rs | 39 ++++++++++++-- pallets/omnipool-liquidity-mining/src/lib.rs | 4 ++ .../src/tests/mock.rs | 52 +++++++++++++++++- pallets/otc/Cargo.toml | 1 + pallets/otc/src/benchmarks.rs | 27 ++++++++-- pallets/otc/src/lib.rs | 4 ++ pallets/otc/src/tests/mock.rs | 54 ++++++++++++++++++- pallets/staking/Cargo.toml | 2 +- pallets/xcm-rate-limiter/src/tests/mock.rs | 27 +++++----- runtime/adapters/src/tests/mock.rs | 27 +++++----- runtime/hydradx/src/assets.rs | 8 ++- runtime/hydradx/src/benchmarking/mod.rs | 2 +- .../src/benchmarking/route_executor.rs | 3 +- 15 files changed, 222 insertions(+), 59 deletions(-) diff --git a/pallets/circuit-breaker/Cargo.toml b/pallets/circuit-breaker/Cargo.toml index 6ebe64d55..f0d88a8d3 100644 --- a/pallets/circuit-breaker/Cargo.toml +++ b/pallets/circuit-breaker/Cargo.toml @@ -47,6 +47,9 @@ std = [ 'frame-system/std', 'serde/std', 'scale-info/std', + 'frame-benchmarking/std', + 'pallet-balances/std', + 'orml-tokens/std', ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/pallets/circuit-breaker/src/tests/mock.rs b/pallets/circuit-breaker/src/tests/mock.rs index 6ae036067..efefa78d5 100644 --- a/pallets/circuit-breaker/src/tests/mock.rs +++ b/pallets/circuit-breaker/src/tests/mock.rs @@ -36,6 +36,7 @@ use sp_runtime::{ use std::cell::RefCell; use std::collections::HashMap; use std::marker::PhantomData; +//use frame_system::GenesisConfig; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; @@ -362,35 +363,32 @@ impl + Into + Copy> Mutate for DummyNFT { } use crate::Config; -use hydradx_traits::{AssetKind, Registry}; +use hydradx_traits::registry::{AssetKind, Inspect as InspectRegistry}; use pallet_omnipool::traits::{AssetInfo, ExternalPriceProvider, OmnipoolHooks}; pub struct DummyRegistry(sp_std::marker::PhantomData); -impl Registry, Balance, DispatchError> for DummyRegistry +impl InspectRegistry for DummyRegistry where T::AssetId: Into + From, { - fn exists(asset_id: T::AssetId) -> bool { - let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); - matches!(asset, Some(_)) + type AssetId = T::AssetId; + + fn is_sufficient(_id: Self::AssetId) -> bool { + unimplemented!() } - fn retrieve_asset(_name: &Vec) -> Result { - Ok(T::AssetId::default()) + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() } - fn retrieve_asset_type(_asset_id: T::AssetId) -> Result { + fn decimals(_id: Self::AssetId) -> Option { unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { - let assigned = REGISTERED_ASSETS.with(|v| { - let l = v.borrow().len(); - v.borrow_mut().insert(l as u32, l as u32); - l as u32 - }); - Ok(T::AssetId::from(assigned)) + fn exists(asset_id: T::AssetId) -> bool { + let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); + matches!(asset, Some(_)) } } diff --git a/pallets/omnipool-liquidity-mining/src/benchmarks.rs b/pallets/omnipool-liquidity-mining/src/benchmarks.rs index 5132a6f0c..f32e43225 100644 --- a/pallets/omnipool-liquidity-mining/src/benchmarks.rs +++ b/pallets/omnipool-liquidity-mining/src/benchmarks.rs @@ -19,7 +19,7 @@ use crate::*; use frame_benchmarking::{account, benchmarks}; use frame_support::traits::{OnFinalize, OnInitialize}; use frame_system::{Pallet as System, RawOrigin}; -use hydradx_traits::Registry; +use hydradx_traits::registry::{AssetKind, Create}; use orml_traits::MultiCurrencyExtended; use pallet_liquidity_mining::Instance1; use primitives::AssetId; @@ -94,6 +94,9 @@ where ::Currency: MultiCurrencyExtended, T: pallet_ema_oracle::Config, T::AssetId: From, + ::AssetRegistry: + Create, + <::AssetRegistry as hydradx_traits::Inspect>::AssetId: From, { let stable_amount: Balance = 1_000_000_000_000_000_u128; let native_amount: Balance = 1_000_000_000_000_000_u128; @@ -115,9 +118,36 @@ where )?; // Register new asset in asset registry - T::AssetRegistry::create_asset(&b"BSX".to_vec(), Balance::one())?; - T::AssetRegistry::create_asset(&b"ETH".to_vec(), Balance::one())?; - T::AssetRegistry::create_asset(&b"BTC".to_vec(), Balance::one())?; + T::AssetRegistry::register_sufficient_asset( + None, + Some(&b"BSX".to_vec()), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )?; + T::AssetRegistry::register_sufficient_asset( + None, + Some(&b"ETH".to_vec()), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )?; + T::AssetRegistry::register_sufficient_asset( + None, + Some(&b"BTC".to_vec()), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )?; // Create account for token provider and set balance let owner: T::AccountId = account("owner", 0, 1); @@ -228,6 +258,7 @@ benchmarks! { ::AssetId: From, ::Currency: MultiCurrencyExtended, T: crate::pallet::Config + pallet_ema_oracle::Config + pallet_liquidity_mining::Config, + ::AssetRegistry: Create::AssetId>, } create_global_farm { diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index 49662556a..43385fa8a 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -153,6 +153,10 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; + + #[cfg(feature = "runtime-benchmarks")] + /// Asset location type + type AssetLocation: Parameter + Member + Default + MaxEncodedLen; } #[pallet::storage] diff --git a/pallets/omnipool-liquidity-mining/src/tests/mock.rs b/pallets/omnipool-liquidity-mining/src/tests/mock.rs index dad46445c..f83373f09 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mock.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mock.rs @@ -169,7 +169,7 @@ parameter_types! { pub const OracleSource: Source = *b"omnipool"; } -impl Config for Test { +impl omnipool_liquidity_mining::Config for Test { type RuntimeEvent = RuntimeEvent; type Currency = Tokens; type CreateOrigin = frame_system::EnsureRoot; @@ -181,6 +181,9 @@ impl Config for Test { type OraclePeriod = PeriodOracle; type PriceOracle = DummyOracle; type WeightInfo = (); + + #[cfg(feature = "runtime-benchmarks")] + type AssetLocation = u8; } parameter_types! { @@ -664,6 +667,53 @@ where } } +#[cfg(feature = "runtime-benchmarks")] +use hydradx_traits::Create as CreateRegistry; +#[cfg(feature = "runtime-benchmarks")] +impl CreateRegistry for DummyRegistry +where + T::AssetId: Into + From, +{ + type Error = DispatchError; + + fn register_asset( + _asset_id: Option, + _name: Option<&[u8]>, + _kind: AssetKind, + _existential_deposit: Option, + _symbol: Option<&[u8]>, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + _is_sufficient: bool, + ) -> Result { + let assigned = REGISTERED_ASSETS.with(|v| { + //NOTE: This is to have same ids as real AssetRegistry which is used in the benchmarks. + //1_000_000 - offset of the reals AssetRegistry + // - 3 - remove assets reagistered by default for the vec.len() + // +1 - first reg asset start with 1 not 0 + // => 1-th asset id == 1_000_001 + let l = 1_000_000 - 3 + 1 + v.borrow().len(); + v.borrow_mut().insert(l as u32, l as u32); + l as u32 + }); + Ok(T::AssetId::from(assigned)) + } + + fn get_or_register_asset( + _name: &[u8], + _kind: AssetKind, + _existential_deposit: Option, + _symbol: Option<&[u8]>, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + _is_sufficient: bool, + ) -> Result { + unimplemented!() + } +} + use hydradx_traits::oracle::AggregatedPriceOracle; use pallet_omnipool::traits::ExternalPriceProvider; diff --git a/pallets/otc/Cargo.toml b/pallets/otc/Cargo.toml index accc98eb6..e27a5b5b3 100644 --- a/pallets/otc/Cargo.toml +++ b/pallets/otc/Cargo.toml @@ -51,6 +51,7 @@ std = [ "scale-info/std", "orml-tokens/std", "hydradx-traits/std", + "frame-benchmarking/std" ] runtime-benchmarks = [ diff --git a/pallets/otc/src/benchmarks.rs b/pallets/otc/src/benchmarks.rs index 0e494de05..3cc294e8c 100644 --- a/pallets/otc/src/benchmarks.rs +++ b/pallets/otc/src/benchmarks.rs @@ -17,9 +17,10 @@ use super::*; use frame_benchmarking::{account, benchmarks}; use frame_support::assert_ok; use frame_system::RawOrigin; -use hydradx_traits::Registry; +use hydradx_traits::{AssetKind, Create}; use orml_traits::MultiCurrencyExtended; use sp_std::vec; +use sp_std::vec::Vec; pub const ONE: Balance = 1_000_000_000_000; benchmarks! { @@ -28,6 +29,7 @@ benchmarks! { T::Currency: MultiCurrencyExtended, T: crate::pallet::Config, u32: From<::AssetId>, + T::AssetRegistry: Create } place_order { let (hdx, dai) = seed_registry::()?; @@ -82,10 +84,29 @@ benchmarks! { fn seed_registry() -> Result<(u32, u32), DispatchError> where u32: From<::AssetId>, + T::AssetRegistry: Create, { // Register new asset in asset registry - let hdx = T::AssetRegistry::create_asset(&b"HDX".to_vec(), ONE)?; - let dai = T::AssetRegistry::create_asset(&b"DAI".to_vec(), ONE)?; + let hdx = ::AssetRegistry::register_sufficient_asset( + None, + Some(&b"HDX".to_vec()), + AssetKind::Token, + ONE, + None, + None, + None, + None, + )?; + let dai = ::AssetRegistry::register_sufficient_asset( + None, + Some(&b"DAI".to_vec()), + AssetKind::Token, + ONE, + None, + None, + None, + None, + )?; Ok((hdx.into(), dai.into())) } diff --git a/pallets/otc/src/lib.rs b/pallets/otc/src/lib.rs index 09cd45333..852cfe5f4 100644 --- a/pallets/otc/src/lib.rs +++ b/pallets/otc/src/lib.rs @@ -104,6 +104,10 @@ pub mod pallet { /// Weight information for the extrinsics. type WeightInfo: WeightInfo; + + #[cfg(feature = "runtime-benchmarks")] + /// Asset location type + type AssetLocation: Parameter + Member + Default + MaxEncodedLen; } #[pallet::event] diff --git a/pallets/otc/src/tests/mock.rs b/pallets/otc/src/tests/mock.rs index 38a0af4af..9f3fe658d 100644 --- a/pallets/otc/src/tests/mock.rs +++ b/pallets/otc/src/tests/mock.rs @@ -78,7 +78,7 @@ parameter_type_with_key! { }; } -impl Config for Test { +impl otc::Config for Test { type AssetId = AssetId; type AssetRegistry = DummyRegistry; type Currency = Tokens; @@ -86,6 +86,9 @@ impl Config for Test { type ExistentialDeposits = ExistentialDeposits; type ExistentialDepositMultiplier = ExistentialDepositMultiplier; type WeightInfo = (); + + #[cfg(feature = "runtime-benchmarks")] + type AssetLocation = u8; } parameter_types! { @@ -158,6 +161,55 @@ impl Inspect for DummyRegistry { } } +#[cfg(feature = "runtime-benchmarks")] +use hydradx_traits::Create as CreateRegistry; +#[cfg(feature = "runtime-benchmarks")] +use sp_runtime::DispatchError; +#[cfg(feature = "runtime-benchmarks")] +impl CreateRegistry for DummyRegistry +where + T::AssetId: Into + From, +{ + type Error = DispatchError; + + fn register_asset( + _asset_id: Option, + _name: Option<&[u8]>, + _kind: AssetKind, + _existential_deposit: Option, + _symbol: Option<&[u8]>, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + _is_sufficient: bool, + ) -> Result { + let assigned = REGISTERED_ASSETS.with(|v| { + //NOTE: This is to have same ids as real AssetRegistry which is used in the benchmarks. + //1_000_000 - offset of the reals AssetRegistry + // - 3 - remove assets reagistered by default for the vec.len() + // +1 - first reg asset start with 1 not 0 + // => 1-th asset id == 1_000_001 + let l = 1_000_000 - 3 + 1 + v.borrow().len(); + v.borrow_mut().insert(l as u32, l as u32); + l as u32 + }); + Ok(assigned) + } + + fn get_or_register_asset( + _name: &[u8], + _kind: AssetKind, + _existential_deposit: Option, + _symbol: Option<&[u8]>, + _decimals: Option, + _location: Option, + _xcm_rate_limit: Option, + _is_sufficient: bool, + ) -> Result { + unimplemented!() + } +} + pub struct ExtBuilder { endowed_accounts: Vec<(u64, AssetId, Balance)>, registered_assets: Vec, diff --git a/pallets/staking/Cargo.toml b/pallets/staking/Cargo.toml index 0babe26ba..eab963ba8 100644 --- a/pallets/staking/Cargo.toml +++ b/pallets/staking/Cargo.toml @@ -58,7 +58,7 @@ std = [ "pallet-democracy/std", ] runtime-benchmarks = [ - "frame-benchmarking/runtime-benchmarks", + "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "sp-runtime/runtime-benchmarks", diff --git a/pallets/xcm-rate-limiter/src/tests/mock.rs b/pallets/xcm-rate-limiter/src/tests/mock.rs index a038c5a8f..fb2e324d7 100644 --- a/pallets/xcm-rate-limiter/src/tests/mock.rs +++ b/pallets/xcm-rate-limiter/src/tests/mock.rs @@ -309,35 +309,32 @@ impl + Into + Copy> Mutate for DummyNFT { } use crate::Config; -use hydradx_traits::{AssetKind, Registry}; +use hydradx_traits::registry::{AssetKind, Inspect as InspectRegistry}; use pallet_omnipool::traits::ExternalPriceProvider; pub struct DummyRegistry(sp_std::marker::PhantomData); -impl Registry, Balance, DispatchError> for DummyRegistry +impl InspectRegistry for DummyRegistry where T::AssetId: Into + From, { - fn exists(asset_id: T::AssetId) -> bool { - let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); - matches!(asset, Some(_)) + type AssetId = T::AssetId; + + fn is_sufficient(_id: Self::AssetId) -> bool { + unimplemented!() } - fn retrieve_asset(_name: &Vec) -> Result { - Ok(T::AssetId::default()) + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() } - fn retrieve_asset_type(_asset_id: T::AssetId) -> Result { + fn decimals(_id: Self::AssetId) -> Option { unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { - let assigned = REGISTERED_ASSETS.with(|v| { - let l = v.borrow().len(); - v.borrow_mut().insert(l as u32, l as u32); - l as u32 - }); - Ok(T::AssetId::from(assigned)) + fn exists(asset_id: T::AssetId) -> bool { + let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); + matches!(asset, Some(_)) } } diff --git a/runtime/adapters/src/tests/mock.rs b/runtime/adapters/src/tests/mock.rs index 3dddb08a2..3b3849ccf 100644 --- a/runtime/adapters/src/tests/mock.rs +++ b/runtime/adapters/src/tests/mock.rs @@ -27,7 +27,7 @@ use frame_support::{ traits::{ConstU32, ConstU64}, }; use frame_system::EnsureRoot; -use hydradx_traits::{AssetKind, Registry}; +use hydradx_traits::{AssetKind, Inspect as InspectRegistry}; use orml_traits::{parameter_type_with_key, GetByKey}; use pallet_currencies::BasicCurrencyAdapter; use pallet_omnipool; @@ -538,30 +538,27 @@ impl + Into + Copy> Mutate for DummyNFT { pub struct DummyRegistry(sp_std::marker::PhantomData); -impl Registry, Balance, DispatchError> for DummyRegistry +impl InspectRegistry for DummyRegistry where T::AssetId: Into + From, { - fn exists(asset_id: T::AssetId) -> bool { - let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); - matches!(asset, Some(_)) + type AssetId = AssetId; + + fn asset_type(_id: Self::AssetId) -> Option { + unimplemented!() } - fn retrieve_asset(_name: &Vec) -> Result { - Ok(T::AssetId::default()) + fn decimals(_id: Self::AssetId) -> Option { + unimplemented!() } - fn retrieve_asset_type(_asset_id: T::AssetId) -> Result { + fn is_sufficient(_id: Self::AssetId) -> bool { unimplemented!() } - fn create_asset(_name: &Vec, _existential_deposit: Balance) -> Result { - let assigned = REGISTERED_ASSETS.with(|v| { - let l = v.borrow().len(); - v.borrow_mut().insert(l as u32, l as u32); - l as u32 - }); - Ok(T::AssetId::from(assigned)) + fn exists(asset_id: AssetId) -> bool { + let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id)).copied()); + matches!(asset, Some(_)) } } diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index c71a2ad89..c20f77c20 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -560,6 +560,9 @@ impl pallet_omnipool_liquidity_mining::Config for Runtime { type OraclePeriod = OmnipoolLMOraclePeriod; type PriceOracle = EmaOracle; type WeightInfo = weights::omnipool_lm::HydraWeight; + + #[cfg(feature = "runtime-benchmarks")] + type AssetLocation = AssetLocation; } // The reason why there is difference between PROD and benchmark is that it is not possible @@ -859,6 +862,9 @@ impl pallet_otc::Config for Runtime { type ExistentialDeposits = AssetRegistry; type ExistentialDepositMultiplier = ExistentialDepositMultiplier; type WeightInfo = weights::otc::HydraWeight; + + #[cfg(feature = "runtime-benchmarks")] + type AssetLocation = AssetLocation; } // Dynamic fees @@ -931,7 +937,7 @@ impl BenchmarkHelper for RegisterAsse Some(asset_id), Some(&asset_name), AssetKind::Token, - Some(1), + 1, Some(&asset_name), Some(decimals), None, diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index 306a45c54..849234096 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -28,7 +28,7 @@ pub fn register_asset(name: Vec, deposit: Balance) -> Result { None, Some(&name), AssetKind::Token, - Some(deposit), + deposit, None, None, None, diff --git a/runtime/hydradx/src/benchmarking/route_executor.rs b/runtime/hydradx/src/benchmarking/route_executor.rs index a4e3e1cde..89aeaff02 100644 --- a/runtime/hydradx/src/benchmarking/route_executor.rs +++ b/runtime/hydradx/src/benchmarking/route_executor.rs @@ -18,7 +18,6 @@ use crate::{AccountId, AssetId, Balance, Currencies, Router, Runtime, System, LBP}; -use crate::InsufficientEDinHDX; use frame_benchmarking::account; use frame_support::dispatch::DispatchResult; use frame_support::{assert_ok, ensure}; @@ -129,7 +128,7 @@ runtime_benchmarks! { assert_eq!(>::free_balance( asset_in, &seller, - ), INITIAL_BALANCE - amount_to_sell - InsufficientEDinHDX::get()); + ), INITIAL_BALANCE - amount_to_sell); } } From 85039edb9e31a463aedb6dca0e325994864ace97 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 10 Nov 2023 16:56:26 +0100 Subject: [PATCH 60/93] pallet-otc: fixed benchmarks --- pallets/otc/src/benchmarks.rs | 87 +++++++++++++++++++---------------- 1 file changed, 47 insertions(+), 40 deletions(-) diff --git a/pallets/otc/src/benchmarks.rs b/pallets/otc/src/benchmarks.rs index 3cc294e8c..3bcb1c25d 100644 --- a/pallets/otc/src/benchmarks.rs +++ b/pallets/otc/src/benchmarks.rs @@ -32,52 +32,52 @@ benchmarks! { T::AssetRegistry: Create } place_order { - let (hdx, dai) = seed_registry::()?; + let (dot, dai) = seed_registry::()?; - let owner: T::AccountId = create_account_with_balances::("owner", 1, vec!(hdx, dai))?; - }: _(RawOrigin::Signed(owner.clone()), dai.into(), hdx.into(), 20 * ONE, 100 * ONE, true) + let owner: T::AccountId = create_account_with_balances::("owner", 1, vec!(dot, dai))?; + }: _(RawOrigin::Signed(owner.clone()), dai.into(), dot.into(), 20 * ONE, 100 * ONE, true) verify { - assert_eq!(T::Currency::reserved_balance_named(&NAMED_RESERVE_ID, hdx.into(), &owner), 100 * ONE); + assert_eq!(T::Currency::reserved_balance_named(&NAMED_RESERVE_ID, dot.into(), &owner), 100 * ONE); } partial_fill_order { - let (hdx, dai) = seed_registry::()?; + let (dot, dai) = seed_registry::()?; - let owner: T::AccountId = create_account_with_balances::("owner", 1, vec!(hdx, dai))?; - let filler: T::AccountId = create_account_with_balances::("filler", 2, vec!(hdx, dai))?; + let owner: T::AccountId = create_account_with_balances::("owner", 1, vec!(dot, dai))?; + let filler: T::AccountId = create_account_with_balances::("filler", 2, vec!(dot, dai))?; assert_ok!( - crate::Pallet::::place_order(RawOrigin::Signed(owner.clone()).into(), dai.into(), hdx.into(), 20 * ONE, 100 * ONE, true) + crate::Pallet::::place_order(RawOrigin::Signed(owner.clone()).into(), dai.into(), dot.into(), 20 * ONE, 100 * ONE, true) ); }: _(RawOrigin::Signed(filler.clone()), 0u32, 10 * ONE) verify { - assert_eq!(T::Currency::reserved_balance_named(&NAMED_RESERVE_ID, hdx.into(), &owner), 50 * ONE); + assert_eq!(T::Currency::reserved_balance_named(&NAMED_RESERVE_ID, dot.into(), &owner), 50 * ONE); } fill_order { - let (hdx, dai) = seed_registry::()?; + let (dot, dai) = seed_registry::()?; - let owner: T::AccountId = create_account_with_balances::("owner", 1, vec!(hdx, dai))?; - let filler: T::AccountId = create_account_with_balances::("filler", 2, vec!(hdx, dai))?; + let owner: T::AccountId = create_account_with_balances::("owner", 1, vec!(dot, dai))?; + let filler: T::AccountId = create_account_with_balances::("filler", 2, vec!(dot, dai))?; assert_ok!( - crate::Pallet::::place_order(RawOrigin::Signed(owner.clone()).into(), dai.into(), hdx.into(), 20 * ONE, 100 * ONE, true) + crate::Pallet::::place_order(RawOrigin::Signed(owner.clone()).into(), dai.into(), dot.into(), 20 * ONE, 100 * ONE, true) ); }: _(RawOrigin::Signed(filler.clone()), 0u32) verify { - assert_eq!(T::Currency::reserved_balance_named(&NAMED_RESERVE_ID, hdx.into(), &owner), 0); + assert_eq!(T::Currency::reserved_balance_named(&NAMED_RESERVE_ID, dot.into(), &owner), 0); } cancel_order { - let (hdx, dai) = seed_registry::()?; + let (dot, dai) = seed_registry::()?; - let owner: T::AccountId = create_account_with_balances::("owner", 1, vec!(hdx, dai))?; + let owner: T::AccountId = create_account_with_balances::("owner", 1, vec!(dot, dai))?; assert_ok!( - crate::Pallet::::place_order(RawOrigin::Signed(owner.clone()).into(), dai.into(), hdx.into(), 20 * ONE, 100 * ONE, true) + crate::Pallet::::place_order(RawOrigin::Signed(owner.clone()).into(), dai.into(), dot.into(), 20 * ONE, 100 * ONE, true) ); }: _(RawOrigin::Signed(owner.clone()), 0u32) verify { - assert_eq!(T::Currency::reserved_balance_named(&NAMED_RESERVE_ID, hdx.into(), &owner), 0); + assert_eq!(T::Currency::reserved_balance_named(&NAMED_RESERVE_ID, dot.into(), &owner), 0); } } @@ -86,29 +86,36 @@ where u32: From<::AssetId>, T::AssetRegistry: Create, { + use frame_support::storage::with_transaction; + use sp_runtime::TransactionOutcome; + // Register new asset in asset registry - let hdx = ::AssetRegistry::register_sufficient_asset( - None, - Some(&b"HDX".to_vec()), - AssetKind::Token, - ONE, - None, - None, - None, - None, - )?; - let dai = ::AssetRegistry::register_sufficient_asset( - None, - Some(&b"DAI".to_vec()), - AssetKind::Token, - ONE, - None, - None, - None, - None, - )?; - - Ok((hdx.into(), dai.into())) + let dot = with_transaction(|| { + TransactionOutcome::Commit(::AssetRegistry::register_sufficient_asset( + None, + Some(&b"DOT".to_vec()), + AssetKind::Token, + ONE, + None, + None, + None, + None, + )) + })?; + let dai = with_transaction(|| { + TransactionOutcome::Commit(::AssetRegistry::register_sufficient_asset( + None, + Some(&b"DAI".to_vec()), + AssetKind::Token, + ONE, + None, + None, + None, + None, + )) + })?; + + Ok((dot.into(), dai.into())) } fn create_account_with_balances( From decf0a49471567320e6489e8cc173b82a5e1d1b7 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 13 Nov 2023 14:50:12 +0100 Subject: [PATCH 61/93] pallet-omnipool-liquidity-mining: fix benchmarks and make clippy happy --- pallets/asset-registry/src/lib.rs | 4 +- .../asset-registry/src/tests/create_trait.rs | 32 ++++----- .../src/benchmarks.rs | 69 +++++++++++-------- pallets/otc/src/benchmarks.rs | 40 +++++------ 4 files changed, 77 insertions(+), 68 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index bcd053426..ee813f86e 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -661,11 +661,11 @@ impl Inspect for Pallet { } fn decimals(id: Self::AssetId) -> Option { - Self::assets(id).map_or(None, |a| a.decimals) + Self::assets(id).and_then(|a| a.decimals) } fn asset_type(id: Self::AssetId) -> Option { - Self::assets(id).map_or(None, |a| Some(a.asset_type.into())) + Self::assets(id).map(|a| a.asset_type.into()) } } diff --git a/pallets/asset-registry/src/tests/create_trait.rs b/pallets/asset-registry/src/tests/create_trait.rs index 507c8724e..706ddb4e5 100644 --- a/pallets/asset-registry/src/tests/create_trait.rs +++ b/pallets/asset-registry/src/tests/create_trait.rs @@ -29,10 +29,10 @@ fn register_asset_should_work() { //Act assert_ok!(>::register_asset( Some(asset_id), - Some(&name.clone()), + Some(&name), AssetKind::XYK, Some(ed), - Some(&symbol.clone()), + Some(&symbol), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), @@ -105,10 +105,10 @@ fn register_insufficient_asset_should_work() { assert_ok!( >::register_insufficient_asset( Some(asset_id), - Some(&name.clone()), + Some(&name), AssetKind::XYK, Some(ed), - Some(&symbol.clone()), + Some(&symbol), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), @@ -180,10 +180,10 @@ fn register_sufficient_asset_should_work() { //Act assert_ok!(>::register_sufficient_asset( Some(asset_id), - Some(&name.clone()), + Some(&name), AssetKind::XYK, ed, - Some(&symbol.clone()), + Some(&symbol), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), @@ -255,10 +255,10 @@ fn get_or_register_asset_should_register_asset_when_does_not_exists() { //Act assert_ok!( >::get_or_register_asset( - &name.clone(), + &name, AssetKind::XYK, Some(ed), - Some(&symbol.clone()), + Some(&symbol), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), @@ -344,12 +344,12 @@ fn get_or_register_asset_should_return_asset_id_when_asset_exists() { //Act assert_ok!( >::get_or_register_asset( - &name.clone(), + &name, AssetKind::XYK, Some(ed), - Some(&symbol.clone()), + Some(&symbol), Some(decimals), - Some(asset_location.clone()), + Some(asset_location), Some(xcm_rate_limit), is_sufficient ), @@ -361,7 +361,7 @@ fn get_or_register_asset_should_return_asset_id_when_asset_exists() { assert_eq!( Registry::assets(existing_asset_id), Some(AssetDetails { - name: bounded_name.clone(), + name: bounded_name, asset_type: AssetType::Token, existential_deposit: UNIT, xcm_rate_limit: None, @@ -393,10 +393,10 @@ fn get_or_register_sufficient_asset_should_work() { //Act assert_ok!( >::get_or_register_sufficient_asset( - &name.clone(), + &name, AssetKind::XYK, ed, - Some(&symbol.clone()), + Some(&symbol), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), @@ -468,10 +468,10 @@ fn get_or_register_insufficient_asset_should_work() { //Act assert_ok!( >::get_or_register_insufficient_asset( - &name.clone(), + &name, AssetKind::XYK, Some(ed), - Some(&symbol.clone()), + Some(&symbol), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), diff --git a/pallets/omnipool-liquidity-mining/src/benchmarks.rs b/pallets/omnipool-liquidity-mining/src/benchmarks.rs index f32e43225..3343bd839 100644 --- a/pallets/omnipool-liquidity-mining/src/benchmarks.rs +++ b/pallets/omnipool-liquidity-mining/src/benchmarks.rs @@ -17,12 +17,14 @@ use crate::*; use frame_benchmarking::{account, benchmarks}; +use frame_support::storage::with_transaction; use frame_support::traits::{OnFinalize, OnInitialize}; use frame_system::{Pallet as System, RawOrigin}; use hydradx_traits::registry::{AssetKind, Create}; use orml_traits::MultiCurrencyExtended; use pallet_liquidity_mining::Instance1; use primitives::AssetId; +use sp_runtime::TransactionOutcome; use sp_runtime::{traits::One, FixedU128, Permill}; const TVL_CAP: Balance = 222_222_000_000_000_000_000_000; @@ -106,6 +108,7 @@ where OmnipoolPallet::::set_tvl_cap(RawOrigin::Root.into(), TVL_CAP)?; + fund::(acc.clone(), HDX.into(), 10_000 * ONE)?; ::Currency::update_balance(T::StableCoinAssetId::get(), &acc, stable_amount as i128)?; ::Currency::update_balance(T::HdxAssetId::get(), &acc, native_amount as i128)?; @@ -118,36 +121,42 @@ where )?; // Register new asset in asset registry - T::AssetRegistry::register_sufficient_asset( - None, - Some(&b"BSX".to_vec()), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )?; - T::AssetRegistry::register_sufficient_asset( - None, - Some(&b"ETH".to_vec()), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )?; - T::AssetRegistry::register_sufficient_asset( - None, - Some(&b"BTC".to_vec()), - AssetKind::Token, - Balance::one(), - None, - None, - None, - None, - )?; + with_transaction(|| { + TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( + None, + Some(b"BSX".as_ref()), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + with_transaction(|| { + TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( + None, + Some(b"ETH".as_ref()), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; + with_transaction(|| { + TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( + None, + Some(b"BTC".as_ref()), + AssetKind::Token, + Balance::one(), + None, + None, + None, + None, + )) + })?; // Create account for token provider and set balance let owner: T::AccountId = account("owner", 0, 1); diff --git a/pallets/otc/src/benchmarks.rs b/pallets/otc/src/benchmarks.rs index 3bcb1c25d..661ee6d3c 100644 --- a/pallets/otc/src/benchmarks.rs +++ b/pallets/otc/src/benchmarks.rs @@ -92,28 +92,28 @@ where // Register new asset in asset registry let dot = with_transaction(|| { TransactionOutcome::Commit(::AssetRegistry::register_sufficient_asset( - None, - Some(&b"DOT".to_vec()), - AssetKind::Token, - ONE, - None, - None, - None, - None, - )) - })?; + None, + Some(b"DOT".as_ref()), + AssetKind::Token, + ONE, + None, + None, + None, + None, + )) + })?; let dai = with_transaction(|| { TransactionOutcome::Commit(::AssetRegistry::register_sufficient_asset( - None, - Some(&b"DAI".to_vec()), - AssetKind::Token, - ONE, - None, - None, - None, - None, - )) - })?; + None, + Some(b"DAI".as_ref()), + AssetKind::Token, + ONE, + None, + None, + None, + None, + )) + })?; Ok((dot.into(), dai.into())) } From b4a19e31285f76c5cf4f1659da42b60bba548f89 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 13 Nov 2023 15:32:45 +0100 Subject: [PATCH 62/93] traits: remove deprecated registry traits --- pallets/asset-registry/src/benchmarking.rs | 2 +- pallets/asset-registry/src/lib.rs | 14 +++--- pallets/asset-registry/src/migration.rs | 8 ++-- pallets/asset-registry/src/types.rs | 19 ++++---- traits/src/registry.rs | 55 ---------------------- 5 files changed, 20 insertions(+), 78 deletions(-) diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index 95804aea1..cfd364510 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -64,7 +64,7 @@ benchmarks! { let _ = Pallet::::register(RawOrigin::Root.into(), Some(asset_id), Some(name), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient); let new_name= vec![98u8; T::StringLimit::get() as usize]; - let new_type = AssetType::PoolShare(T::AssetId::from(10u8),T::AssetId::from(20u8)); + let new_type = AssetType::XYK; let new_ed = 1_000_000_u128; let new_xcm_rate_limit = 1_000_u128; let new_is_sufficient = false; diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index ee813f86e..c0e28a5be 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -62,7 +62,7 @@ pub mod pallet { use super::*; - pub type AssetDetailsT = AssetDetails<::AssetId, ::StringLimit>; + pub type AssetDetailsT = AssetDetails<::StringLimit>; #[pallet::config] pub trait Config: frame_system::Config { @@ -308,7 +308,7 @@ pub mod pallet { Registered { asset_id: T::AssetId, asset_name: Option>, - asset_type: AssetType, + asset_type: AssetType, existential_deposit: Balance, xcm_rate_limit: Option, symbol: Option>, @@ -320,7 +320,7 @@ pub mod pallet { Updated { asset_id: T::AssetId, asset_name: Option>, - asset_type: AssetType, + asset_type: AssetType, existential_deposit: Balance, xcm_rate_limit: Option, symbol: Option>, @@ -356,7 +356,7 @@ pub mod pallet { origin: OriginFor, asset_id: Option, name: Option>, - asset_type: AssetType, + asset_type: AssetType, existential_deposit: Option, symbol: Option>, decimals: Option, @@ -399,7 +399,7 @@ pub mod pallet { origin: OriginFor, asset_id: T::AssetId, name: Option>, - asset_type: Option>, + asset_type: Option, existential_deposit: Option, xcm_rate_limit: Option, is_sufficient: Option, @@ -535,7 +535,7 @@ impl Pallet { #[require_transactional] fn do_register_asset( selected_asset_id: Option, - details: &AssetDetails, + details: &AssetDetails, location: Option, ) -> Result { let asset_id = if let Some(id) = selected_asset_id { @@ -584,7 +584,7 @@ impl Pallet { /// Create asset for given name or return existing AssetId if such asset already exists. pub fn get_or_create_asset( name: Vec, - asset_type: AssetType, + asset_type: AssetType, existential_deposit: Balance, asset_id: Option, is_sufficient: bool, diff --git a/pallets/asset-registry/src/migration.rs b/pallets/asset-registry/src/migration.rs index b9db6dffb..2c2520e00 100644 --- a/pallets/asset-registry/src/migration.rs +++ b/pallets/asset-registry/src/migration.rs @@ -34,9 +34,9 @@ pub mod v1 { use sp_runtime::BoundedVec; #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, TypeInfo)] - pub struct AssetDetails { + pub struct AssetDetails { pub name: BoundedString, - pub asset_type: AssetType, + pub asset_type: AssetType, pub existential_deposit: Balance, pub xcm_rate_limit: Option, } @@ -52,7 +52,7 @@ pub mod v1 { Pallet, Twox64Concat, ::AssetId, - AssetDetails<::AssetId, Balance, BoundedVec::StringLimit>>, + AssetDetails::StringLimit>>, OptionQuery, >; @@ -101,7 +101,7 @@ pub mod v2 { let mut i = 0; let mut v2_assets_details = Vec::<( ::AssetId, - AssetDetails<::AssetId, ::StringLimit>, + AssetDetails<::StringLimit>, )>::new(); for (k, v) in v1::Assets::::iter() { i += 1; diff --git a/pallets/asset-registry/src/types.rs b/pallets/asset-registry/src/types.rs index 63e191e7f..434567a2d 100644 --- a/pallets/asset-registry/src/types.rs +++ b/pallets/asset-registry/src/types.rs @@ -26,17 +26,15 @@ use serde::{Deserialize, Serialize}; #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub enum AssetType { +pub enum AssetType { Token, - #[deprecated] - PoolShare(AssetId, AssetId), // Use XYX instead XYK, StableSwap, Bond, External, } -impl From for AssetType { +impl From for AssetType { fn from(value: AssetKind) -> Self { match value { AssetKind::Token => Self::Token, @@ -48,11 +46,10 @@ impl From for AssetType { } } -impl From> for AssetKind { - fn from(value: AssetType) -> Self { +impl From for AssetKind { + fn from(value: AssetType) -> Self { match value { AssetType::Token => Self::Token, - AssetType::PoolShare(_, _) => Self::XYK, AssetType::XYK => Self::XYK, AssetType::StableSwap => Self::StableSwap, AssetType::Bond => Self::Bond, @@ -64,12 +61,12 @@ impl From> for AssetKind { #[derive(Encode, Decode, Eq, PartialEq, Clone, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(StringLimit))] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub struct AssetDetails> { +pub struct AssetDetails> { /// The name of this asset. Limited in length by `StringLimit`. pub name: Option>, /// Asset type - pub asset_type: AssetType, + pub asset_type: AssetType, /// Existential deposit pub existential_deposit: Balance, @@ -87,10 +84,10 @@ pub struct AssetDetails> { pub is_sufficient: bool, } -impl> AssetDetails { +impl> AssetDetails { pub fn new( name: Option>, - asset_type: AssetType, + asset_type: AssetType, existential_deposit: Balance, symbol: Option>, decimals: Option, diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 7e400756c..5978a3cd3 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -1,54 +1,5 @@ use sp_std::vec::Vec; -#[deprecated(since = "3.0.0", note = "Please use `registry::Create` trait instead")] -pub trait Registry { - fn exists(name: AssetId) -> bool; - - fn retrieve_asset(name: &AssetName) -> Result; - - fn retrieve_asset_type(asset_id: AssetId) -> Result; - - fn create_asset(name: &AssetName, existential_deposit: Balance) -> Result; - - fn get_or_create_asset(name: AssetName, existential_deposit: Balance) -> Result { - if let Ok(asset_id) = Self::retrieve_asset(&name) { - Ok(asset_id) - } else { - Self::create_asset(&name, existential_deposit) - } - } -} - -// Use CreateRegistry if possible -#[deprecated(since = "3.0.0", note = "Please use `registry::Create` trait instead")] -pub trait ShareTokenRegistry: Registry { - fn retrieve_shared_asset(name: &AssetName, assets: &[AssetId]) -> Result; - - fn create_shared_asset( - name: &AssetName, - assets: &[AssetId], - existential_deposit: Balance, - ) -> Result; - - fn get_or_create_shared_asset( - name: AssetName, - assets: Vec, - existential_deposit: Balance, - ) -> Result { - if let Ok(asset_id) = Self::retrieve_shared_asset(&name, &assets) { - Ok(asset_id) - } else { - Self::create_shared_asset(&name, &assets, existential_deposit) - } - } -} - -#[deprecated(since = "3.0.0", note = "Please use `registry::Inspect` trait instead")] -pub trait InspectRegistry { - fn exists(asset_id: AssetId) -> bool; - fn decimals(asset_id: AssetId) -> Option; -} - #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub enum AssetKind { Token, @@ -58,12 +9,6 @@ pub enum AssetKind { External, } -#[deprecated(since = "3.0.0", note = "Please use `registry::Create` trait instead")] -pub trait CreateRegistry { - type Error; - fn create_asset(name: &[u8], kind: AssetKind, existential_deposit: Balance) -> Result; -} - // Deprecated. // TODO: the following macro is commented out for a reason for now - due to failing clippy in CI // #[deprecated(since = "0.6.0", note = "Please use `AccountIdFor` instead")] From 3ddb972857876a7c5984f73ebcaa3584bbda051e Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 14 Nov 2023 11:05:31 +0100 Subject: [PATCH 63/93] traits: make location associated type of Inspect trait + update all necessary code --- pallets/asset-registry/src/lib.rs | 9 +-- .../asset-registry/src/tests/create_trait.rs | 70 +++++++++---------- .../asset-registry/src/tests/mutate_trait.rs | 9 +-- pallets/bonds/src/lib.rs | 6 +- pallets/bonds/src/tests/mock.rs | 12 ++-- pallets/circuit-breaker/src/tests/mock.rs | 1 + pallets/dca/src/tests/mock.rs | 1 + pallets/liquidity-mining/src/tests/mock.rs | 1 + .../src/benchmarks.rs | 5 +- pallets/omnipool-liquidity-mining/src/lib.rs | 4 -- .../src/tests/mock.rs | 10 ++- pallets/omnipool/src/tests/mock.rs | 1 + pallets/otc/src/benchmarks.rs | 4 +- pallets/otc/src/lib.rs | 4 -- pallets/otc/src/tests/mock.rs | 10 ++- pallets/stableswap/src/tests/mock.rs | 1 + pallets/xcm-rate-limiter/src/tests/mock.rs | 1 + pallets/xyk/src/lib.rs | 5 +- pallets/xyk/src/tests/mock.rs | 4 +- runtime/adapters/src/tests/mock.rs | 1 + runtime/hydradx/src/assets.rs | 8 --- traits/src/registry.rs | 19 ++--- 22 files changed, 78 insertions(+), 108 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index c0e28a5be..c81ce8db1 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -648,6 +648,7 @@ impl GetByKey> for XcmRateLimitsInRegistr impl Inspect for Pallet { type AssetId = T::AssetId; + type Location = T::AssetNativeLocation; fn is_sufficient(id: Self::AssetId) -> bool { match Self::assets(id) { @@ -669,7 +670,7 @@ impl Inspect for Pallet { } } -impl Mutate for Pallet { +impl Mutate for Pallet { type Error = DispatchError; fn set_location(asset_id: Self::AssetId, location: T::AssetNativeLocation) -> Result<(), Self::Error> { @@ -679,7 +680,7 @@ impl Mutate for Pallet { } } -impl Create for Pallet { +impl Create for Pallet { type Error = DispatchError; fn register_asset( @@ -689,7 +690,7 @@ impl Create for Pallet { existential_deposit: Option, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, is_sufficient: bool, ) -> Result { @@ -715,7 +716,7 @@ impl Create for Pallet { existential_deposit: Option, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, is_sufficient: bool, ) -> Result { diff --git a/pallets/asset-registry/src/tests/create_trait.rs b/pallets/asset-registry/src/tests/create_trait.rs index 706ddb4e5..0e00f17ca 100644 --- a/pallets/asset-registry/src/tests/create_trait.rs +++ b/pallets/asset-registry/src/tests/create_trait.rs @@ -27,7 +27,7 @@ fn register_asset_should_work() { let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); //Act - assert_ok!(>::register_asset( + assert_ok!(>::register_asset( Some(asset_id), Some(&name), AssetKind::XYK, @@ -102,18 +102,16 @@ fn register_insufficient_asset_should_work() { let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); //Act - assert_ok!( - >::register_insufficient_asset( - Some(asset_id), - Some(&name), - AssetKind::XYK, - Some(ed), - Some(&symbol), - Some(decimals), - Some(asset_location.clone()), - Some(xcm_rate_limit), - ) - ); + assert_ok!(>::register_insufficient_asset( + Some(asset_id), + Some(&name), + AssetKind::XYK, + Some(ed), + Some(&symbol), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + )); //Assert let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); @@ -178,7 +176,7 @@ fn register_sufficient_asset_should_work() { let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); //Act - assert_ok!(>::register_sufficient_asset( + assert_ok!(>::register_sufficient_asset( Some(asset_id), Some(&name), AssetKind::XYK, @@ -254,7 +252,7 @@ fn get_or_register_asset_should_register_asset_when_does_not_exists() { //Act assert_ok!( - >::get_or_register_asset( + >::get_or_register_asset( &name, AssetKind::XYK, Some(ed), @@ -343,7 +341,7 @@ fn get_or_register_asset_should_return_asset_id_when_asset_exists() { //Act assert_ok!( - >::get_or_register_asset( + >::get_or_register_asset( &name, AssetKind::XYK, Some(ed), @@ -391,17 +389,15 @@ fn get_or_register_sufficient_asset_should_work() { let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); //Act - assert_ok!( - >::get_or_register_sufficient_asset( - &name, - AssetKind::XYK, - ed, - Some(&symbol), - Some(decimals), - Some(asset_location.clone()), - Some(xcm_rate_limit), - ), - ); + assert_ok!(>::get_or_register_sufficient_asset( + &name, + AssetKind::XYK, + ed, + Some(&symbol), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + ),); //Assert let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); @@ -466,17 +462,15 @@ fn get_or_register_insufficient_asset_should_work() { let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); //Act - assert_ok!( - >::get_or_register_insufficient_asset( - &name, - AssetKind::XYK, - Some(ed), - Some(&symbol), - Some(decimals), - Some(asset_location.clone()), - Some(xcm_rate_limit), - ), - ); + assert_ok!(>::get_or_register_insufficient_asset( + &name, + AssetKind::XYK, + Some(ed), + Some(&symbol), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + ),); //Assert let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); diff --git a/pallets/asset-registry/src/tests/mutate_trait.rs b/pallets/asset-registry/src/tests/mutate_trait.rs index b84c16b51..0477fe167 100644 --- a/pallets/asset-registry/src/tests/mutate_trait.rs +++ b/pallets/asset-registry/src/tests/mutate_trait.rs @@ -29,10 +29,7 @@ fn set_location_should_work_when_location_was_not_set_yet() { assert_eq!(Registry::locations(asset_id), None); //Act - assert_ok!(>::set_location( - asset_id, - location.clone() - )); + assert_ok!(::set_location(asset_id, location.clone())); //Assert assert_eq!(Registry::location_assets(location.clone()), Some(asset_id)); @@ -62,7 +59,7 @@ fn set_location_should_not_work_when_location_was_not() { //Act assert_noop!( - >::set_location(asset_id, location), + ::set_location(asset_id, location), Error::::LocationAlreadyRegistered ); }); @@ -78,7 +75,7 @@ fn set_location_should_not_work_when_asset_does_not_exists() { //Act assert_noop!( - >::set_location(non_existing_id, location), + ::set_location(non_existing_id, location), Error::::AssetNotFound ); }); diff --git a/pallets/bonds/src/lib.rs b/pallets/bonds/src/lib.rs index ca75526a4..2d43e271c 100644 --- a/pallets/bonds/src/lib.rs +++ b/pallets/bonds/src/lib.rs @@ -104,8 +104,7 @@ pub mod pallet { type Currency: MultiCurrency; /// Asset Registry mechanism - used to register bonds in the asset registry. - type AssetRegistry: Inspect - + Create; + type AssetRegistry: Inspect + Create; /// Provider for existential deposits of assets. type ExistentialDeposits: GetByKey; @@ -131,9 +130,6 @@ pub mod pallet { #[pallet::constant] type FeeReceiver: Get; - /// Asset location type - type AssetLocation: Parameter + Member + Default + MaxEncodedLen; - /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } diff --git a/pallets/bonds/src/tests/mock.rs b/pallets/bonds/src/tests/mock.rs index 374afd05f..9f6eedeca 100644 --- a/pallets/bonds/src/tests/mock.rs +++ b/pallets/bonds/src/tests/mock.rs @@ -105,7 +105,7 @@ impl Contains for AssetTypeWhitelist { } } -impl Config for Test { +impl pallet_bonds::Config for Test { type RuntimeEvent = RuntimeEvent; type Balance = Balance; type Currency = Tokens; @@ -117,7 +117,6 @@ impl Config for Test { type AssetTypeWhitelist = AssetTypeWhitelist; type ProtocolFee = ProtocolFee; type FeeReceiver = TreasuryAccount; - type AssetLocation = AssetLocation; type WeightInfo = (); } @@ -175,7 +174,7 @@ impl pallet_timestamp::Config for Test { pub struct DummyRegistry(sp_std::marker::PhantomData); -impl Create for DummyRegistry { +impl Create for DummyRegistry { type Error = DispatchError; fn register_asset( @@ -185,7 +184,7 @@ impl Create for DummyRegistry { _existential_deposit: Option, _symbol: Option<&[u8]>, _decimals: Option, - _location: Option, + _location: Option, _xcm_rate_limit: Option, _is_sufficient: bool, ) -> Result { @@ -199,7 +198,7 @@ impl Create for DummyRegistry { existential_deposit: Option, _symbol: Option<&[u8]>, _decimals: Option, - _location: Option, + _location: Option, _xcm_rate_limit: Option, ) -> Result { let assigned = REGISTERED_ASSETS.with(|v| { @@ -216,7 +215,7 @@ impl Create for DummyRegistry { _existential_deposit: Option, _symbol: Option<&[u8]>, _decimals: Option, - _location: Option, + _location: Option, _xcm_rate_limit: Option, _is_sufficient: bool, ) -> Result { @@ -226,6 +225,7 @@ impl Create for DummyRegistry { impl Inspect for DummyRegistry { type AssetId = AssetId; + type Location = AssetLocation; fn is_sufficient(_id: Self::AssetId) -> bool { unimplemented!() diff --git a/pallets/circuit-breaker/src/tests/mock.rs b/pallets/circuit-breaker/src/tests/mock.rs index efefa78d5..6d1035868 100644 --- a/pallets/circuit-breaker/src/tests/mock.rs +++ b/pallets/circuit-breaker/src/tests/mock.rs @@ -373,6 +373,7 @@ where T::AssetId: Into + From, { type AssetId = T::AssetId; + type Location = u8; fn is_sufficient(_id: Self::AssetId) -> bool { unimplemented!() diff --git a/pallets/dca/src/tests/mock.rs b/pallets/dca/src/tests/mock.rs index ed52a1168..e31a25c33 100644 --- a/pallets/dca/src/tests/mock.rs +++ b/pallets/dca/src/tests/mock.rs @@ -721,6 +721,7 @@ where T::AssetId: Into + From, { type AssetId = T::AssetId; + type Location = u8; fn asset_type(_id: Self::AssetId) -> Option { unimplemented!() diff --git a/pallets/liquidity-mining/src/tests/mock.rs b/pallets/liquidity-mining/src/tests/mock.rs index 270ff6715..356a0dd0e 100644 --- a/pallets/liquidity-mining/src/tests/mock.rs +++ b/pallets/liquidity-mining/src/tests/mock.rs @@ -433,6 +433,7 @@ pub struct DummyRegistry; impl Inspect for DummyRegistry { type AssetId = AssetId; + type Location = u8; fn is_sufficient(_id: Self::AssetId) -> bool { unimplemented!() diff --git a/pallets/omnipool-liquidity-mining/src/benchmarks.rs b/pallets/omnipool-liquidity-mining/src/benchmarks.rs index 3343bd839..bcd7f299a 100644 --- a/pallets/omnipool-liquidity-mining/src/benchmarks.rs +++ b/pallets/omnipool-liquidity-mining/src/benchmarks.rs @@ -96,8 +96,7 @@ where ::Currency: MultiCurrencyExtended, T: pallet_ema_oracle::Config, T::AssetId: From, - ::AssetRegistry: - Create, + ::AssetRegistry: Create, <::AssetRegistry as hydradx_traits::Inspect>::AssetId: From, { let stable_amount: Balance = 1_000_000_000_000_000_u128; @@ -267,7 +266,7 @@ benchmarks! { ::AssetId: From, ::Currency: MultiCurrencyExtended, T: crate::pallet::Config + pallet_ema_oracle::Config + pallet_liquidity_mining::Config, - ::AssetRegistry: Create::AssetId>, + ::AssetRegistry: Create::AssetId>, } create_global_farm { diff --git a/pallets/omnipool-liquidity-mining/src/lib.rs b/pallets/omnipool-liquidity-mining/src/lib.rs index 43385fa8a..49662556a 100644 --- a/pallets/omnipool-liquidity-mining/src/lib.rs +++ b/pallets/omnipool-liquidity-mining/src/lib.rs @@ -153,10 +153,6 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; - - #[cfg(feature = "runtime-benchmarks")] - /// Asset location type - type AssetLocation: Parameter + Member + Default + MaxEncodedLen; } #[pallet::storage] diff --git a/pallets/omnipool-liquidity-mining/src/tests/mock.rs b/pallets/omnipool-liquidity-mining/src/tests/mock.rs index f83373f09..2fe4bf781 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mock.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mock.rs @@ -181,9 +181,6 @@ impl omnipool_liquidity_mining::Config for Test { type OraclePeriod = PeriodOracle; type PriceOracle = DummyOracle; type WeightInfo = (); - - #[cfg(feature = "runtime-benchmarks")] - type AssetLocation = u8; } parameter_types! { @@ -648,6 +645,7 @@ where T::AssetId: Into + From, { type AssetId = T::AssetId; + type Location = u8; fn is_sufficient(_id: Self::AssetId) -> bool { unimplemented!() @@ -670,7 +668,7 @@ where #[cfg(feature = "runtime-benchmarks")] use hydradx_traits::Create as CreateRegistry; #[cfg(feature = "runtime-benchmarks")] -impl CreateRegistry for DummyRegistry +impl CreateRegistry for DummyRegistry where T::AssetId: Into + From, { @@ -683,7 +681,7 @@ where _existential_deposit: Option, _symbol: Option<&[u8]>, _decimals: Option, - _location: Option, + _location: Option, _xcm_rate_limit: Option, _is_sufficient: bool, ) -> Result { @@ -706,7 +704,7 @@ where _existential_deposit: Option, _symbol: Option<&[u8]>, _decimals: Option, - _location: Option, + _location: Option, _xcm_rate_limit: Option, _is_sufficient: bool, ) -> Result { diff --git a/pallets/omnipool/src/tests/mock.rs b/pallets/omnipool/src/tests/mock.rs index f6e6b85e0..ccbcb7119 100644 --- a/pallets/omnipool/src/tests/mock.rs +++ b/pallets/omnipool/src/tests/mock.rs @@ -520,6 +520,7 @@ where T::AssetId: Into + From, { type AssetId = T::AssetId; + type Location = u8; fn is_sufficient(_id: Self::AssetId) -> bool { unimplemented!() diff --git a/pallets/otc/src/benchmarks.rs b/pallets/otc/src/benchmarks.rs index 661ee6d3c..19901ea9b 100644 --- a/pallets/otc/src/benchmarks.rs +++ b/pallets/otc/src/benchmarks.rs @@ -29,7 +29,7 @@ benchmarks! { T::Currency: MultiCurrencyExtended, T: crate::pallet::Config, u32: From<::AssetId>, - T::AssetRegistry: Create + T::AssetRegistry: Create } place_order { let (dot, dai) = seed_registry::()?; @@ -84,7 +84,7 @@ benchmarks! { fn seed_registry() -> Result<(u32, u32), DispatchError> where u32: From<::AssetId>, - T::AssetRegistry: Create, + T::AssetRegistry: Create, { use frame_support::storage::with_transaction; use sp_runtime::TransactionOutcome; diff --git a/pallets/otc/src/lib.rs b/pallets/otc/src/lib.rs index 852cfe5f4..09cd45333 100644 --- a/pallets/otc/src/lib.rs +++ b/pallets/otc/src/lib.rs @@ -104,10 +104,6 @@ pub mod pallet { /// Weight information for the extrinsics. type WeightInfo: WeightInfo; - - #[cfg(feature = "runtime-benchmarks")] - /// Asset location type - type AssetLocation: Parameter + Member + Default + MaxEncodedLen; } #[pallet::event] diff --git a/pallets/otc/src/tests/mock.rs b/pallets/otc/src/tests/mock.rs index 9f3fe658d..e86a35108 100644 --- a/pallets/otc/src/tests/mock.rs +++ b/pallets/otc/src/tests/mock.rs @@ -86,9 +86,6 @@ impl otc::Config for Test { type ExistentialDeposits = ExistentialDeposits; type ExistentialDepositMultiplier = ExistentialDepositMultiplier; type WeightInfo = (); - - #[cfg(feature = "runtime-benchmarks")] - type AssetLocation = u8; } parameter_types! { @@ -142,6 +139,7 @@ pub struct DummyRegistry(sp_std::marker::PhantomData); impl Inspect for DummyRegistry { type AssetId = AssetId; + type Location = u8; fn asset_type(_id: Self::AssetId) -> Option { unimplemented!() @@ -166,7 +164,7 @@ use hydradx_traits::Create as CreateRegistry; #[cfg(feature = "runtime-benchmarks")] use sp_runtime::DispatchError; #[cfg(feature = "runtime-benchmarks")] -impl CreateRegistry for DummyRegistry +impl CreateRegistry for DummyRegistry where T::AssetId: Into + From, { @@ -179,7 +177,7 @@ where _existential_deposit: Option, _symbol: Option<&[u8]>, _decimals: Option, - _location: Option, + _location: Option, _xcm_rate_limit: Option, _is_sufficient: bool, ) -> Result { @@ -202,7 +200,7 @@ where _existential_deposit: Option, _symbol: Option<&[u8]>, _decimals: Option, - _location: Option, + _location: Option, _xcm_rate_limit: Option, _is_sufficient: bool, ) -> Result { diff --git a/pallets/stableswap/src/tests/mock.rs b/pallets/stableswap/src/tests/mock.rs index 9d6f15635..5de7148cf 100644 --- a/pallets/stableswap/src/tests/mock.rs +++ b/pallets/stableswap/src/tests/mock.rs @@ -318,6 +318,7 @@ pub struct DummyRegistry; impl Inspect for DummyRegistry { type AssetId = AssetId; + type Location = u8; fn exists(asset_id: AssetId) -> bool { let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&asset_id).copied()); diff --git a/pallets/xcm-rate-limiter/src/tests/mock.rs b/pallets/xcm-rate-limiter/src/tests/mock.rs index fb2e324d7..89475ca18 100644 --- a/pallets/xcm-rate-limiter/src/tests/mock.rs +++ b/pallets/xcm-rate-limiter/src/tests/mock.rs @@ -319,6 +319,7 @@ where T::AssetId: Into + From, { type AssetId = T::AssetId; + type Location = MultiLocation; fn is_sufficient(_id: Self::AssetId) -> bool { unimplemented!() diff --git a/pallets/xyk/src/lib.rs b/pallets/xyk/src/lib.rs index cdb521410..9fbfedf59 100644 --- a/pallets/xyk/src/lib.rs +++ b/pallets/xyk/src/lib.rs @@ -80,7 +80,7 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Registry support - type AssetRegistry: Create; + type AssetRegistry: Create; /// Share token support type AssetPairAccountId: AssetPairAccountIdFor; @@ -132,9 +132,6 @@ pub mod pallet { /// Account whitelist manager to exclude pool accounts from dusting mechanism. type NonDustableWhitelistHandler: DustRemovalAccountWhitelist; - - /// Asset location type - type AssetLocation: Parameter + Member + Default + MaxEncodedLen; } #[pallet::error] diff --git a/pallets/xyk/src/tests/mock.rs b/pallets/xyk/src/tests/mock.rs index 6c66a04d4..22e59f666 100644 --- a/pallets/xyk/src/tests/mock.rs +++ b/pallets/xyk/src/tests/mock.rs @@ -16,7 +16,6 @@ // limitations under the License. use crate as xyk; -use crate::Config; use crate::*; use frame_support::parameter_types; use frame_system as system; @@ -201,7 +200,7 @@ impl CanCreatePool for Disallow10_10Pool { } } -impl Config for Test { +impl xyk::Config for Test { type RuntimeEvent = RuntimeEvent; type AssetRegistry = AssetRegistry; type AssetPairAccountId = AssetPairAccountIdTest; @@ -218,7 +217,6 @@ impl Config for Test { type DiscountedFee = DiscountedFeeRate; type NonDustableWhitelistHandler = Whitelist; type OracleSource = OracleSourceIdentifier; - type AssetLocation = AssetLocation; } pub struct ExtBuilder { diff --git a/runtime/adapters/src/tests/mock.rs b/runtime/adapters/src/tests/mock.rs index 3b3849ccf..077e288ad 100644 --- a/runtime/adapters/src/tests/mock.rs +++ b/runtime/adapters/src/tests/mock.rs @@ -543,6 +543,7 @@ where T::AssetId: Into + From, { type AssetId = AssetId; + type Location = u8; fn asset_type(_id: Self::AssetId) -> Option { unimplemented!() diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index c20f77c20..cbf978a0c 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -560,9 +560,6 @@ impl pallet_omnipool_liquidity_mining::Config for Runtime { type OraclePeriod = OmnipoolLMOraclePeriod; type PriceOracle = EmaOracle; type WeightInfo = weights::omnipool_lm::HydraWeight; - - #[cfg(feature = "runtime-benchmarks")] - type AssetLocation = AssetLocation; } // The reason why there is difference between PROD and benchmark is that it is not possible @@ -862,9 +859,6 @@ impl pallet_otc::Config for Runtime { type ExistentialDeposits = AssetRegistry; type ExistentialDepositMultiplier = ExistentialDepositMultiplier; type WeightInfo = weights::otc::HydraWeight; - - #[cfg(feature = "runtime-benchmarks")] - type AssetLocation = AssetLocation; } // Dynamic fees @@ -991,7 +985,6 @@ impl pallet_bonds::Config for Runtime { type AssetTypeWhitelist = AssetTypeWhitelist; type ProtocolFee = ProtocolFee; type FeeReceiver = TreasuryAccount; - type AssetLocation = AssetLocation; type WeightInfo = weights::bonds::HydraWeight; } @@ -1107,5 +1100,4 @@ impl pallet_xyk::Config for Runtime { type DiscountedFee = DiscountedFee; type NonDustableWhitelistHandler = Duster; type OracleSource = XYKOracleSourceIdentifier; - type AssetLocation = AssetLocation; } diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 5978a3cd3..9851a05a7 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -31,6 +31,7 @@ use frame_support::dispatch::Parameter; pub trait Inspect { type AssetId: Parameter; + type Location: Parameter; fn is_sufficient(id: Self::AssetId) -> bool; @@ -42,7 +43,7 @@ pub trait Inspect { } #[allow(clippy::too_many_arguments)] -pub trait Create: Inspect { +pub trait Create: Inspect { type Error; fn register_asset( @@ -52,7 +53,7 @@ pub trait Create: Inspect { existential_deposit: Option, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, is_sufficient: bool, ) -> Result; @@ -64,7 +65,7 @@ pub trait Create: Inspect { existential_deposit: Option, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, ) -> Result { Self::register_asset( @@ -87,7 +88,7 @@ pub trait Create: Inspect { existential_deposit: Balance, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, ) -> Result { Self::register_asset( @@ -109,7 +110,7 @@ pub trait Create: Inspect { existential_deposit: Option, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, is_sufficient: bool, ) -> Result; @@ -120,7 +121,7 @@ pub trait Create: Inspect { existential_deposit: Balance, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, ) -> Result { Self::get_or_register_asset( @@ -141,7 +142,7 @@ pub trait Create: Inspect { existential_deposit: Option, symbol: Option<&[u8]>, decimals: Option, - location: Option, + location: Option, xcm_rate_limit: Option, ) -> Result { Self::get_or_register_asset( @@ -157,9 +158,9 @@ pub trait Create: Inspect { } } -pub trait Mutate: Inspect { +pub trait Mutate: Inspect { type Error; /// Set location for existing asset id if it wasn't set yet. - fn set_location(asset_id: Self::AssetId, location: Location) -> Result<(), Self::Error>; + fn set_location(asset_id: Self::AssetId, location: Self::Location) -> Result<(), Self::Error>; } From f0e4412cc6358c60247ba40f08e83a8b96f13aa6 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 14 Nov 2023 15:37:54 +0100 Subject: [PATCH 64/93] fix PR comments --- .../src/insufficient_assets_ed.rs | 56 +++++++++---------- pallets/asset-registry/src/benchmarking.rs | 6 +- pallets/asset-registry/src/lib.rs | 55 ++++++++++++------ pallets/asset-registry/src/tests/register.rs | 13 +++-- pallets/xyk/src/benchmarking.rs | 2 +- runtime/hydradx/src/assets.rs | 2 +- .../src/benchmarking/route_executor.rs | 3 +- 7 files changed, 80 insertions(+), 57 deletions(-) diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index 9eb574d6f..51ab7224e 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -20,7 +20,7 @@ use xcm_emulator::TestExt; fn sender_should_pay_ed_in_hdx_when_it_is_not_whitelisted() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_external_asset(0_u128); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), BOB.into(), @@ -79,7 +79,7 @@ fn sender_should_pay_ed_in_hdx_when_it_is_not_whitelisted() { fn reciever_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_external_asset(0_u128); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), BOB.into(), @@ -131,7 +131,7 @@ fn reciever_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted() { fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_hdx() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_external_asset(0_u128); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), BOB.into(), @@ -189,7 +189,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_hdx() { fn sender_should_pay_ed_only_when_dest_didnt_pay_yet() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_external_asset(0_u128); let fee_asset = BTC; assert_ok!(Tokens::set_balance( @@ -273,7 +273,7 @@ fn sender_should_pay_ed_only_when_dest_didnt_pay_yet() { fn dest_should_pay_ed_only_once_when_insufficient_asset_was_depsitted() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_external_asset(0_u128); let fee_asset = BTC; assert_ok!(Tokens::set_balance( @@ -341,7 +341,7 @@ fn dest_should_pay_ed_only_once_when_insufficient_asset_was_depsitted() { fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_external_asset(0_u128); let fee_asset = BTC; //NOTE: this is important for this tests - it basically mean that Bob already paid ED. @@ -425,7 +425,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset fn tx_should_fail_with_existential_deposit_err_when_dest_account_cant_pay_ed() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_external_asset(0_u128); let fee_asset = BTC; assert_ok!(MultiTransactionPayment::set_currency( @@ -449,7 +449,7 @@ fn tx_should_fail_with_existential_deposit_err_when_dest_account_cant_pay_ed() { fn sender_should_pay_ed_in_fee_asset_when_sending_insufficient_asset() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_external_asset(0_u128); let fee_asset = BTC; assert_ok!(Tokens::set_balance( @@ -591,7 +591,7 @@ fn grandfathered_account_should_receive_hdx_when_account_is_killed() { fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() { TestNet::reset(); Hydra::execute_with(|| { - let sht1 = register_shitcoin(0_u128); + let sht1 = register_external_asset(0_u128); let sufficient_asset = DAI; //This pays ED. @@ -672,7 +672,7 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() fn ed_should_not_be_released_when_sufficient_asset_killed_account() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_external_asset(0_u128); let sufficient_asset = DAI; //This pays ED. @@ -735,10 +735,10 @@ fn ed_should_not_be_released_when_sufficient_asset_killed_account() { fn ed_should_be_collected_for_each_insufficient_asset_when_transfered_or_depositted() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); - let sht2: AssetId = register_shitcoin(1_u128); - let sht3: AssetId = register_shitcoin(2_u128); - let sht4: AssetId = register_shitcoin(3_u128); + let sht1: AssetId = register_external_asset(0_u128); + let sht2: AssetId = register_external_asset(1_u128); + let sht3: AssetId = register_external_asset(2_u128); + let sht4: AssetId = register_external_asset(3_u128); let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let bob_hdx_balance = Currencies::free_balance(HDX, &BOB.into()); @@ -841,10 +841,10 @@ fn ed_should_be_collected_for_each_insufficient_asset_when_transfered_or_deposit fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); - let sht2: AssetId = register_shitcoin(1_u128); - let sht3: AssetId = register_shitcoin(2_u128); - let sht4: AssetId = register_shitcoin(3_u128); + let sht1: AssetId = register_external_asset(0_u128); + let sht2: AssetId = register_external_asset(1_u128); + let sht3: AssetId = register_external_asset(2_u128); + let sht4: AssetId = register_external_asset(3_u128); //so bob doesn't pay ed assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), BOB.into(), sht1, 1, 0)); @@ -968,10 +968,10 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); - let sht2: AssetId = register_shitcoin(1_u128); - let sht3: AssetId = register_shitcoin(2_u128); - let sht4: AssetId = register_shitcoin(3_u128); + let sht1: AssetId = register_external_asset(0_u128); + let sht2: AssetId = register_external_asset(1_u128); + let sht3: AssetId = register_external_asset(2_u128); + let sht4: AssetId = register_external_asset(3_u128); //so bob doesn't pay ed assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), BOB.into(), sht1, 1, 0)); @@ -1143,8 +1143,8 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { fn sender_should_pay_ed_when_tranferred_or_deposited_to_whitelisted_dest() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); - let sht2: AssetId = register_shitcoin(1_u128); + let sht1: AssetId = register_external_asset(0_u128); + let sht2: AssetId = register_external_asset(1_u128); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), @@ -1226,7 +1226,7 @@ fn sender_should_pay_ed_when_tranferred_or_deposited_to_whitelisted_dest() { fn ed_should_be_released_when_whitelisted_account_was_killed() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); + let sht1: AssetId = register_external_asset(0_u128); let treasury = TreasuryAccount::get(); assert_ok!(Tokens::set_balance( @@ -1292,8 +1292,8 @@ fn ed_should_be_released_when_whitelisted_account_was_killed() { fn tx_should_fail_with_unsupported_currency_error_when_fee_asset_price_wasn_not_provided() { TestNet::reset(); Hydra::execute_with(|| { - let sht1: AssetId = register_shitcoin(0_u128); - let sht2: AssetId = register_shitcoin(1_u128); + let sht1: AssetId = register_external_asset(0_u128); + let sht2: AssetId = register_external_asset(1_u128); let fee_asset = BTC; assert_ok!(Tokens::set_balance( @@ -1335,7 +1335,7 @@ fn tx_should_fail_with_unsupported_currency_error_when_fee_asset_price_wasn_not_ }); } -fn register_shitcoin(general_index: u128) -> AssetId { +fn register_external_asset(general_index: u128) -> AssetId { let location = hydradx_runtime::AssetLocation(MultiLocation::new( 1, X2(Parachain(MOONBEAM_PARA_ID), GeneralIndex(general_index)), diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index 95804aea1..8f9f650e5 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -21,15 +21,15 @@ use super::*; use crate::types::AssetDetails; use frame_benchmarking::{account, benchmarks}; +use frame_support::traits::tokens::fungibles::Mutate as FungiblesMutate; use frame_system::RawOrigin; -use orml_traits::MultiCurrencyExtended; use sp_std::vec; const UNIT: u128 = 1_000_000_000_000; benchmarks! { where_clause { where - T::Currency: MultiCurrencyExtended, + T::Currency: FungiblesMutate, T: crate::pallet::Config, } @@ -92,7 +92,7 @@ benchmarks! { register_external { let caller: T::AccountId = account("caller", 0, 1); - T::Currency::update_balance(T::StorageFeesAssetId::get(), &caller, (100_000 * UNIT) as i128)?; + T::Currency::mint_into(T::StorageFeesAssetId::get(), &caller, 101_000 * UNIT)?; let expected_asset_id = Pallet::::next_asset_id().unwrap(); let location: T::AssetNativeLocation = Default::default(); diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index be34a5af6..57a1ca6d5 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -19,9 +19,9 @@ use frame_support::pallet_prelude::*; use frame_support::sp_runtime::traits::CheckedAdd; +use frame_support::traits::tokens::fungibles::{Inspect as FungiblesInspect, Transfer}; use frame_support::{dispatch::DispatchError, require_transactional}; use frame_system::pallet_prelude::*; -use orml_traits::MultiCurrency; use scale_info::TypeInfo; use sp_arithmetic::traits::{BaseArithmetic, Zero}; use sp_std::convert::TryInto; @@ -88,7 +88,8 @@ pub mod pallet { type AssetNativeLocation: Parameter + Member + Default + MaxEncodedLen; /// Multi currency mechanism - type Currency: MultiCurrency; + type Currency: FungiblesInspect + + Transfer; #[pallet::constant] type SequentialIdStartAt: Get; @@ -157,6 +158,23 @@ pub mod pallet { //NOTE: This error is triggered from `SufficiencyCheck`. /// Existential deposit can't be zero. ZeroExistentialDeposit, + + /// Action cannot be completed because unexpected error has occurred. This should be reported + /// to protocol maintainers. + InconsistentState(InconsistentStateError), + } + + // NOTE: these errors should never happen. + #[derive(Encode, Decode, Eq, PartialEq, TypeInfo, frame_support::PalletError, RuntimeDebug)] + pub enum InconsistentStateError { + /// Name or symbol conversion to bounded string failed. + BoundedConversionFailed, + } + + impl From for Error { + fn from(e: InconsistentStateError) -> Error { + Error::::InconsistentState(e) + } } #[pallet::type_value] @@ -232,7 +250,7 @@ pub mod pallet { #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { - let _ = with_transaction(|| { + with_transaction(|| { // Register native asset first // It is to make sure that native is registered as any other asset let native_asset_name = Pallet::::try_into_bounded(Some(self.native_asset_name.to_vec())) @@ -285,7 +303,8 @@ pub mod pallet { ); TransactionOutcome::Commit(DispatchResult::Ok(())) - }); + }) + .expect("Genesis build failed.") } } @@ -475,7 +494,9 @@ pub mod pallet { if !T::StorageFees::get().is_zero() { ensure!( - T::Currency::ensure_can_withdraw(T::StorageFeesAssetId::get(), &who, T::StorageFees::get()).is_ok(), + T::Currency::can_withdraw(T::StorageFeesAssetId::get(), &who, T::StorageFees::get()) + .into_result() + .is_ok(), Error::::InsufficientBalance ); @@ -484,6 +505,7 @@ pub mod pallet { &who, &T::StorageFeesBeneficiary::get(), T::StorageFees::get(), + false, )?; } @@ -505,13 +527,11 @@ impl Pallet { /// Convert Vec to BoundedVec so it respects the max set limit, otherwise return TooLong error fn try_into_bounded(name: Option>) -> Result>, Error> { - if let Some(name) = name { - TryInto::>::try_into(name) - .map_err(|_| Error::::TooLong) - .map(Some) - } else { - Ok(None) - } + let Some(s) = name else { + return Ok(None); + }; + + s.try_into().map_err(|_| Error::::TooLong).map(Some) } fn do_set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { @@ -587,8 +607,11 @@ impl Pallet { ) -> Result { let bounded_name = Self::try_into_bounded(Some(name))?; - //NOTE: this unwrap is safe. - if let Some(asset_id) = AssetIds::::get(bounded_name.as_ref().unwrap()) { + if let Some(asset_id) = AssetIds::::get( + bounded_name + .as_ref() + .ok_or_else(|| -> pallet::Error { InconsistentStateError::BoundedConversionFailed.into() })?, + ) { Ok(asset_id) } else { Self::do_register_asset( @@ -624,8 +647,8 @@ impl Registry, Balance, DispatchError> for Pallet } fn retrieve_asset(name: &Vec) -> Result { - //NOTE: This unwrap is safe. - let bounded_name = Self::try_into_bounded(Some(name.clone()))?.unwrap(); + let bounded_name = Self::try_into_bounded(Some(name.clone()))? + .ok_or_else(|| -> pallet::Error { InconsistentStateError::BoundedConversionFailed.into() })?; if let Some(asset_id) = AssetIds::::get(bounded_name) { Ok(asset_id) } else { diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index 766af4159..b5bcfbba2 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -2,6 +2,7 @@ use super::*; use crate::types::AssetType; use frame_support::error::BadOrigin; +use frame_support::traits::tokens::fungibles::Mutate as MutateFungibles; use mock::{AssetId, Registry}; use polkadot_xcm::v3::{ Junction::{self, Parachain}, @@ -382,8 +383,8 @@ fn register_external_asset_should_work_when_location_is_provided() { let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); let alice_balance = 10_000 * UNIT; - Tokens::set_balance(RuntimeOrigin::root(), ALICE, NativeAssetId::get(), alice_balance, 0).unwrap(); - assert_eq!(Tokens::free_balance(NativeAssetId::get(), &TREASURY), 0); + Tokens::mint_into(NativeAssetId::get(), &ALICE, alice_balance).unwrap(); + assert_eq!(Tokens::balance(NativeAssetId::get(), &TREASURY), 0); //Act assert_ok!(Registry::register_external( @@ -431,10 +432,10 @@ fn register_external_asset_should_work_when_location_is_provided() { )); assert_eq!( - Tokens::free_balance(NativeAssetId::get(), &ALICE), + Tokens::balance(NativeAssetId::get(), &ALICE), alice_balance - StoreFees::get() ); - assert_eq!(Tokens::free_balance(NativeAssetId::get(), &TREASURY), StoreFees::get()); + assert_eq!(Tokens::balance(NativeAssetId::get(), &TREASURY), StoreFees::get()); }); } @@ -467,8 +468,8 @@ fn register_external_asset_should_not_work_when_location_is_already_used() { )); let alice_balance = 10_000 * UNIT; - Tokens::set_balance(RuntimeOrigin::root(), ALICE, NativeAssetId::get(), alice_balance, 0).unwrap(); - assert_eq!(Tokens::free_balance(NativeAssetId::get(), &TREASURY), 0); + Tokens::mint_into(NativeAssetId::get(), &ALICE, alice_balance).unwrap(); + assert_eq!(Tokens::balance(NativeAssetId::get(), &TREASURY), 0); //Act assert_noop!( diff --git a/pallets/xyk/src/benchmarking.rs b/pallets/xyk/src/benchmarking.rs index 122ddfea3..6acf6cb85 100644 --- a/pallets/xyk/src/benchmarking.rs +++ b/pallets/xyk/src/benchmarking.rs @@ -32,7 +32,7 @@ const SEED: u32 = 1; fn funded_account(name: &'static str, index: u32) -> T::AccountId { let caller: T::AccountId = account(name, index, SEED); - //Necessary for ED for insufficien assets. + //Necessary for ED for insufficient assets. T::Currency::update_balance(0, &caller, 1_000_000_000_000_000).unwrap(); T::Currency::update_balance(1, &caller, 1_000_000_000_000_000).unwrap(); diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 716fcd184..a22d3af97 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -346,7 +346,7 @@ impl pallet_asset_registry::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RegistryOrigin = EnsureRoot; type UpdateOrigin = SuperMajorityTechCommittee; - type Currency = Currencies; + type Currency = pallet_currencies::fungibles::FungibleCurrencies; type AssetId = AssetId; type AssetNativeLocation = AssetLocation; type StringLimit = RegistryStrLimit; diff --git a/runtime/hydradx/src/benchmarking/route_executor.rs b/runtime/hydradx/src/benchmarking/route_executor.rs index a4e3e1cde..89aeaff02 100644 --- a/runtime/hydradx/src/benchmarking/route_executor.rs +++ b/runtime/hydradx/src/benchmarking/route_executor.rs @@ -18,7 +18,6 @@ use crate::{AccountId, AssetId, Balance, Currencies, Router, Runtime, System, LBP}; -use crate::InsufficientEDinHDX; use frame_benchmarking::account; use frame_support::dispatch::DispatchResult; use frame_support::{assert_ok, ensure}; @@ -129,7 +128,7 @@ runtime_benchmarks! { assert_eq!(>::free_balance( asset_in, &seller, - ), INITIAL_BALANCE - amount_to_sell - InsufficientEDinHDX::get()); + ), INITIAL_BALANCE - amount_to_sell); } } From aa4b6a93950b9e38578ce3122279b37a4b27adc3 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 14 Nov 2023 15:53:47 +0100 Subject: [PATCH 65/93] fix PR comments --- pallets/circuit-breaker/src/tests/mock.rs | 1 - pallets/lbp/src/types.rs | 8 ++++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/pallets/circuit-breaker/src/tests/mock.rs b/pallets/circuit-breaker/src/tests/mock.rs index 6d1035868..21d7884ae 100644 --- a/pallets/circuit-breaker/src/tests/mock.rs +++ b/pallets/circuit-breaker/src/tests/mock.rs @@ -36,7 +36,6 @@ use sp_runtime::{ use std::cell::RefCell; use std::collections::HashMap; use std::marker::PhantomData; -//use frame_system::GenesisConfig; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; diff --git a/pallets/lbp/src/types.rs b/pallets/lbp/src/types.rs index fbf9eaa58..e565b7146 100644 --- a/pallets/lbp/src/types.rs +++ b/pallets/lbp/src/types.rs @@ -1,4 +1,4 @@ -// This file is part of Basilisk-node. +// This file is part of HydraDX-node. // Copyright (C) 2020-2022 Intergalactic, Limited (GIB). // SPDX-License-Identifier: Apache-2.0 @@ -27,10 +27,10 @@ use sp_std::vec::Vec; use serde::{Deserialize, Serialize}; /// Asset Pair representation for AMM trades -/// ( asset_a, asset_b ) combination where asset_a is meant to be exchanged for asset_b +/// `( asset_a, asset_b )` combination where `asset_a` is meant to be exchanged for `asset_b` /// -/// asset_in represents asset coming into the pool -/// asset_out represents asset coming out of the pool +/// `asset_in` represents asset coming into the pool +/// `asset_out` represents asset coming out of the pool #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] #[derive(Debug, Encode, Decode, Copy, Clone, PartialEq, Eq, Default, TypeInfo)] pub struct AssetPair { From 5a03cf08945b492be0a05d343e4c42aa2e460b4f Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 15 Nov 2023 13:53:55 +0100 Subject: [PATCH 66/93] fix PR comments --- .../src/insufficient_assets_ed.rs | 80 ++++++++++--------- runtime/hydradx/src/assets.rs | 6 +- 2 files changed, 45 insertions(+), 41 deletions(-) diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index 51ab7224e..4ef19b1eb 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -34,7 +34,7 @@ fn sender_should_pay_ed_in_hdx_when_it_is_not_whitelisted() { let treasury_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); //Act assert_ok!(Tokens::transfer( @@ -57,7 +57,7 @@ fn sender_should_pay_ed_in_hdx_when_it_is_not_whitelisted() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_balance + InsufficientEDinHDX::get() ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -76,7 +76,7 @@ fn sender_should_pay_ed_in_hdx_when_it_is_not_whitelisted() { } #[test] -fn reciever_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted() { +fn reciever_should_pay_ed_in_hdx_when_insuficcient_asset_was_deposited() { TestNet::reset(); Hydra::execute_with(|| { let sht1: AssetId = register_external_asset(0_u128); @@ -92,7 +92,7 @@ fn reciever_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted() { let treasury_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); //Act assert_ok!(Tokens::deposit(sht1, &ALICE.into(), 1_000_000 * UNITS)); @@ -109,7 +109,7 @@ fn reciever_should_pay_ed_in_hdx_when_insuficcient_asset_was_depositted() { treasury_balance + InsufficientEDinHDX::get() ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -145,7 +145,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_hdx() { let alice_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_suffyciency_lock(), 1100000000000_u128); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); //Act assert_ok!(Tokens::transfer( @@ -167,7 +167,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_hdx() { treasury_balance - InsufficientEDinHDX::get() ); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -251,7 +251,7 @@ fn sender_should_pay_ed_only_when_dest_didnt_pay_yet() { .unwrap() .saturating_mul_int(InsufficientEDinHDX::get()); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -319,7 +319,7 @@ fn dest_should_pay_ed_only_once_when_insufficient_asset_was_depsitted() { .unwrap() .saturating_mul_int(InsufficientEDinHDX::get()); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -372,7 +372,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); let treasury_fee_asset_balance = Currencies::free_balance(fee_asset, &TreasuryAccount::get()); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); //Act assert_ok!(Tokens::transfer( @@ -403,7 +403,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset treasury_fee_asset_balance ); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -479,7 +479,7 @@ fn sender_should_pay_ed_in_fee_asset_when_sending_insufficient_asset() { let treasury_fee_asset_balance = Currencies::free_balance(fee_asset, &TreasuryAccount::get()); assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); //Act assert_ok!(Tokens::transfer( @@ -513,7 +513,7 @@ fn sender_should_pay_ed_in_fee_asset_when_sending_insufficient_asset() { treasury_fee_asset_balance + ed_in_fee_asset ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -533,8 +533,10 @@ fn sender_should_pay_ed_in_fee_asset_when_sending_insufficient_asset() { #[test] fn grandfathered_account_should_receive_hdx_when_account_is_killed() { - //NOTE: thiscase simulates old account that received insufficient asset before sufficiency + //NOTE: this case simulates old account that received insufficient asset before sufficiency //check and didn't pay ED. + //`GRANDFATHERED_UNPAID_ED` bypassed `SufficiencyCheck` by receiving tokens during chain state + //initialization. TestNet::reset(); Hydra::execute_with(|| { @@ -570,7 +572,7 @@ fn grandfathered_account_should_receive_hdx_when_account_is_killed() { ); //NOTE: this is zero because Alice paid ED and it was paid to grandfathered - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 0_u128 @@ -601,7 +603,7 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() let alice_sufficient_asset_balance = Currencies::free_balance(DAI, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -626,7 +628,7 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -651,7 +653,7 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -686,7 +688,7 @@ fn ed_should_not_be_released_when_sufficient_asset_killed_account() { let alice_sufficient_asset_balance = Currencies::free_balance(DAI, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -714,7 +716,7 @@ fn ed_should_not_be_released_when_sufficient_asset_killed_account() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -746,7 +748,7 @@ fn ed_should_be_collected_for_each_insufficient_asset_when_transfered_or_deposit assert_eq!(MultiTransactionPayment::account_currency(&ALICE.into()), HDX); assert_eq!(MultiTransactionPayment::account_currency(&BOB.into()), HDX); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); assert_ok!(Tokens::set_balance( RawOrigin::Root.into(), @@ -811,7 +813,7 @@ fn ed_should_be_collected_for_each_insufficient_asset_when_transfered_or_deposit Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance + InsufficientEDinHDX::get() * 4 ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 4); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get() * 4); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 4_u128 @@ -868,7 +870,7 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 4); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get() * 4); //Act 1 assert_ok!(Tokens::transfer( @@ -887,7 +889,7 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance - InsufficientEDinHDX::get() ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 3); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get() * 3); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 3_u128 @@ -910,7 +912,7 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance - InsufficientEDinHDX::get() * 2 ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 2); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get() * 2); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 2_u128 @@ -933,7 +935,7 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance - InsufficientEDinHDX::get() * 3 ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -956,7 +958,7 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance - InsufficientEDinHDX::get() * 4 ); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 0_u128 @@ -1008,7 +1010,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get() * 2); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get() * 2); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 2_u128 @@ -1031,7 +1033,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance - InsufficientEDinHDX::get() ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -1056,7 +1058,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -1083,7 +1085,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance - InsufficientEDinHDX::get() ); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 0_u128 @@ -1107,7 +1109,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 0_u128 @@ -1131,7 +1133,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 0_u128 @@ -1180,7 +1182,7 @@ fn sender_should_pay_ed_when_tranferred_or_deposited_to_whitelisted_dest() { bob_fee_asset_balance - InsufficientEDinHDX::get() ); assert_eq!(Currencies::free_balance(sht1, &treasury), 10); - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -1197,7 +1199,7 @@ fn sender_should_pay_ed_when_tranferred_or_deposited_to_whitelisted_dest() { assert_eq!(Currencies::free_balance(sht1, &treasury), 10); assert_eq!(Currencies::free_balance(sht2, &treasury), 20); //NOTE: treasury paid ED in hdx so hdx balance didn't changed but locked was increased. - assert_eq!(treasury_suffyciency_lock(), 2 * InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), 2 * InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 2_u128 @@ -1258,7 +1260,7 @@ fn ed_should_be_released_when_whitelisted_account_was_killed() { let treasury_hdx_balance = Currencies::free_balance(HDX, &treasury); //NOTE: set_balance bypass mutation hooks so none was paid. - assert_eq!(treasury_suffyciency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -1278,7 +1280,7 @@ fn ed_should_be_released_when_whitelisted_account_was_killed() { assert_eq!(Currencies::free_balance(sht1, &BOB.into()), 2_000_000 * UNITS); //NOTE: bob already holds sht1 so it means additional ed is not necessary. - assert_eq!(treasury_suffyciency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), 0); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 0_u128 @@ -1347,7 +1349,7 @@ fn register_external_asset(general_index: u128) -> AssetId { next_asset_id } -fn treasury_suffyciency_lock() -> Balance { +fn treasury_sufficiency_lock() -> Balance { pallet_balances::Locks::::get(TreasuryAccount::get()) .iter() .find(|x| x.id == SUFFICIENCY_LOCK) @@ -1359,7 +1361,7 @@ fn treasury_suffyciency_lock() -> Balance { /// /// Parameters: /// - `event` -/// - `times` - number of times event should occure. +/// - `times` - number of times event should occur. #[macro_export] macro_rules! assert_event_times { ( $x:expr, $y: expr ) => {{ diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index a22d3af97..1394f5b5b 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -18,6 +18,7 @@ use super::*; use crate::system::NativeAssetId; +use frame_support::traits::Defensive; use hydradx_adapters::{ inspect::MultiInspectAdapter, EmaOraclePriceAdapter, FreezableNFT, MultiCurrencyLockedBalance, OmnipoolHookAdapter, OracleAssetVolumeProvider, PriceAdjustmentAdapter, StableswapHooksAdapter, VestingInfo, @@ -105,7 +106,7 @@ parameter_types! { pub struct SufficiencyCheck; impl SufficiencyCheck { - /// This function is used by `orml-toknes` `MutationHooks` before a transaction is executed. + /// This function is used by `orml-toknes::MutationHooks` before a transaction is executed. /// It is called from `PreDeposit` and `PreTransfer`. /// If transferred asset is not sufficient asset, it calculates ED amount in user's fee asset /// and transfers it from user to treasury account. @@ -242,7 +243,8 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { NativeAssetId::get(), &TreasuryAccount::get(), to_lock, - ); + ) + .defensive(); } let _ = >::transfer( From a0b3d4452420b8fab6eccabb5e7edaacc8c03625 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 22 Nov 2023 14:48:19 +0100 Subject: [PATCH 67/93] fix PR comments --- .../src/insufficient_assets_ed.rs | 37 ++++++++++--------- integration-tests/src/polkadot_test_net.rs | 4 -- pallets/asset-registry/src/lib.rs | 4 -- pallets/asset-registry/src/migration.rs | 21 ++++++++--- runtime/hydradx/src/assets.rs | 23 +++--------- 5 files changed, 40 insertions(+), 49 deletions(-) diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index 4ef19b1eb..bb8042b55 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -532,50 +532,51 @@ fn sender_should_pay_ed_in_fee_asset_when_sending_insufficient_asset() { } #[test] -fn grandfathered_account_should_receive_hdx_when_account_is_killed() { - //NOTE: this case simulates old account that received insufficient asset before sufficiency - //check and didn't pay ED. - //`GRANDFATHERED_UNPAID_ED` bypassed `SufficiencyCheck` by receiving tokens during chain state - //initialization. - +fn account_with_zero_sufficients_should_not_release_ed() { TestNet::reset(); Hydra::execute_with(|| { let dummy: AssetId = 1_000_001; + //NOTE: set balance baypass `MutationHooks` so Bob received insufficient asset without + //locking ED. + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + dummy, + 100_000_000 * UNITS, + 0, + )); + assert_ok!(Tokens::deposit(dummy, &ALICE.into(), 1_000_000 * UNITS)); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 ); - let grandfathered_balance = Currencies::free_balance(HDX, &GRANDFATHERED_UNPAID_ED.into()); + let bob_balance = Currencies::free_balance(HDX, &BOB.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - let dummy_balance = Currencies::free_balance(dummy, &GRANDFATHERED_UNPAID_ED.into()); + let dummy_balance = Currencies::free_balance(dummy, &BOB.into()); //Act assert_ok!(Tokens::transfer( - hydra_origin::signed(GRANDFATHERED_UNPAID_ED.into()), + hydra_origin::signed(BOB.into()), ALICE.into(), dummy, dummy_balance )); //Assert - assert_eq!( - Currencies::free_balance(HDX, &GRANDFATHERED_UNPAID_ED.into()), - grandfathered_balance + InsufficientEDinHDX::get() - ); + assert_eq!(Currencies::free_balance(HDX, &BOB.into()), bob_balance); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_balance - InsufficientEDinHDX::get() + treasury_hdx_balance ); - //NOTE: this is zero because Alice paid ED and it was paid to grandfathered - assert_eq!(treasury_sufficiency_lock(), 0); + assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), - 0_u128 + 1_u128 ); assert_event_times!( @@ -1259,7 +1260,7 @@ fn ed_should_be_released_when_whitelisted_account_was_killed() { assert_eq!(MultiTransactionPayment::account_currency(&treasury), HDX); let treasury_hdx_balance = Currencies::free_balance(HDX, &treasury); - //NOTE: set_balance bypass mutation hooks so none was paid. + //NOTE: set_balance bypass mutation hooks so only Bob paid ED for Treasury. assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), diff --git a/integration-tests/src/polkadot_test_net.rs b/integration-tests/src/polkadot_test_net.rs index 29a56527d..be4f62caf 100644 --- a/integration-tests/src/polkadot_test_net.rs +++ b/integration-tests/src/polkadot_test_net.rs @@ -24,8 +24,6 @@ pub const ALICE: [u8; 32] = [4u8; 32]; pub const BOB: [u8; 32] = [5u8; 32]; pub const CHARLIE: [u8; 32] = [6u8; 32]; pub const DAVE: [u8; 32] = [7u8; 32]; -//This account received insufficient asset before sufficiency check. -pub const GRANDFATHERED_UNPAID_ED: [u8; 32] = [8u8; 32]; pub const UNITS: Balance = 1_000_000_000_000; @@ -267,8 +265,6 @@ pub fn hydra_ext() -> sp_io::TestExternalities { (omnipool_account.clone(), ETH, eth_amount), (omnipool_account.clone(), BTC, btc_amount), (omnipool_account, DOT, dot_amount), - //Special account for insufficient assets ED tests - (AccountId::from(GRANDFATHERED_UNPAID_ED), 1_000_001, 1_000 * UNITS), ], } .assimilate_storage(&mut t) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 79edea684..0c97cf77c 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -155,10 +155,6 @@ pub mod pallet { /// Balance too low. InsufficientBalance, - //NOTE: This error is triggered from `SufficiencyCheck`. - /// Existential deposit can't be zero. - ZeroExistentialDeposit, - /// Action cannot be completed because unexpected error has occurred. This should be reported /// to protocol maintainers. InconsistentState(InconsistentStateError), diff --git a/pallets/asset-registry/src/migration.rs b/pallets/asset-registry/src/migration.rs index 2c2520e00..30eac3917 100644 --- a/pallets/asset-registry/src/migration.rs +++ b/pallets/asset-registry/src/migration.rs @@ -98,13 +98,17 @@ pub mod v2 { "Migrating Assets storage" ); - let mut i = 0; + let mut reads = 0; + let mut writes = 0; + let mut v2_assets_details = Vec::<( ::AssetId, AssetDetails<::StringLimit>, )>::new(); + + let mut assets_count = 0; for (k, v) in v1::Assets::::iter() { - i += 1; + assets_count += 1; let (symbol, decimals) = if let Some(meta) = v1::AssetMetadataMap::::get(k) { (Some(meta.symbol), Some(meta.decimals)) } else { @@ -125,9 +129,13 @@ pub mod v2 { }, )); } + reads += assets_count; + + let _ = v1::Assets::::clear(u32::MAX, None); + writes += assets_count; for (k, v) in v2_assets_details { - i += 1; + writes += 1; Assets::::insert(k, v); log::info!( target: "runtime::asset-registry", @@ -136,8 +144,8 @@ pub mod v2 { } //This assumes every asset has metadata and each metadata is touched. - i += i; let _ = v1::AssetMetadataMap::::clear(u32::MAX, None); + writes += assets_count; log::info!( target: "runtime::asset-registry", @@ -145,7 +153,8 @@ pub mod v2 { ); for k in v1::AssetLocations::::iter_keys() { - i += 1; + reads += 1; + writes += 1; AssetLocations::::migrate_key::::AssetId>(k); @@ -156,7 +165,7 @@ pub mod v2 { } StorageVersion::new(2).put::>(); - T::DbWeight::get().reads_writes(i, i) + T::DbWeight::get().reads_writes(reads, writes) } pub fn post_migrate() { diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 42ce02472..f9b20f71f 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -47,7 +47,7 @@ use sp_runtime::{traits::Zero, DispatchResult, FixedPointNumber}; use core::ops::RangeInclusive; use frame_support::{ - ensure, parameter_types, + parameter_types, sp_runtime::app_crypto::sp_core::crypto::UncheckedFrom, sp_runtime::traits::{One, PhantomData}, sp_runtime::{FixedU128, Perbill, Permill}, @@ -144,13 +144,8 @@ impl SufficiencyCheck { let ed_in_fee_asset = MultiTransactionPayment::price(fee_payment_asset) .ok_or(pallet_transaction_multi_payment::Error::::UnsupportedCurrency)? - .saturating_mul_int(InsufficientEDinHDX::get()); - - //NOTE: Not tested, this should never happen. - ensure!( - !ed_in_fee_asset.is_zero(), - pallet_asset_registry::Error::::ZeroExistentialDeposit - ); + .saturating_mul_int(InsufficientEDinHDX::get()) + .max(1); //NOTE: Account doesn't have enough funds to pay ED if this fail. >::transfer( @@ -175,7 +170,7 @@ impl SufficiencyCheck { to_lock, )?; - frame_system::Pallet::::inc_sufficients(paying_account); + frame_system::Pallet::::inc_sufficients(to); pallet_asset_registry::ExistentialDepositCounter::::mutate(|v| *v = v.saturating_add(1)); @@ -213,7 +208,7 @@ impl OnDeposit for SufficiencyCheck { pub struct OnKilledTokenAccount; impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { fn happened((who, asset): &(AccountId, AssetId)) { - if AssetRegistry::is_sufficient(*asset) { + if AssetRegistry::is_sufficient(*asset) || frame_system::Pallet::::account(who).sufficients.is_zero() { return; } @@ -254,13 +249,7 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { ed_to_refund, ); - //NOTE: This is necessary because grandfathered accounts doesn't have incremented - //sufficients by `SufficiencyCheck` so without check it can overflow. - //`set_balance` also bypass `MutationHooks` - if frame_system::Pallet::::account(who).sufficients > 0 { - frame_system::Pallet::::dec_sufficients(who); - } - + frame_system::Pallet::::dec_sufficients(who); pallet_asset_registry::ExistentialDepositCounter::::set(paid_accounts.saturating_sub(1)); } } From af4b8c18b8ada3a42517582ae2801972be744847 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 1 Dec 2023 15:19:01 +0100 Subject: [PATCH 68/93] asset-registry: disallow suff -> insuff asset sufficiency change and added assets blacklist --- pallets/asset-registry/src/lib.rs | 65 ++++++++++- pallets/asset-registry/src/tests/mod.rs | 1 + pallets/asset-registry/src/tests/tests.rs | 120 +++++++++++++++++++++ pallets/asset-registry/src/tests/update.rs | 45 ++++++-- 4 files changed, 223 insertions(+), 8 deletions(-) create mode 100644 pallets/asset-registry/src/tests/tests.rs diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 0c97cf77c..9af1273ac 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -155,6 +155,15 @@ pub mod pallet { /// Balance too low. InsufficientBalance, + /// Sufficient assets can't be changed to insufficient. + ForbiddenSufficiencyChange, + + /// Asset is already blacklisted. + AssetAlreadyBlacklisted, + + /// Asset is not in assets blacklist. + AssetNotBlacklisted, + /// Action cannot be completed because unexpected error has occurred. This should be reported /// to protocol maintainers. InconsistentState(InconsistentStateError), @@ -201,6 +210,11 @@ pub mod pallet { pub type AssetLocations = StorageMap<_, Blake2_128Concat, T::AssetId, T::AssetNativeLocation, OptionQuery>; + #[pallet::storage] + #[pallet::getter(fn blacklists)] + /// Assets that are blacklisted. + pub type BlacklistedAssets = StorageMap<_, Blake2_128Concat, T::AssetId, (), OptionQuery>; + #[pallet::storage] #[pallet::getter(fn location_assets)] /// Local asset for native location. @@ -344,6 +358,12 @@ pub mod pallet { asset_id: T::AssetId, location: T::AssetNativeLocation, }, + + /// Asset was added to assets blacklist. + BlacklistAdded { asset_id: T::AssetId }, + + /// Asset was removed from assets blacklist. + BlacklistRemoved { asset_id: T::AssetId }, } #[pallet::call] @@ -444,9 +464,16 @@ pub mod pallet { details.asset_type = asset_type.unwrap_or(details.asset_type); details.existential_deposit = existential_deposit.unwrap_or(details.existential_deposit); details.xcm_rate_limit = xcm_rate_limit.or(details.xcm_rate_limit); - details.is_sufficient = is_sufficient.unwrap_or(details.is_sufficient); details.symbol = bounded_symbol.or_else(|| details.symbol.clone()); + let suff = is_sufficient.unwrap_or(details.is_sufficient); + if details.is_sufficient != suff { + //NOTE: Change sufficient -> insufficient require storage migration and is not + //allowed by extrinsic. + ensure!(!details.is_sufficient, Error::::ForbiddenSufficiencyChange); + details.is_sufficient = suff; + } + if decimals.is_some() { if details.decimals.is_none() { details.decimals = decimals; @@ -513,6 +540,42 @@ pub mod pallet { Ok(()) } + + #[pallet::call_index(5)] + //#[pallet::weight(::WeightInfo::register_external())] + #[pallet::weight(1000)] + pub fn blacklist_add(origin: OriginFor, asset_id: T::AssetId) -> DispatchResult { + T::UpdateOrigin::ensure_origin(origin)?; + + ensure!(Assets::::contains_key(asset_id), Error::::AssetNotFound); + + ensure!( + !BlacklistedAssets::::contains_key(asset_id), + Error::::AssetAlreadyBlacklisted + ); + + BlacklistedAssets::::insert(asset_id, ()); + + Self::deposit_event(Event::BlacklistAdded { asset_id }); + Ok(()) + } + + #[pallet::call_index(6)] + //#[pallet::weight(::WeightInfo::register_external())] + #[pallet::weight(1000)] + pub fn blacklist_remove(origin: OriginFor, asset_id: T::AssetId) -> DispatchResult { + T::UpdateOrigin::ensure_origin(origin)?; + + ensure!( + BlacklistedAssets::::contains_key(asset_id), + Error::::AssetNotBlacklisted + ); + + BlacklistedAssets::::remove(asset_id); + + Self::deposit_event(Event::BlacklistRemoved { asset_id }); + Ok(()) + } } } diff --git a/pallets/asset-registry/src/tests/mod.rs b/pallets/asset-registry/src/tests/mod.rs index 16d7c4489..2b5bc502a 100644 --- a/pallets/asset-registry/src/tests/mod.rs +++ b/pallets/asset-registry/src/tests/mod.rs @@ -8,6 +8,7 @@ mod inspect_trait; pub(crate) mod mock; mod mutate_trait; mod register; +mod tests; mod update; #[macro_export] diff --git a/pallets/asset-registry/src/tests/tests.rs b/pallets/asset-registry/src/tests/tests.rs new file mode 100644 index 000000000..6bf147c22 --- /dev/null +++ b/pallets/asset-registry/src/tests/tests.rs @@ -0,0 +1,120 @@ +use super::*; + +use mock::Registry; +use pretty_assertions::assert_eq; + +#[test] +fn blacklist_add_should_work_when_asset_is_not_blacklisted() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"tkn2".to_vec()), UNIT, None, None, None, false), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + //Act + //NOTE: update origin is set to ensure_signed in tests + assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 1)); + + //Assert + assert_last_event!(Event::::BlacklistAdded { asset_id: 1 }.into()); + + assert_eq!(Registry::blacklists(1), Some(())) + }); +} + +#[test] +fn blacklist_add_should_fial_when_asset_is_already_blacklisted() { + let asset_id: u32 = 1; + ExtBuilder::default() + .with_assets(vec![ + (Some(asset_id), Some(b"tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"tkn2".to_vec()), UNIT, None, None, None, false), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + //Arrange + assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 2)); + assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), asset_id)); + + //Act + //NOTE: update origin is set to ensure_signed in tests + assert_noop!( + Registry::blacklist_add(RuntimeOrigin::signed(ALICE), asset_id), + Error::::AssetAlreadyBlacklisted + ); + }); +} + +#[test] +fn blacklist_add_should_fail_when_asset_is_not_registered() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"tkn2".to_vec()), UNIT, None, None, None, false), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + let not_existing_asset = 112_412_u32; + + //Act + //NOTE: update origin is set to ensure_signed in tests + assert_noop!( + Registry::blacklist_add(RuntimeOrigin::signed(ALICE), not_existing_asset), + Error::::AssetNotFound + ); + }); +} + +#[test] +fn blacklist_remove_should_work_when_asset_is_blacklisted() { + let asset_id: u32 = 1; + ExtBuilder::default() + .with_assets(vec![ + (Some(asset_id), Some(b"tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"tkn2".to_vec()), UNIT, None, None, None, false), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + //Arrange + assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 3)); + assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), asset_id)); + + //Act + //NOTE: update origin is set to ensure_signed in tests + assert_ok!(Registry::blacklist_remove(RuntimeOrigin::signed(ALICE), asset_id),); + + //Assert + assert_last_event!(Event::::BlacklistRemoved { asset_id }.into()); + + assert_eq!(Registry::blacklists(asset_id), None) + }); +} + +#[test] +fn blacklist_remove_should_fail_when_asset_is_not_blacklisted() { + let asset_id: u32 = 1; + ExtBuilder::default() + .with_assets(vec![ + (Some(asset_id), Some(b"tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"tkn2".to_vec()), UNIT, None, None, None, false), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + //Arrange + assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 3)); + assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 2)); + + //Act + //NOTE: update origin is set to ensure_signed in tests + assert_noop!( + Registry::blacklist_remove(RuntimeOrigin::signed(ALICE), asset_id), + Error::::AssetNotBlacklisted + ); + }); +} diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index e40252a0e..bcfff090e 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -15,7 +15,7 @@ fn update_should_work_when_asset_exists() { ExtBuilder::default() .with_assets(vec![ (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(old_asset_name.clone()), UNIT, None, None, None, true), + (Some(2), Some(old_asset_name.clone()), UNIT, None, None, None, false), (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), ]) .build() @@ -26,7 +26,7 @@ fn update_should_work_when_asset_exists() { let xcm_rate_limit = 463; let symbol = b"nTkn2".to_vec(); let decimals = 23; - let is_sufficient = false; + let is_sufficient = true; //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); @@ -59,7 +59,7 @@ fn update_should_work_when_asset_exists() { xcm_rate_limit: Some(xcm_rate_limit), symbol: bounded_symbol.clone(), decimals: Some(decimals), - is_sufficient: false + is_sufficient: true }) ); @@ -104,7 +104,7 @@ fn update_should_update_provided_params_when_values_was_previously_set() { Some(12), Some(asset_location.clone()), Some(1_000), - true + false )); let name = b"New name".to_vec(); @@ -112,7 +112,7 @@ fn update_should_update_provided_params_when_values_was_previously_set() { let xcm_rate_limit = 463; let symbol = b"nTkn".to_vec(); let decimals = 23; - let is_sufficient = false; + let is_sufficient = true; //Act assert_ok!(Registry::update( @@ -140,7 +140,7 @@ fn update_should_update_provided_params_when_values_was_previously_set() { xcm_rate_limit: Some(xcm_rate_limit), symbol: bounded_symbol.clone(), decimals: Some(decimals), - is_sufficient: false + is_sufficient: true }) ); @@ -657,7 +657,7 @@ fn update_should_fail_when_name_is_too_long() { } #[test] -fn update_should_fail_when_symbolis_too_long() { +fn update_should_fail_when_symbol_is_too_long() { ExtBuilder::default() .with_assets(vec![ (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), @@ -692,3 +692,34 @@ fn update_should_fail_when_symbolis_too_long() { ); }); } + +#[test] +fn change_sufficiency_should_fail_when_asset_is_sufficient() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), + (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + + //Act + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + None, + None, + None, + None, + Some(false), + None, + None, + None + ), + Error::::ForbiddenSufficiencyChange + ); + }); +} From 974f778e2cbb2c20713b9d23b96062fc00c0a10b Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 4 Dec 2023 11:27:40 +0100 Subject: [PATCH 69/93] registy-registry: implemented is_blacklisted fn and block asset transfer when asset is blacklieste and updated tests --- .../src/insufficient_assets_ed.rs | 63 ++++++++++++++++++- pallets/asset-registry/src/benchmarking.rs | 42 ++++++++++++- pallets/asset-registry/src/lib.rs | 4 ++ .../asset-registry/src/tests/inspect_trait.rs | 20 ++++++ pallets/asset-registry/src/tests/mod.rs | 1 + pallets/bonds/src/tests/mock.rs | 4 ++ pallets/circuit-breaker/src/tests/mock.rs | 4 ++ pallets/dca/src/tests/mock.rs | 4 ++ pallets/liquidity-mining/src/tests/mock.rs | 4 ++ .../src/tests/mock.rs | 4 ++ pallets/omnipool/src/tests/mock.rs | 4 ++ pallets/otc/src/tests/mock.rs | 4 ++ pallets/stableswap/src/tests/mock.rs | 4 ++ pallets/xcm-rate-limiter/src/tests/mock.rs | 4 ++ runtime/adapters/src/tests/mock.rs | 4 ++ runtime/hydradx/src/assets.rs | 6 +- traits/src/registry.rs | 2 + 17 files changed, 174 insertions(+), 4 deletions(-) diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index bb8042b55..9a0844288 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -8,7 +8,7 @@ use frame_system::RawOrigin; use hydradx_runtime::RuntimeOrigin as hydra_origin; use hydradx_runtime::{ AssetRegistry as Registry, Currencies, DustRemovalWhitelist, InsufficientEDinHDX, MultiTransactionPayment, - RuntimeEvent, Tokens, TreasuryAccount, SUFFICIENCY_LOCK, + RuntimeEvent, TechnicalCollective, Tokens, TreasuryAccount, SUFFICIENCY_LOCK, }; use hydradx_traits::NativePriceOracle; use orml_traits::MultiCurrency; @@ -1338,6 +1338,67 @@ fn tx_should_fail_with_unsupported_currency_error_when_fee_asset_price_wasn_not_ }); } +#[test] +fn blacklisted_asset_should_not_create_new_account() { + TestNet::reset(); + Hydra::execute_with(|| { + let tech_comm = pallet_collective::RawOrigin::::Members(1, 1); + //Arrange + let sht1: AssetId = register_external_asset(0_u128); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + sht1, + 100_000_000 * UNITS, + 0, + )); + + assert_ok!(Registry::blacklist_add(tech_comm.into(), sht1)); + + assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); + assert_eq!(treasury_sufficiency_lock(), 0); + + //Act & assert + assert_noop!( + Tokens::transfer(hydra_origin::signed(BOB.into()), ALICE.into(), sht1, 1_000_000 * UNITS), + sp_runtime::DispatchError::Other("BlacklistedAssetTransfer") + ); + }); +} + +#[test] +fn blacklisted_asset_should_not_be_transferable_to_existing_account() { + TestNet::reset(); + Hydra::execute_with(|| { + let tech_comm = pallet_collective::RawOrigin::::Members(1, 1); + //Arrange + let sht1: AssetId = register_external_asset(0_u128); + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + BOB.into(), + sht1, + 100_000_000 * UNITS, + 0, + )); + + assert_ok!(Tokens::set_balance( + RawOrigin::Root.into(), + ALICE.into(), + sht1, + 100_000_000 * UNITS, + 0, + )); + + assert_ok!(Registry::blacklist_add(tech_comm.into(), sht1)); + + //Act & assert + assert_noop!( + Tokens::transfer(hydra_origin::signed(BOB.into()), ALICE.into(), sht1, 1_000_000 * UNITS), + sp_runtime::DispatchError::Other("BlacklistedAssetTransfer") + ); + }); +} + fn register_external_asset(general_index: u128) -> AssetId { let location = hydradx_runtime::AssetLocation(MultiLocation::new( 1, diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index 2ff460c26..cf6b19c94 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -59,7 +59,7 @@ benchmarks! { let decimals = 12_u8; let location: T::AssetNativeLocation = Default::default(); let xcm_rate_limit = 1_000_u128; - let is_sufficient = true; + let is_sufficient = false; let _ = Pallet::::register(RawOrigin::Root.into(), Some(asset_id), Some(name), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient); @@ -67,7 +67,7 @@ benchmarks! { let new_type = AssetType::XYK; let new_ed = 1_000_000_u128; let new_xcm_rate_limit = 1_000_u128; - let new_is_sufficient = false; + let new_is_sufficient = true; let new_symbol = vec![98u8; T::StringLimit::get() as usize]; let new_decimals = 12_u8; @@ -102,8 +102,46 @@ benchmarks! { verify { assert_eq!(Pallet::::locations(expected_asset_id), Some(location.clone())); assert_eq!(Pallet::::location_assets(location), Some(expected_asset_id)); + } + blacklist_add { + let asset_id = T::AssetId::from(3); + let name = vec![97u8; T::StringLimit::get() as usize]; + let ed = 1_000_000_u128; + let symbol = vec![97u8; T::StringLimit::get() as usize]; + let decimals = 12_u8; + let location: T::AssetNativeLocation = Default::default(); + let xcm_rate_limit = 1_000_u128; + let is_sufficient = true; + + let _ = Pallet::::register(RawOrigin::Root.into(), Some(asset_id), Some(name), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient); + + let origin = T::UpdateOrigin::try_successful_origin().unwrap(); + }: _(origin, asset_id) + verify { + assert_eq!(Pallet::::blacklists(asset_id), Some(())); } + blacklist_remove { + let asset_id = T::AssetId::from(3); + let name = vec![97u8; T::StringLimit::get() as usize]; + let ed = 1_000_000_u128; + let symbol = vec![97u8; T::StringLimit::get() as usize]; + let decimals = 12_u8; + let location: T::AssetNativeLocation = Default::default(); + let xcm_rate_limit = 1_000_u128; + let is_sufficient = true; + + let origin = T::UpdateOrigin::try_successful_origin().unwrap(); + let _ = Pallet::::register(RawOrigin::Root.into(), Some(asset_id), Some(name), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient); + let _ = Pallet::::blacklist_add(origin.clone(), asset_id); + + assert_eq!(Pallet::::blacklists(asset_id), Some(())); + }: _(origin, asset_id) + verify { + assert_eq!(Pallet::::blacklists(asset_id), None); + } + + impl_benchmark_test_suite!(Pallet, crate::tests::mock::ExtBuilder::default().build(), crate::tests::mock::Test); } diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 9af1273ac..d374c8228 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -746,6 +746,10 @@ impl Inspect for Pallet { fn asset_type(id: Self::AssetId) -> Option { Self::assets(id).map(|a| a.asset_type.into()) } + + fn is_blacklisted(id: Self::AssetId) -> bool { + BlacklistedAssets::::contains_key(id) + } } impl Mutate for Pallet { diff --git a/pallets/asset-registry/src/tests/inspect_trait.rs b/pallets/asset-registry/src/tests/inspect_trait.rs index 82f5b1422..8a19bdc38 100644 --- a/pallets/asset-registry/src/tests/inspect_trait.rs +++ b/pallets/asset-registry/src/tests/inspect_trait.rs @@ -131,3 +131,23 @@ fn asset_type_should_work() { }); }); } + +#[test] +fn is_blacklisted_should_work() { + ExtBuilder::default() + .with_assets(vec![ + (Some(1), Some(b"Suff".to_vec()), UNIT, None, None, None, true), + (Some(2), Some(b"Insuff".to_vec()), UNIT, None, None, None, false), + ]) + .build() + .execute_with(|| { + //Arrange + //NOTE: update origin is set to ensure_signed in tests + assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 1)); + + //Act & assert + assert_eq!(::is_blacklisted(1), true); + + assert_eq!(::is_blacklisted(2), false); + }); +} diff --git a/pallets/asset-registry/src/tests/mod.rs b/pallets/asset-registry/src/tests/mod.rs index 2b5bc502a..4e789aee6 100644 --- a/pallets/asset-registry/src/tests/mod.rs +++ b/pallets/asset-registry/src/tests/mod.rs @@ -8,6 +8,7 @@ mod inspect_trait; pub(crate) mod mock; mod mutate_trait; mod register; +#[allow(clippy::module_inception)] mod tests; mod update; diff --git a/pallets/bonds/src/tests/mock.rs b/pallets/bonds/src/tests/mock.rs index 9f6eedeca..a53ab9468 100644 --- a/pallets/bonds/src/tests/mock.rs +++ b/pallets/bonds/src/tests/mock.rs @@ -242,6 +242,10 @@ impl Inspect for DummyRegistry { fn exists(_name: AssetId) -> bool { unimplemented!() } + + fn is_blacklisted(_id: Self::AssetId) -> bool { + unimplemented!() + } } pub struct ExtBuilder { diff --git a/pallets/circuit-breaker/src/tests/mock.rs b/pallets/circuit-breaker/src/tests/mock.rs index 21d7884ae..53bf43125 100644 --- a/pallets/circuit-breaker/src/tests/mock.rs +++ b/pallets/circuit-breaker/src/tests/mock.rs @@ -390,6 +390,10 @@ where let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); matches!(asset, Some(_)) } + + fn is_blacklisted(_id: Self::AssetId) -> bool { + unimplemented!() + } } pub struct ExtBuilder { diff --git a/pallets/dca/src/tests/mock.rs b/pallets/dca/src/tests/mock.rs index e31a25c33..ddb85b045 100644 --- a/pallets/dca/src/tests/mock.rs +++ b/pallets/dca/src/tests/mock.rs @@ -739,6 +739,10 @@ where let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); matches!(asset, Some(_)) } + + fn is_blacklisted(_id: Self::AssetId) -> bool { + unimplemented!() + } } pub type AccountId = u64; diff --git a/pallets/liquidity-mining/src/tests/mock.rs b/pallets/liquidity-mining/src/tests/mock.rs index 356a0dd0e..87b019b8f 100644 --- a/pallets/liquidity-mining/src/tests/mock.rs +++ b/pallets/liquidity-mining/src/tests/mock.rs @@ -450,6 +450,10 @@ impl Inspect for DummyRegistry { fn exists(name: AssetId) -> bool { name != UNKNOWN_ASSET } + + fn is_blacklisted(_id: Self::AssetId) -> bool { + unimplemented!() + } } impl GetByKey for DummyRegistry { diff --git a/pallets/omnipool-liquidity-mining/src/tests/mock.rs b/pallets/omnipool-liquidity-mining/src/tests/mock.rs index 2fe4bf781..d0e999b8d 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mock.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mock.rs @@ -663,6 +663,10 @@ where let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); matches!(asset, Some(_)) } + + fn is_blacklisted(_id: Self::AssetId) -> bool { + unimplemented!() + } } #[cfg(feature = "runtime-benchmarks")] diff --git a/pallets/omnipool/src/tests/mock.rs b/pallets/omnipool/src/tests/mock.rs index ccbcb7119..fd573a553 100644 --- a/pallets/omnipool/src/tests/mock.rs +++ b/pallets/omnipool/src/tests/mock.rs @@ -538,6 +538,10 @@ where fn asset_type(_id: Self::AssetId) -> Option { unimplemented!() } + + fn is_blacklisted(_id: Self::AssetId) -> bool { + unimplemented!() + } } pub(crate) fn get_mock_minted_position(position_id: u32) -> Option { diff --git a/pallets/otc/src/tests/mock.rs b/pallets/otc/src/tests/mock.rs index e86a35108..5cef53ecc 100644 --- a/pallets/otc/src/tests/mock.rs +++ b/pallets/otc/src/tests/mock.rs @@ -157,6 +157,10 @@ impl Inspect for DummyRegistry { let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id)).copied()); matches!(asset, Some(_)) } + + fn is_blacklisted(_id: Self::AssetId) -> bool { + unimplemented!() + } } #[cfg(feature = "runtime-benchmarks")] diff --git a/pallets/stableswap/src/tests/mock.rs b/pallets/stableswap/src/tests/mock.rs index 5de7148cf..0a7d9f529 100644 --- a/pallets/stableswap/src/tests/mock.rs +++ b/pallets/stableswap/src/tests/mock.rs @@ -337,6 +337,10 @@ impl Inspect for DummyRegistry { fn asset_type(_id: Self::AssetId) -> Option { unimplemented!() } + + fn is_blacklisted(_id: Self::AssetId) -> bool { + unimplemented!() + } } #[cfg(feature = "runtime-benchmarks")] diff --git a/pallets/xcm-rate-limiter/src/tests/mock.rs b/pallets/xcm-rate-limiter/src/tests/mock.rs index 89475ca18..1c6303c76 100644 --- a/pallets/xcm-rate-limiter/src/tests/mock.rs +++ b/pallets/xcm-rate-limiter/src/tests/mock.rs @@ -337,6 +337,10 @@ where let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id.into())).copied()); matches!(asset, Some(_)) } + + fn is_blacklisted(_id: Self::AssetId) -> bool { + unimplemented!() + } } pub struct ExtBuilder { diff --git a/runtime/adapters/src/tests/mock.rs b/runtime/adapters/src/tests/mock.rs index 077e288ad..5fa6e5d00 100644 --- a/runtime/adapters/src/tests/mock.rs +++ b/runtime/adapters/src/tests/mock.rs @@ -561,6 +561,10 @@ where let asset = REGISTERED_ASSETS.with(|v| v.borrow().get(&(asset_id)).copied()); matches!(asset, Some(_)) } + + fn is_blacklisted(_id: Self::AssetId) -> bool { + unimplemented!() + } } pub struct MockOracle; diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index f9b20f71f..a3a134e2a 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -137,9 +137,13 @@ impl SufficiencyCheck { /// /// Emits `pallet_asset_registry::Event::ExistentialDepositPaid` when ED was paid. fn on_funds(asset: AssetId, paying_account: &AccountId, to: &AccountId) -> DispatchResult { + if AssetRegistry::is_blacklisted(asset) { + return Err(sp_runtime::DispatchError::Other("BlacklistedAssetTransfer")); + } + //NOTE: To prevent duplicate ED collection we assume account already paid ED //if it has any amount of `asset`(exists in the storage). - if orml_tokens::Accounts::::try_get(to, asset).is_err() && !AssetRegistry::is_sufficient(asset) { + if !orml_tokens::Accounts::::contains_key(to, asset) && !AssetRegistry::is_sufficient(asset) { let fee_payment_asset = MultiTransactionPayment::account_currency(paying_account); let ed_in_fee_asset = MultiTransactionPayment::price(fee_payment_asset) diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 9851a05a7..30ae49493 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -40,6 +40,8 @@ pub trait Inspect { fn decimals(id: Self::AssetId) -> Option; fn asset_type(id: Self::AssetId) -> Option; + + fn is_blacklisted(id: Self::AssetId) -> bool; } #[allow(clippy::too_many_arguments)] From 9b8f0b4f0ccd293cc9c6feb88e5a811b2cbd763e Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 4 Dec 2023 13:26:58 +0100 Subject: [PATCH 70/93] asset-registry: rebenchmarked weights --- pallets/asset-registry/src/lib.rs | 6 ++-- pallets/asset-registry/src/weights.rs | 40 +++++++++++++++++++++++++ runtime/hydradx/src/weights/registry.rs | 40 ++++++++++++++++++------- 3 files changed, 71 insertions(+), 15 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index d374c8228..60fb317ad 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -542,8 +542,7 @@ pub mod pallet { } #[pallet::call_index(5)] - //#[pallet::weight(::WeightInfo::register_external())] - #[pallet::weight(1000)] + #[pallet::weight(::WeightInfo::blacklist_add())] pub fn blacklist_add(origin: OriginFor, asset_id: T::AssetId) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; @@ -561,8 +560,7 @@ pub mod pallet { } #[pallet::call_index(6)] - //#[pallet::weight(::WeightInfo::register_external())] - #[pallet::weight(1000)] + #[pallet::weight(::WeightInfo::blacklist_remove())] pub fn blacklist_remove(origin: OriginFor, asset_id: T::AssetId) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; diff --git a/pallets/asset-registry/src/weights.rs b/pallets/asset-registry/src/weights.rs index 230427a32..32231be55 100644 --- a/pallets/asset-registry/src/weights.rs +++ b/pallets/asset-registry/src/weights.rs @@ -50,6 +50,8 @@ pub trait WeightInfo { fn register() -> Weight; fn update() -> Weight; fn register_external() -> Weight; + fn blacklist_add() -> Weight; + fn blacklist_remove() -> Weight; } /// Weights for pallet_asset_registry using the hydraDX node and recommended hardware. pub struct HydraWeight(PhantomData); @@ -99,6 +101,25 @@ impl WeightInfo for HydraWeight { .saturating_add(T::DbWeight::get().reads(4 as u64)) .saturating_add(T::DbWeight::get().writes(6 as u64)) } + + // Storage: AssetRegistry Assets (r:1 w:0) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) + // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) + fn blacklist_add() -> Weight { + // Minimum execution time: 22_677 nanoseconds. + Weight::from_ref_time(22_950_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) + // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) + fn blacklist_remove() -> Weight { + // Minimum execution time: 17_460 nanoseconds. + Weight::from_ref_time(17_958_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } } impl WeightInfo for () { @@ -146,4 +167,23 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(4 as u64)) .saturating_add(RocksDbWeight::get().writes(6 as u64)) } + + // Storage: AssetRegistry Assets (r:1 w:0) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) + // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) + fn blacklist_add() -> Weight { + // Minimum execution time: 22_677 nanoseconds. + Weight::from_ref_time(22_950_000 as u64) + .saturating_add(RocksDbWeight::get().reads(2 as u64)) + .saturating_add(RocksDbWeight::get().writes(1 as u64)) + } + // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) + // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) + fn blacklist_remove() -> Weight { + // Minimum execution time: 17_460 nanoseconds. + Weight::from_ref_time(17_958_000 as u64) + .saturating_add(RocksDbWeight::get().reads(1 as u64)) + .saturating_add(RocksDbWeight::get().writes(1 as u64)) + } } diff --git a/runtime/hydradx/src/weights/registry.rs b/runtime/hydradx/src/weights/registry.rs index df84cfcce..0b93095a9 100644 --- a/runtime/hydradx/src/weights/registry.rs +++ b/runtime/hydradx/src/weights/registry.rs @@ -18,7 +18,7 @@ //! Autogenerated weights for pallet_asset_registry //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-13, STEPS: 10, REPEAT: 30, LOW RANGE: [], HIGH RANGE: [] +//! DATE: 2023-12-04, STEPS: 10, REPEAT: 30, LOW RANGE: [], HIGH RANGE: [] //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: @@ -33,7 +33,7 @@ // --heap-pages=4096 // --template=.maintain/pallet-weight-template-no-back.hbs // --pallet=pallet_asset_registry -// --output=weights.rs +// --output=registry.rs // --extrinsic=* #![allow(unused_parens)] @@ -59,10 +59,10 @@ impl WeightInfo for HydraWeight { // Storage: AssetRegistry LocationAssets (r:1 w:1) // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry AssetLocations (r:0 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) fn register() -> Weight { - // Minimum execution time: 37_420 nanoseconds. - Weight::from_ref_time(38_232_000 as u64) + // Minimum execution time: 40_681 nanoseconds. + Weight::from_ref_time(41_321_000 as u64) .saturating_add(T::DbWeight::get().reads(3 as u64)) .saturating_add(T::DbWeight::get().writes(4 as u64)) } @@ -71,12 +71,12 @@ impl WeightInfo for HydraWeight { // Storage: AssetRegistry AssetIds (r:1 w:2) // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) // Storage: AssetRegistry AssetLocations (r:1 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry LocationAssets (r:0 w:1) // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) fn update() -> Weight { - // Minimum execution time: 45_094 nanoseconds. - Weight::from_ref_time(46_207_000 as u64) + // Minimum execution time: 49_934 nanoseconds. + Weight::from_ref_time(50_392_000 as u64) .saturating_add(T::DbWeight::get().reads(3 as u64)) .saturating_add(T::DbWeight::get().writes(5 as u64)) } @@ -87,13 +87,31 @@ impl WeightInfo for HydraWeight { // Storage: AssetRegistry LocationAssets (r:1 w:1) // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry AssetLocations (r:0 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(614), added: 3089, mode: MaxEncodedLen) + // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) // Storage: AssetRegistry Assets (r:0 w:1) // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) fn register_external() -> Weight { - // Minimum execution time: 62_277 nanoseconds. - Weight::from_ref_time(63_068_000 as u64) + // Minimum execution time: 62_510 nanoseconds. + Weight::from_ref_time(63_275_000 as u64) .saturating_add(T::DbWeight::get().reads(4 as u64)) .saturating_add(T::DbWeight::get().writes(6 as u64)) } + // Storage: AssetRegistry Assets (r:1 w:0) + // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) + // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) + fn blacklist_add() -> Weight { + // Minimum execution time: 22_677 nanoseconds. + Weight::from_ref_time(22_950_000 as u64) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } + // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) + // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) + fn blacklist_remove() -> Weight { + // Minimum execution time: 17_460 nanoseconds. + Weight::from_ref_time(17_958_000 as u64) + .saturating_add(T::DbWeight::get().reads(1 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) + } } From 346e444cf97b46d40b8e21dfa94ca75aaccae8d1 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 5 Dec 2023 11:14:51 +0100 Subject: [PATCH 71/93] sufficiencyCheck: added defensive handling --- runtime/hydradx/src/assets.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index a3a134e2a..eb4f8f0ce 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -235,7 +235,8 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { SUFFICIENCY_LOCK, NativeAssetId::get(), &TreasuryAccount::get(), - ); + ) + .defensive(); } else { let _ = >::set_lock( SUFFICIENCY_LOCK, From 949fdb5f27d7a2631276c15cf43b37973d187c4e Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 24 Jan 2024 12:37:45 +0100 Subject: [PATCH 72/93] asset-registry: fixed PoolShare migration --- Cargo.lock | 2 +- pallets/asset-registry/src/migration.rs | 30 +++++++++++++++++++++---- runtime/hydradx/Cargo.toml | 2 +- runtime/hydradx/src/lib.rs | 2 +- 4 files changed, 29 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2f0e36689..b5ff30af8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4618,7 +4618,7 @@ dependencies = [ [[package]] name = "hydradx-runtime" -version = "205.0.0" +version = "206.0.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", diff --git a/pallets/asset-registry/src/migration.rs b/pallets/asset-registry/src/migration.rs index d976ec897..1d0da1840 100644 --- a/pallets/asset-registry/src/migration.rs +++ b/pallets/asset-registry/src/migration.rs @@ -32,10 +32,20 @@ pub mod v1 { use sp_core::RuntimeDebug; use sp_runtime::BoundedVec; + #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, TypeInfo, MaxEncodedLen)] + pub enum AssetType { + Token, + PoolShare(AssetId, AssetId), // Use XYX instead + XYK, + StableSwap, + Bond, + External, + } + #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, TypeInfo)] - pub struct AssetDetails { + pub struct AssetDetails { pub name: BoundedString, - pub asset_type: AssetType, + pub asset_type: AssetType, pub existential_deposit: Balance, pub xcm_rate_limit: Option, } @@ -51,7 +61,7 @@ pub mod v1 { Pallet, Twox64Concat, ::AssetId, - AssetDetails::StringLimit>>, + AssetDetails<::AssetId, Balance, BoundedVec::StringLimit>>, OptionQuery, >; @@ -77,6 +87,18 @@ pub mod v1 { pub mod v2 { use super::*; + impl From> for AssetType { + fn from(value: v1::AssetType) -> Self { + match value { + v1::AssetType::Token => Self::Token, + v1::AssetType::PoolShare(_, _) => Self::XYK, + v1::AssetType::XYK => Self::XYK, + v1::AssetType::StableSwap => Self::StableSwap, + v1::AssetType::Bond => Self::Bond, + v1::AssetType::External => Self::External, + } + } + } pub fn pre_migrate() { assert_eq!(StorageVersion::get::>(), 1, "Storage version too high."); @@ -118,7 +140,7 @@ pub mod v2 { k, AssetDetails { name: Some(v.name), - asset_type: v.asset_type, + asset_type: v.asset_type.into(), existential_deposit: v.existential_deposit, symbol, decimals, diff --git a/runtime/hydradx/Cargo.toml b/runtime/hydradx/Cargo.toml index 28f8de74a..501190821 100644 --- a/runtime/hydradx/Cargo.toml +++ b/runtime/hydradx/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-runtime" -version = "205.0.0" +version = "206.0.0" authors = ["GalacticCouncil"] edition = "2021" license = "Apache 2.0" diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index 0786950f8..ed07a09b6 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -107,7 +107,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("hydradx"), impl_name: create_runtime_str!("hydradx"), authoring_version: 1, - spec_version: 205, + spec_version: 206, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, From 31d7159b742131ad30ce71025c67b2d724ea08f0 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 24 Jan 2024 14:05:12 +0100 Subject: [PATCH 73/93] asset-registry: call correct asset registry migration --- pallets/asset-registry/src/lib.rs | 2 +- runtime/hydradx/src/migrations.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index c74320586..9107974a2 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -66,7 +66,7 @@ pub mod pallet { use super::*; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); pub type AssetDetailsT = AssetDetails<::StringLimit>; diff --git a/runtime/hydradx/src/migrations.rs b/runtime/hydradx/src/migrations.rs index ea9a9c788..07903cc78 100644 --- a/runtime/hydradx/src/migrations.rs +++ b/runtime/hydradx/src/migrations.rs @@ -24,8 +24,8 @@ impl OnRuntimeUpgrade for OnRuntimeUpgradeMigration { log::info!("Migrate Asset Registry Pallet"); weight = weight - .saturating_add(pallet_collator_selection::migration::v1::MigrateToV1::::on_runtime_upgrade()); - log::info!("Migrate Asset Registry Pallet"); + .saturating_add(pallet_asset_registry::migration::v2::migrate::()); + log::info!("Migrate Asset Registry Pallet end"); log::info!("Migrate Collator Selection Pallet to v1 start"); weight = weight From 1fe9a6f0872dcb51cdf8caf0a023fa3dfc0f23b7 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 24 Jan 2024 14:13:21 +0100 Subject: [PATCH 74/93] rustfmt --- runtime/hydradx/src/migrations.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/runtime/hydradx/src/migrations.rs b/runtime/hydradx/src/migrations.rs index 07903cc78..653eb51e0 100644 --- a/runtime/hydradx/src/migrations.rs +++ b/runtime/hydradx/src/migrations.rs @@ -23,8 +23,7 @@ impl OnRuntimeUpgrade for OnRuntimeUpgradeMigration { let mut weight: Weight = Weight::zero(); log::info!("Migrate Asset Registry Pallet"); - weight = weight - .saturating_add(pallet_asset_registry::migration::v2::migrate::()); + weight = weight.saturating_add(pallet_asset_registry::migration::v2::migrate::()); log::info!("Migrate Asset Registry Pallet end"); log::info!("Migrate Collator Selection Pallet to v1 start"); From 0fd752fe0645d0532c796c66031e6fc712588653 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 26 Jan 2024 13:52:29 +0100 Subject: [PATCH 75/93] asset-registry: use BoundedVec for Name and Symbol instead of Vec --- pallets/asset-registry/src/lib.rs | 119 ++--- .../asset-registry/src/tests/create_trait.rs | 133 +++--- .../asset-registry/src/tests/inspect_trait.rs | 90 +++- pallets/asset-registry/src/tests/mock.rs | 9 +- .../asset-registry/src/tests/mutate_trait.rs | 4 +- pallets/asset-registry/src/tests/register.rs | 261 ++++++----- pallets/asset-registry/src/tests/tests.rs | 150 +++++- pallets/asset-registry/src/tests/update.rs | 426 ++++++++++++------ pallets/asset-registry/src/types.rs | 7 +- traits/src/registry.rs | 26 +- 10 files changed, 782 insertions(+), 443 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 9107974a2..3b78999a0 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -46,7 +46,7 @@ pub use types::AssetType; // Re-export pallet items so that they can be accessed from the crate namespace. pub use pallet::*; -pub use crate::types::{AssetDetails, Balance}; +pub use crate::types::{AssetDetails, Balance, Name, Symbol}; use frame_support::storage::with_transaction; use frame_support::BoundedVec; use hydradx_traits::{ @@ -239,16 +239,16 @@ pub mod pallet { //asset_id, name, existential deposit, symbol, decimals, xcm_rate_limit, is_sufficient pub registered_assets: Vec<( Option, - Option>, + Option>, Balance, - Option>, + Option>, Option, Option, bool, )>, - pub native_asset_name: Vec, + pub native_asset_name: Name, pub native_existential_deposit: Balance, - pub native_symbol: Vec, + pub native_symbol: Symbol, pub native_decimals: u8, } @@ -256,9 +256,9 @@ pub mod pallet { fn default() -> Self { GenesisConfig:: { registered_assets: sp_std::vec![], - native_asset_name: b"HDX".to_vec(), + native_asset_name: b"HDX".to_vec().try_into().expect("Invalid native asset name!"), native_existential_deposit: DEFAULT_ED, - native_symbol: b"HDX".to_vec(), + native_symbol: b"HDX".to_vec().try_into().expect("Invalid native asset symbol!"), native_decimals: 12, } } @@ -269,23 +269,14 @@ pub mod pallet { with_transaction(|| { // Register native asset first // It is to make sure that native is registered as any other asset - let native_asset_name = Pallet::::try_into_bounded(Some(self.native_asset_name.to_vec())) - .expect("Invalid native asset name!"); - - let native_symbol = Pallet::::try_into_bounded(Some(self.native_symbol.to_vec())) - .expect("Invalid native asset symbol!"); - let native_asset_id = T::AssetId::from(0); - AssetIds::::insert( - native_asset_name.as_ref().expect("Invalid native asset name!"), - native_asset_id, - ); + AssetIds::::insert(&self.native_asset_name, native_asset_id); let details = AssetDetails { - name: native_asset_name, + name: Some(self.native_asset_name.clone()), asset_type: AssetType::Token, existential_deposit: self.native_existential_deposit, xcm_rate_limit: None, - symbol: native_symbol, + symbol: Some(self.native_symbol.clone()), decimals: Some(self.native_decimals), is_sufficient: true, }; @@ -294,23 +285,12 @@ pub mod pallet { self.registered_assets.iter().for_each( |(id, name, ed, symbol, decimals, xcm_rate_limit, is_sufficient)| { - let bounded_name = name.as_ref().map(|name| { - Pallet::::try_into_bounded(Some(name.to_vec())) - .expect("Invalid asset name!") - .unwrap() - }); - let bounded_symbol = symbol.as_ref().map(|symbol| { - Pallet::::try_into_bounded(Some(symbol.to_vec())) - .expect("Invalid symbol!") - .unwrap() - }); - let details = AssetDetails { - name: bounded_name, + name: name.clone(), asset_type: AssetType::Token, existential_deposit: *ed, xcm_rate_limit: *xcm_rate_limit, - symbol: bounded_symbol, + symbol: symbol.clone(), decimals: *decimals, is_sufficient: *is_sufficient, }; @@ -392,10 +372,10 @@ pub mod pallet { pub fn register( origin: OriginFor, asset_id: Option, - name: Option>, + name: Option>, asset_type: AssetType, existential_deposit: Option, - symbol: Option>, + symbol: Option>, decimals: Option, location: Option, xcm_rate_limit: Option, @@ -403,14 +383,11 @@ pub mod pallet { ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; - let bounded_name = Self::try_into_bounded(name)?; - let bounded_symbol = Self::try_into_bounded(symbol)?; - let details = AssetDetails::new( - bounded_name, + name, asset_type, existential_deposit.unwrap_or(DEFAULT_ED), - bounded_symbol, + symbol, decimals, xcm_rate_limit, is_sufficient, @@ -435,12 +412,12 @@ pub mod pallet { pub fn update( origin: OriginFor, asset_id: T::AssetId, - name: Option>, + name: Option>, asset_type: Option, existential_deposit: Option, xcm_rate_limit: Option, is_sufficient: Option, - symbol: Option>, + symbol: Option>, decimals: Option, location: Option, ) -> DispatchResult { @@ -452,8 +429,7 @@ pub mod pallet { Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { let detail = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; - let new_bounded_name = Self::try_into_bounded(name)?; - if let Some(new_name) = new_bounded_name.as_ref() { + if let Some(new_name) = name.as_ref() { ensure!(Self::asset_ids(new_name).is_none(), Error::::AssetAlreadyRegistered); if let Some(old_name) = &detail.name { @@ -464,13 +440,12 @@ pub mod pallet { AssetIds::::insert(new_name, asset_id); } }; - let bounded_symbol = Self::try_into_bounded(symbol)?; - detail.name = new_bounded_name.or_else(|| detail.name.clone()); + detail.name = name.or_else(|| detail.name.clone()); detail.asset_type = asset_type.unwrap_or(detail.asset_type); detail.existential_deposit = existential_deposit.unwrap_or(detail.existential_deposit); detail.xcm_rate_limit = xcm_rate_limit.or(detail.xcm_rate_limit); - detail.symbol = bounded_symbol.or_else(|| detail.symbol.clone()); + detail.symbol = symbol.or_else(|| detail.symbol.clone()); let suff = is_sufficient.unwrap_or(detail.is_sufficient); if detail.is_sufficient != suff { @@ -588,15 +563,6 @@ impl Pallet { NextAssetId::::get().checked_add(&T::SequentialIdStartAt::get()) } - /// Convert Vec to BoundedVec so it respects the max set limit, otherwise return TooLong error - pub fn try_into_bounded(name: Option>) -> Result>, Error> { - let Some(s) = name else { - return Ok(None); - }; - - s.try_into().map_err(|_| Error::::TooLong).map(Some) - } - fn do_set_location(asset_id: T::AssetId, location: T::AssetNativeLocation) -> Result<(), DispatchError> { ensure!( Self::location_assets(&location).is_none(), @@ -662,25 +628,20 @@ impl Pallet { /// Create asset for given name or return existing AssetId if such asset already exists. pub fn get_or_create_asset( - name: Vec, + name: Name, asset_type: AssetType, existential_deposit: Balance, asset_id: Option, is_sufficient: bool, ) -> Result { - let bounded_name = Self::try_into_bounded(Some(name))?; - - if let Some(asset_id) = AssetIds::::get( - bounded_name - .as_ref() - .ok_or_else(|| -> pallet::Error { InconsistentStateError::BoundedConversionFailed.into() })?, - ) { + //TODO: remove this fn + if let Some(asset_id) = AssetIds::::get(&name) { Ok(asset_id) } else { Self::do_register_asset( asset_id, &AssetDetails::new( - bounded_name, + Some(name), asset_type, existential_deposit, None, @@ -776,26 +737,25 @@ impl Mutate for Pallet { impl Create for Pallet { type Error = DispatchError; + type Name = Name; + type Symbol = Symbol; fn register_asset( asset_id: Option, - name: Option<&[u8]>, + name: Option, kind: AssetKind, existential_deposit: Option, - symbol: Option<&[u8]>, + symbol: Option, decimals: Option, location: Option, xcm_rate_limit: Option, is_sufficient: bool, ) -> Result { - let bounded_name = Self::try_into_bounded(name.map(|x| x.to_vec()))?; - let bounded_symbol = Self::try_into_bounded(symbol.map(|x| x.to_vec()))?; - let details = AssetDetails::new( - bounded_name, + name, kind.into(), existential_deposit.unwrap_or(DEFAULT_ED), - bounded_symbol, + symbol, decimals, xcm_rate_limit, is_sufficient, @@ -805,31 +765,24 @@ impl Create for Pallet { } fn get_or_register_asset( - name: &[u8], + name: Self::Name, kind: AssetKind, existential_deposit: Option, - symbol: Option<&[u8]>, + symbol: Option, decimals: Option, location: Option, xcm_rate_limit: Option, is_sufficient: bool, ) -> Result { //NOTE: in this case `try_into_bounded()` should never return None. - let bounded_name = match Self::try_into_bounded(Some(name.to_vec()))? { - Some(n) => n, - None => return Err(Error::::InconsistentState(InconsistentStateError::BoundedConversionFailed).into()), - }; - - match Self::asset_ids(bounded_name.clone()) { + match Self::asset_ids(&name) { Some(id) => Ok(id), None => { - let bounded_symbol = Self::try_into_bounded(symbol.map(|x| x.to_vec()))?; - let details = AssetDetails::new( - Some(bounded_name), + Some(name), kind.into(), existential_deposit.unwrap_or(DEFAULT_ED), - bounded_symbol, + symbol, decimals, xcm_rate_limit, is_sufficient, diff --git a/pallets/asset-registry/src/tests/create_trait.rs b/pallets/asset-registry/src/tests/create_trait.rs index 0e00f17ca..a658e5fba 100644 --- a/pallets/asset-registry/src/tests/create_trait.rs +++ b/pallets/asset-registry/src/tests/create_trait.rs @@ -16,8 +16,8 @@ fn register_asset_should_work() { ExtBuilder::default().build().execute_with(|| { let _ = with_transaction(|| { let asset_id = 1; - let name = b"Test asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -29,10 +29,10 @@ fn register_asset_should_work() { //Act assert_ok!(>::register_asset( Some(asset_id), - Some(&name), + Some(name.clone()), AssetKind::XYK, Some(ed), - Some(&symbol), + Some(symbol.clone()), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), @@ -40,22 +40,20 @@ fn register_asset_should_work() { )); //Assert - let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); - let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(asset_id), Some(AssetDetails { - name: bounded_name.clone(), + name: Some(name.clone()), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol.clone(), + symbol: Some(symbol.clone()), decimals: Some(decimals), is_sufficient }) ); - assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(asset_id)); + assert_eq!(Registry::asset_ids(name.clone()), Some(asset_id)); assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); @@ -63,11 +61,11 @@ fn register_asset_should_work() { assert!(has_event( Event::::Registered { asset_id, - asset_name: bounded_name, + asset_name: Some(name), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol, + symbol: Some(symbol), decimals: Some(decimals), is_sufficient } @@ -92,8 +90,8 @@ fn register_insufficient_asset_should_work() { ExtBuilder::default().build().execute_with(|| { let _ = with_transaction(|| { let asset_id = 1; - let name = b"Test asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -104,32 +102,30 @@ fn register_insufficient_asset_should_work() { //Act assert_ok!(>::register_insufficient_asset( Some(asset_id), - Some(&name), + Some(name.clone()), AssetKind::XYK, Some(ed), - Some(&symbol), + Some(symbol.clone()), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), )); //Assert - let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); - let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(asset_id), Some(AssetDetails { - name: bounded_name.clone(), + name: Some(name.clone()), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol.clone(), + symbol: Some(symbol.clone()), decimals: Some(decimals), is_sufficient: false }) ); - assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(asset_id)); + assert_eq!(Registry::asset_ids(name.clone()), Some(asset_id)); assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); @@ -137,11 +133,11 @@ fn register_insufficient_asset_should_work() { assert!(has_event( Event::::Registered { asset_id, - asset_name: bounded_name, + asset_name: Some(name), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol, + symbol: Some(symbol), decimals: Some(decimals), is_sufficient: false } @@ -166,8 +162,8 @@ fn register_sufficient_asset_should_work() { ExtBuilder::default().build().execute_with(|| { let _ = with_transaction(|| { let asset_id = 1; - let name = b"Test asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -178,32 +174,30 @@ fn register_sufficient_asset_should_work() { //Act assert_ok!(>::register_sufficient_asset( Some(asset_id), - Some(&name), + Some(name.clone()), AssetKind::XYK, ed, - Some(&symbol), + Some(symbol.clone()), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), )); //Assert - let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); - let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(asset_id), Some(AssetDetails { - name: bounded_name.clone(), + name: Some(name.clone()), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol.clone(), + symbol: Some(symbol.clone()), decimals: Some(decimals), is_sufficient: true }) ); - assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(asset_id)); + assert_eq!(Registry::asset_ids(name.clone()), Some(asset_id)); assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); @@ -211,11 +205,11 @@ fn register_sufficient_asset_should_work() { assert!(has_event( Event::::Registered { asset_id, - asset_name: bounded_name, + asset_name: Some(name), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol, + symbol: Some(symbol), decimals: Some(decimals), is_sufficient: true } @@ -240,8 +234,8 @@ fn get_or_register_asset_should_register_asset_when_does_not_exists() { ExtBuilder::default().build().execute_with(|| { let _ = with_transaction(|| { let new_asset_id = Registry::next_asset_id().unwrap(); - let name = b"Test asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -253,10 +247,10 @@ fn get_or_register_asset_should_register_asset_when_does_not_exists() { //Act assert_ok!( >::get_or_register_asset( - &name, + name.clone(), AssetKind::XYK, Some(ed), - Some(&symbol), + Some(symbol.clone()), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), @@ -266,22 +260,20 @@ fn get_or_register_asset_should_register_asset_when_does_not_exists() { ); //Assert - let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); - let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(new_asset_id), Some(AssetDetails { - name: bounded_name.clone(), + name: Some(name.clone()), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol.clone(), + symbol: Some(symbol.clone()), decimals: Some(decimals), is_sufficient }) ); - assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(new_asset_id)); + assert_eq!(Registry::asset_ids(name.clone()), Some(new_asset_id)); assert_eq!(Registry::location_assets(asset_location.clone()), Some(new_asset_id)); assert_eq!(Registry::locations(new_asset_id), Some(asset_location.clone())); @@ -289,11 +281,11 @@ fn get_or_register_asset_should_register_asset_when_does_not_exists() { assert!(has_event( Event::::Registered { asset_id: new_asset_id, - asset_name: bounded_name, + asset_name: Some(name), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol, + symbol: Some(symbol), decimals: Some(decimals), is_sufficient } @@ -319,7 +311,7 @@ fn get_or_register_asset_should_return_asset_id_when_asset_exists() { ExtBuilder::default() .with_assets(vec![( Some(existing_asset_id), - Some(b"Asset".to_vec()), + Some(b"Asset".to_vec().try_into().unwrap()), UNIT, None, None, @@ -329,8 +321,8 @@ fn get_or_register_asset_should_return_asset_id_when_asset_exists() { .build() .execute_with(|| { let _ = with_transaction(|| { - let name = b"Asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -342,10 +334,10 @@ fn get_or_register_asset_should_return_asset_id_when_asset_exists() { //Act assert_ok!( >::get_or_register_asset( - &name, + name.clone(), AssetKind::XYK, Some(ed), - Some(&symbol), + Some(symbol.clone()), Some(decimals), Some(asset_location), Some(xcm_rate_limit), @@ -355,11 +347,10 @@ fn get_or_register_asset_should_return_asset_id_when_asset_exists() { ); //Assert - let bounded_name = Pallet::::try_into_bounded(Some(b"Asset".to_vec())).unwrap(); assert_eq!( Registry::assets(existing_asset_id), Some(AssetDetails { - name: bounded_name, + name: Some(name), asset_type: AssetType::Token, existential_deposit: UNIT, xcm_rate_limit: None, @@ -379,8 +370,8 @@ fn get_or_register_sufficient_asset_should_work() { ExtBuilder::default().build().execute_with(|| { let _ = with_transaction(|| { let new_asset_id = Registry::next_asset_id().unwrap(); - let name = b"Test asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -390,32 +381,30 @@ fn get_or_register_sufficient_asset_should_work() { //Act assert_ok!(>::get_or_register_sufficient_asset( - &name, + name.clone(), AssetKind::XYK, ed, - Some(&symbol), + Some(symbol.clone()), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), ),); //Assert - let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); - let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(new_asset_id), Some(AssetDetails { - name: bounded_name.clone(), + name: Some(name.clone()), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol.clone(), + symbol: Some(symbol.clone()), decimals: Some(decimals), is_sufficient: true }) ); - assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(new_asset_id)); + assert_eq!(Registry::asset_ids(name.clone()), Some(new_asset_id)); assert_eq!(Registry::location_assets(asset_location.clone()), Some(new_asset_id)); assert_eq!(Registry::locations(new_asset_id), Some(asset_location.clone())); @@ -423,11 +412,11 @@ fn get_or_register_sufficient_asset_should_work() { assert!(has_event( Event::::Registered { asset_id: new_asset_id, - asset_name: bounded_name, + asset_name: Some(name), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol, + symbol: Some(symbol), decimals: Some(decimals), is_sufficient: true } @@ -452,8 +441,8 @@ fn get_or_register_insufficient_asset_should_work() { ExtBuilder::default().build().execute_with(|| { let _ = with_transaction(|| { let new_asset_id = Registry::next_asset_id().unwrap(); - let name = b"Test asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -463,32 +452,30 @@ fn get_or_register_insufficient_asset_should_work() { //Act assert_ok!(>::get_or_register_insufficient_asset( - &name, + name.clone(), AssetKind::XYK, Some(ed), - Some(&symbol), + Some(symbol.clone()), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), ),); //Assert - let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); - let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(new_asset_id), Some(AssetDetails { - name: bounded_name.clone(), + name: Some(name.clone()), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol.clone(), + symbol: Some(symbol.clone()), decimals: Some(decimals), is_sufficient: false }) ); - assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(new_asset_id)); + assert_eq!(Registry::asset_ids(name.clone()), Some(new_asset_id)); assert_eq!(Registry::location_assets(asset_location.clone()), Some(new_asset_id)); assert_eq!(Registry::locations(new_asset_id), Some(asset_location.clone())); @@ -496,11 +483,11 @@ fn get_or_register_insufficient_asset_should_work() { assert!(has_event( Event::::Registered { asset_id: new_asset_id, - asset_name: bounded_name, + asset_name: Some(name), asset_type: AssetType::XYK, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol, + symbol: Some(symbol), decimals: Some(decimals), is_sufficient: false } diff --git a/pallets/asset-registry/src/tests/inspect_trait.rs b/pallets/asset-registry/src/tests/inspect_trait.rs index e73e14194..3c407e03a 100644 --- a/pallets/asset-registry/src/tests/inspect_trait.rs +++ b/pallets/asset-registry/src/tests/inspect_trait.rs @@ -17,7 +17,7 @@ fn is_sufficient_should_work() { .with_assets(vec![ ( Some(suff_asset_id), - Some(b"Suff".to_vec()), + Some(b"Suff".to_vec().try_into().unwrap()), UNIT, None, None, @@ -26,7 +26,7 @@ fn is_sufficient_should_work() { ), ( Some(insuff_asset_id), - Some(b"Insuff".to_vec()), + Some(b"Insuff".to_vec().try_into().unwrap()), UNIT, None, None, @@ -52,7 +52,7 @@ fn exists_should_work() { ExtBuilder::default() .with_assets(vec![( Some(asset_id), - Some(b"Suff".to_vec()), + Some(b"Suff".to_vec().try_into().unwrap()), UNIT, None, None, @@ -73,9 +73,33 @@ fn decimals_should_work() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"TKN1".to_vec()), UNIT, None, Some(5_u8), None, true), - (Some(2), Some(b"TKN2".to_vec()), UNIT, None, Some(0_u8), None, true), - (Some(3), Some(b"TKN3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"TKN1".to_vec().try_into().unwrap()), + UNIT, + None, + Some(5_u8), + None, + true, + ), + ( + Some(2), + Some(b"TKN2".to_vec().try_into().unwrap()), + UNIT, + None, + Some(0_u8), + None, + true, + ), + ( + Some(3), + Some(b"TKN3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -136,8 +160,24 @@ fn asset_type_should_work() { fn is_blacklisted_should_work() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Suff".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Insuff".to_vec()), UNIT, None, None, None, false), + ( + Some(1), + Some(b"Suff".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Insuff".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + false, + ), ]) .build() .execute_with(|| { @@ -159,9 +199,25 @@ fn asset_name_should_work() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(asset_one_name.clone()), UNIT, None, None, None, true), + ( + Some(1), + Some(asset_one_name.clone().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), (Some(2), None, UNIT, None, None, None, false), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -183,15 +239,23 @@ fn asset_symbol_should_work() { .with_assets(vec![ ( Some(1), - Some(b"Tkn1".to_vec()), + Some(b"Tkn1".to_vec().try_into().unwrap()), UNIT, - Some(asset_one_symbol.clone()), + Some(asset_one_symbol.clone().try_into().unwrap()), None, None, true, ), (Some(2), None, UNIT, None, None, None, false), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { diff --git a/pallets/asset-registry/src/tests/mock.rs b/pallets/asset-registry/src/tests/mock.rs index 5749432ca..261d27a02 100644 --- a/pallets/asset-registry/src/tests/mock.rs +++ b/pallets/asset-registry/src/tests/mock.rs @@ -31,6 +31,7 @@ use frame_support::traits::Everything; use polkadot_xcm::v3::MultiLocation; use crate as pallet_asset_registry; +use crate::types::{Name, Symbol}; pub type AssetId = u32; pub type Balance = u128; @@ -137,9 +138,9 @@ impl orml_tokens::Config for Test { pub struct ExtBuilder { registered_assets: Vec<( Option, - Option>, + Option>, Balance, - Option>, + Option>, Option, Option, bool, @@ -152,9 +153,9 @@ impl ExtBuilder { mut self, assets: Vec<( Option, - Option>, + Option>, Balance, - Option>, + Option>, Option, Option, bool, diff --git a/pallets/asset-registry/src/tests/mutate_trait.rs b/pallets/asset-registry/src/tests/mutate_trait.rs index 0477fe167..991a5b557 100644 --- a/pallets/asset-registry/src/tests/mutate_trait.rs +++ b/pallets/asset-registry/src/tests/mutate_trait.rs @@ -15,7 +15,7 @@ fn set_location_should_work_when_location_was_not_set_yet() { ExtBuilder::default() .with_assets(vec![( Some(asset_id), - Some(b"Suff".to_vec()), + Some(b"Suff".to_vec().try_into().unwrap()), UNIT, None, None, @@ -43,7 +43,7 @@ fn set_location_should_not_work_when_location_was_not() { ExtBuilder::default() .with_assets(vec![( Some(asset_id), - Some(b"Suff".to_vec()), + Some(b"Suff".to_vec().try_into().unwrap()), UNIT, None, None, diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index b5bcfbba2..de5203f61 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -3,6 +3,7 @@ use super::*; use crate::types::AssetType; use frame_support::error::BadOrigin; use frame_support::traits::tokens::fungibles::Mutate as MutateFungibles; +use mock::RegistryStringLimit; use mock::{AssetId, Registry}; use polkadot_xcm::v3::{ Junction::{self, Parachain}, @@ -15,8 +16,8 @@ use pretty_assertions::assert_eq; fn register_should_work_when_all_params_are_provided() { ExtBuilder::default().build().execute_with(|| { let asset_id = 1; - let name = b"Test asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -40,22 +41,20 @@ fn register_should_work_when_all_params_are_provided() { )); //Assert - let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); - let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(asset_id), Some(AssetDetails { - name: bounded_name.clone(), + name: Some(name.clone()), asset_type: AssetType::Token, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol.clone(), + symbol: Some(symbol.clone()), decimals: Some(decimals), is_sufficient }) ); - assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()), Some(asset_id)); + assert_eq!(Registry::asset_ids(name.clone()), Some(asset_id)); assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location.clone())); @@ -63,11 +62,11 @@ fn register_should_work_when_all_params_are_provided() { assert!(has_event( Event::::Registered { asset_id, - asset_name: bounded_name, + asset_name: Some(name), asset_type: AssetType::Token, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol, + symbol: Some(symbol), decimals: Some(decimals), is_sufficient } @@ -138,8 +137,8 @@ fn register_should_work_when_only_required_params_were_provided() { fn register_should_not_work_when_asset_id_is_not_from_reserved_range() { ExtBuilder::default().build().execute_with(|| { let asset_id: AssetId = Pallet::::next_asset_id().unwrap(); - let name = b"Test asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -171,15 +170,39 @@ fn register_should_not_work_when_asset_id_is_not_from_reserved_range() { fn register_should_not_work_when_asset_id_is_already_used() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { let asset_id = 1; - let name = b"Test asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -211,15 +234,39 @@ fn register_should_not_work_when_asset_id_is_already_used() { fn register_should_not_work_when_asset_name_is_already_used() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { let asset_id = 4; - let name = b"Tkn3".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Tkn3".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -251,9 +298,33 @@ fn register_should_not_work_when_asset_name_is_already_used() { fn register_should_not_work_when_asset_location_is_already_used() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -264,8 +335,8 @@ fn register_should_not_work_when_asset_location_is_already_used() { let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); Pallet::::set_location(3, asset_location.clone()).unwrap(); - let name = b"Tkn4".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Tkn4".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -294,17 +365,41 @@ fn register_should_not_work_when_asset_location_is_already_used() { fn register_should_not_work_when_origin_is_none() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { //Arrange let asset_id = 4; - let name = b"Tkn4".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Tkn4".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -336,17 +431,41 @@ fn register_should_not_work_when_origin_is_none() { fn register_should_not_work_when_origin_is_not_allowed() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { //Arrange let asset_id = 4; - let name = b"Tkn4".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Tkn4".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -444,8 +563,8 @@ fn register_external_asset_should_not_work_when_location_is_already_used() { ExtBuilder::default().build().execute_with(|| { //Arrange let asset_id = 1; - let name = b"Test asset".to_vec(); - let symbol = b"TKN".to_vec(); + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); let decimals = 12; let xcm_rate_limit = 1_000; let ed = 10_000; @@ -502,69 +621,3 @@ fn register_external_asset_should_not_work_when_user_cant_pay_storage_fees() { ); }); } - -#[test] -fn register_should_fail_when_name_is_too_long() { - ExtBuilder::default().build().execute_with(|| { - let asset_id = 1; - let name = vec![97u8; ::StringLimit::get() as usize + 1]; - let symbol = b"TKN".to_vec(); - let decimals = 12; - let xcm_rate_limit = 1_000; - let ed = 10_000; - let is_sufficient = true; - - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - - //Act - assert_noop!( - Registry::register( - RuntimeOrigin::root(), - Some(asset_id), - Some(name), - AssetType::Token, - Some(ed), - Some(symbol), - Some(decimals), - Some(asset_location), - Some(xcm_rate_limit), - is_sufficient - ), - Error::::TooLong - ); - }); -} - -#[test] -fn register_should_fail_when_symbol_is_too_long() { - ExtBuilder::default().build().execute_with(|| { - let asset_id = 1; - let name = b"Test asset".to_vec(); - let symbol = vec![97u8; ::StringLimit::get() as usize + 1]; - let decimals = 12; - let xcm_rate_limit = 1_000; - let ed = 10_000; - let is_sufficient = true; - - let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - - //Act - assert_noop!( - Registry::register( - RuntimeOrigin::root(), - Some(asset_id), - Some(name), - AssetType::Token, - Some(ed), - Some(symbol), - Some(decimals), - Some(asset_location), - Some(xcm_rate_limit), - is_sufficient - ), - Error::::TooLong - ); - }); -} diff --git a/pallets/asset-registry/src/tests/tests.rs b/pallets/asset-registry/src/tests/tests.rs index 6bf147c22..5e7803d0b 100644 --- a/pallets/asset-registry/src/tests/tests.rs +++ b/pallets/asset-registry/src/tests/tests.rs @@ -7,9 +7,33 @@ use pretty_assertions::assert_eq; fn blacklist_add_should_work_when_asset_is_not_blacklisted() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"tkn2".to_vec()), UNIT, None, None, None, false), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + false, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -29,9 +53,33 @@ fn blacklist_add_should_fial_when_asset_is_already_blacklisted() { let asset_id: u32 = 1; ExtBuilder::default() .with_assets(vec![ - (Some(asset_id), Some(b"tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"tkn2".to_vec()), UNIT, None, None, None, false), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(asset_id), + Some(b"tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + false, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -52,9 +100,33 @@ fn blacklist_add_should_fial_when_asset_is_already_blacklisted() { fn blacklist_add_should_fail_when_asset_is_not_registered() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"tkn2".to_vec()), UNIT, None, None, None, false), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + false, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -74,9 +146,33 @@ fn blacklist_remove_should_work_when_asset_is_blacklisted() { let asset_id: u32 = 1; ExtBuilder::default() .with_assets(vec![ - (Some(asset_id), Some(b"tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"tkn2".to_vec()), UNIT, None, None, None, false), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(asset_id), + Some(b"tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + false, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -100,9 +196,33 @@ fn blacklist_remove_should_fail_when_asset_is_not_blacklisted() { let asset_id: u32 = 1; ExtBuilder::default() .with_assets(vec![ - (Some(asset_id), Some(b"tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"tkn2".to_vec()), UNIT, None, None, None, false), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(asset_id), + Some(b"tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + false, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index bcfff090e..7dc49461c 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -2,6 +2,7 @@ use super::*; use crate::types::AssetType; use mock::Registry; +use mock::RegistryStringLimit; use polkadot_xcm::v3::{ Junction::{self, Parachain}, Junctions::X2, @@ -14,17 +15,41 @@ fn update_should_work_when_asset_exists() { let old_asset_name = b"Tkn2".to_vec(); ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(old_asset_name.clone()), UNIT, None, None, None, false), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(old_asset_name.clone().try_into().unwrap()), + UNIT, + None, + None, + None, + false, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { let asset_id = 2; - let name = b"New Tkn 2".to_vec(); + let name: BoundedVec = b"New Tkn 2".to_vec().try_into().unwrap(); let ed = 10_000 * UNIT; let xcm_rate_limit = 463; - let symbol = b"nTkn2".to_vec(); + let symbol: BoundedVec = b"nTkn2".to_vec().try_into().unwrap(); let decimals = 23; let is_sufficient = true; @@ -48,16 +73,14 @@ fn update_should_work_when_asset_exists() { )); //Assert - let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); - let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(asset_id), Some(AssetDetails { - name: bounded_name.clone(), + name: Some(name.clone()), asset_type: AssetType::External, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol.clone(), + symbol: Some(symbol.clone()), decimals: Some(decimals), is_sufficient: true }) @@ -67,18 +90,20 @@ fn update_should_work_when_asset_exists() { assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location)); - let old_bounded_name = Pallet::::try_into_bounded(Some(old_asset_name)).unwrap(); - assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()).unwrap(), asset_id); - assert!(Registry::asset_ids(old_bounded_name.unwrap()).is_none()); + assert_eq!(Registry::asset_ids(name.clone()).unwrap(), asset_id); + assert!( + Registry::asset_ids::>(old_asset_name.try_into().unwrap()) + .is_none() + ); assert_last_event!(Event::::Updated { asset_id, - asset_name: bounded_name, + asset_name: Some(name), asset_type: AssetType::External, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), decimals: Some(decimals), - symbol: bounded_symbol, + symbol: Some(symbol), is_sufficient, } .into()); @@ -87,7 +112,7 @@ fn update_should_work_when_asset_exists() { #[test] fn update_should_update_provided_params_when_values_was_previously_set() { - let old_asset_name = b"Tkn2".to_vec(); + let old_asset_name: BoundedVec = b"Tkn2".to_vec().try_into().unwrap(); ExtBuilder::default().with_assets(vec![]).build().execute_with(|| { //Arrange let asset_id = 1; @@ -97,20 +122,20 @@ fn update_should_update_provided_params_when_values_was_previously_set() { assert_ok!(Registry::register( RuntimeOrigin::root(), Some(asset_id), - Some(b"Test asset".to_vec()), + Some(b"Test asset".to_vec().try_into().unwrap()), AssetType::Token, Some(10_000), - Some(b"TKN".to_vec()), + Some(b"TKN".to_vec().try_into().unwrap()), Some(12), Some(asset_location.clone()), Some(1_000), false )); - let name = b"New name".to_vec(); + let name: BoundedVec = b"New name".to_vec().try_into().unwrap(); let ed = 20_000 * UNIT; let xcm_rate_limit = 463; - let symbol = b"nTkn".to_vec(); + let symbol: BoundedVec = b"nTkn".to_vec().try_into().unwrap(); let decimals = 23; let is_sufficient = true; @@ -129,16 +154,14 @@ fn update_should_update_provided_params_when_values_was_previously_set() { )); //Assert - let bounded_name = Pallet::::try_into_bounded(Some(name)).unwrap(); - let bounded_symbol = Pallet::::try_into_bounded(Some(symbol)).unwrap(); assert_eq!( Registry::assets(asset_id), Some(AssetDetails { - name: bounded_name.clone(), + name: Some(name.clone()), asset_type: AssetType::External, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), - symbol: bounded_symbol.clone(), + symbol: Some(symbol.clone()), decimals: Some(decimals), is_sufficient: true }) @@ -148,18 +171,17 @@ fn update_should_update_provided_params_when_values_was_previously_set() { assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); assert_eq!(Registry::locations(asset_id), Some(asset_location)); - let old_bounded_name = Pallet::::try_into_bounded(Some(old_asset_name)).unwrap(); - assert_eq!(Registry::asset_ids(bounded_name.clone().unwrap()).unwrap(), asset_id); - assert!(Registry::asset_ids(old_bounded_name.unwrap()).is_none()); + assert_eq!(Registry::asset_ids(name.clone()).unwrap(), asset_id); + assert!(Registry::asset_ids(old_asset_name).is_none()); assert_last_event!(Event::::Updated { asset_id, - asset_name: bounded_name, + asset_name: Some(name), asset_type: AssetType::External, existential_deposit: ed, xcm_rate_limit: Some(xcm_rate_limit), decimals: Some(decimals), - symbol: bounded_symbol, + symbol: Some(symbol), is_sufficient, } .into()); @@ -170,9 +192,33 @@ fn update_should_update_provided_params_when_values_was_previously_set() { fn update_should_not_change_values_when_param_is_none() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -202,8 +248,8 @@ fn update_should_not_change_values_when_param_is_none() { //Assert assert_eq!(Registry::assets(asset_id).unwrap(), details_0); - let old_bounded_name = Pallet::::try_into_bounded(Some(b"Tkn2".to_vec())).unwrap(); - assert_eq!(Registry::asset_ids(old_bounded_name.unwrap()).unwrap(), asset_id); + let old_bounded_name: BoundedVec = b"Tkn2".to_vec().try_into().unwrap(); + assert_eq!(Registry::asset_ids(old_bounded_name).unwrap(), asset_id); //NOTE: location shouldn't change assert_eq!(Registry::location_assets(asset_location.clone()), Some(asset_id)); @@ -227,9 +273,33 @@ fn update_should_not_change_values_when_param_is_none() { fn update_origin_should_set_decimals_if_its_none() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -290,9 +360,33 @@ fn update_origin_should_set_decimals_if_its_none() { fn update_origin_should_not_chane_decimals_if_its_some() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, Some(3), None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + Some(3), + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -328,9 +422,33 @@ fn update_origin_should_not_chane_decimals_if_its_some() { fn create_origin_should_always_set_decimals() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, Some(3), None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + Some(3), + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -401,20 +519,36 @@ fn create_origin_should_always_set_decimals() { #[test] fn update_should_fail_when_name_is_already_used() { - let old_asset_name = b"Tkn2".to_vec(); + let old_asset_name: BoundedVec = b"Tkn2".to_vec().try_into().unwrap(); ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), (Some(2), Some(old_asset_name), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { let asset_id = 2; - let name = b"Tkn3".to_vec(); + let name: BoundedVec = b"Tkn3".to_vec().try_into().unwrap(); let ed = 10_000 * UNIT; let xcm_rate_limit = 463; - let symbol = b"nTkn2".to_vec(); + let symbol: BoundedVec = b"nTkn2".to_vec().try_into().unwrap(); let decimals = 23; let is_sufficient = false; @@ -447,9 +581,33 @@ fn update_should_not_update_location_when_origin_is_not_registry_origin() { let old_asset_name = b"Tkn2".to_vec(); ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(old_asset_name), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(old_asset_name.try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -505,9 +663,33 @@ fn update_should_update_location_when_origin_is_registry_origin() { let old_asset_name = b"Tkn2".to_vec(); ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(old_asset_name), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(old_asset_name.try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { @@ -581,17 +763,41 @@ fn update_should_not_work_when_name_is_same_as_old() { let old_asset_name = b"Tkn2".to_vec(); ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(old_asset_name.clone()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(old_asset_name.clone().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { let asset_id = 2; - let name = old_asset_name.clone(); + let name: BoundedVec = old_asset_name.clone().try_into().unwrap(); let ed = 10_000 * UNIT; let xcm_rate_limit = 463; - let symbol = b"nTkn2".to_vec(); + let symbol: BoundedVec = b"nTkn2".to_vec().try_into().unwrap(); let decimals = 23; let is_sufficient = false; @@ -619,87 +825,37 @@ fn update_should_not_work_when_name_is_same_as_old() { }); } -#[test] -fn update_should_fail_when_name_is_too_long() { - ExtBuilder::default() - .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), - ]) - .build() - .execute_with(|| { - let asset_id = 2; - let name = vec![97u8; ::StringLimit::get() as usize + 1]; - let ed = 10_000 * UNIT; - let xcm_rate_limit = 463; - let symbol = b"nTkn2".to_vec(); - let decimals = 23; - let is_sufficient = false; - - //Act - assert_noop!( - Registry::update( - RuntimeOrigin::root(), - asset_id, - Some(name), - Some(AssetType::External), - Some(ed), - Some(xcm_rate_limit), - Some(is_sufficient), - Some(symbol), - Some(decimals), - None - ), - Error::::TooLong - ); - }); -} - -#[test] -fn update_should_fail_when_symbol_is_too_long() { - ExtBuilder::default() - .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), - ]) - .build() - .execute_with(|| { - let asset_id = 2; - let name = b"New Token Name".to_vec(); - let ed = 10_000 * UNIT; - let xcm_rate_limit = 463; - let symbol = vec![97u8; ::StringLimit::get() as usize + 1]; - let decimals = 23; - let is_sufficient = false; - - //Act - assert_noop!( - Registry::update( - RuntimeOrigin::root(), - asset_id, - Some(name), - Some(AssetType::External), - Some(ed), - Some(xcm_rate_limit), - Some(is_sufficient), - Some(symbol), - Some(decimals), - None - ), - Error::::TooLong - ); - }); -} - #[test] fn change_sufficiency_should_fail_when_asset_is_sufficient() { ExtBuilder::default() .with_assets(vec![ - (Some(1), Some(b"Tkn1".to_vec()), UNIT, None, None, None, true), - (Some(2), Some(b"Tkn2".to_vec()), UNIT, None, None, None, true), - (Some(3), Some(b"Tkn3".to_vec()), UNIT, None, None, None, true), + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), ]) .build() .execute_with(|| { diff --git a/pallets/asset-registry/src/types.rs b/pallets/asset-registry/src/types.rs index 434567a2d..7c819b8a9 100644 --- a/pallets/asset-registry/src/types.rs +++ b/pallets/asset-registry/src/types.rs @@ -24,6 +24,9 @@ use hydradx_traits::AssetKind; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; +pub type Name = BoundedVec; +pub type Symbol = BoundedVec; + #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub enum AssetType { @@ -63,7 +66,7 @@ impl From for AssetKind { #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct AssetDetails> { /// The name of this asset. Limited in length by `StringLimit`. - pub name: Option>, + pub name: Option>, /// Asset type pub asset_type: AssetType, @@ -72,7 +75,7 @@ pub struct AssetDetails> { pub existential_deposit: Balance, /// The ticker symbol for this asset. Limited in length by `StringLimit`. - pub symbol: Option>, + pub symbol: Option>, /// The number of decimals this asset uses to represent one unit. pub decimals: Option, diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 5b568eed0..1cbc84738 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -51,13 +51,15 @@ pub trait Inspect { #[allow(clippy::too_many_arguments)] pub trait Create: Inspect { type Error; + type Name: Parameter; + type Symbol: Parameter; fn register_asset( asset_id: Option, - name: Option<&[u8]>, + name: Option, kind: AssetKind, existential_deposit: Option, - symbol: Option<&[u8]>, + symbol: Option, decimals: Option, location: Option, xcm_rate_limit: Option, @@ -66,10 +68,10 @@ pub trait Create: Inspect { fn register_insufficient_asset( asset_id: Option, - name: Option<&[u8]>, + name: Option, kind: AssetKind, existential_deposit: Option, - symbol: Option<&[u8]>, + symbol: Option, decimals: Option, location: Option, xcm_rate_limit: Option, @@ -89,10 +91,10 @@ pub trait Create: Inspect { fn register_sufficient_asset( asset_id: Option, - name: Option<&[u8]>, + name: Option, kind: AssetKind, existential_deposit: Balance, - symbol: Option<&[u8]>, + symbol: Option, decimals: Option, location: Option, xcm_rate_limit: Option, @@ -111,10 +113,10 @@ pub trait Create: Inspect { } fn get_or_register_asset( - name: &[u8], + name: Self::Name, kind: AssetKind, existential_deposit: Option, - symbol: Option<&[u8]>, + symbol: Option, decimals: Option, location: Option, xcm_rate_limit: Option, @@ -122,10 +124,10 @@ pub trait Create: Inspect { ) -> Result; fn get_or_register_sufficient_asset( - name: &[u8], + name: Self::Name, kind: AssetKind, existential_deposit: Balance, - symbol: Option<&[u8]>, + symbol: Option, decimals: Option, location: Option, xcm_rate_limit: Option, @@ -143,10 +145,10 @@ pub trait Create: Inspect { } fn get_or_register_insufficient_asset( - name: &[u8], + name: Self::Name, kind: AssetKind, existential_deposit: Option, - symbol: Option<&[u8]>, + symbol: Option, decimals: Option, location: Option, xcm_rate_limit: Option, From f3d7932fe609016d1f29e94e977de6bb5da90958 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 26 Jan 2024 14:56:47 +0100 Subject: [PATCH 76/93] AssetRegistry: disallow whitespace chars in symbol --- pallets/asset-registry/src/lib.rs | 35 +++---- pallets/asset-registry/src/tests/register.rs | 87 ++++++++++++++++ pallets/asset-registry/src/tests/update.rs | 100 +++++++++++++++++++ 3 files changed, 203 insertions(+), 19 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 3b78999a0..c19c84548 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -135,8 +135,8 @@ pub mod pallet { /// Invalid asset name or symbol. AssetNotFound, - /// Invalid asset name or symbol. - TooLong, + /// Asset's symbol can't contain whitespace characters. + InvalidSymbol, /// Asset ID is not registered in the asset-registry. AssetNotRegistered, @@ -170,23 +170,6 @@ pub mod pallet { /// Asset is not in assets blacklist. AssetNotBlacklisted, - - /// Action cannot be completed because unexpected error has occurred. This should be reported - /// to protocol maintainers. - InconsistentState(InconsistentStateError), - } - - // NOTE: these errors should never happen. - #[derive(Encode, Decode, Eq, PartialEq, TypeInfo, frame_support::PalletError, RuntimeDebug)] - pub enum InconsistentStateError { - /// Name or symbol conversion to bounded string failed. - BoundedConversionFailed, - } - - impl From for Error { - fn from(e: InconsistentStateError) -> Error { - Error::::InconsistentState(e) - } } #[pallet::type_value] @@ -383,6 +366,8 @@ pub mod pallet { ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; + Self::validate_symbol(&symbol)?; + let details = AssetDetails::new( name, asset_type, @@ -426,6 +411,8 @@ pub mod pallet { T::UpdateOrigin::ensure_origin(origin)?; } + Self::validate_symbol(&symbol)?; + Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { let detail = maybe_detail.as_mut().ok_or(Error::::AssetNotFound)?; @@ -559,6 +546,16 @@ pub mod pallet { } impl Pallet { + fn validate_symbol(symbol: &Option>) -> Result<(), DispatchError> { + if let Some(s) = symbol.clone() { + ensure!( + s.into_inner().iter().all(|c| !char::is_whitespace(*c as char)), + Error::::InvalidSymbol + ); + } + Ok(()) + } + pub fn next_asset_id() -> Option { NextAssetId::::get().checked_add(&T::SequentialIdStartAt::get()) } diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index de5203f61..b7d6c0c43 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -621,3 +621,90 @@ fn register_external_asset_should_not_work_when_user_cant_pay_storage_fees() { ); }); } + +#[test] +fn register_should_not_work_when_symbol_is_not_valid() { + ExtBuilder::default().build().execute_with(|| { + let asset_id = 1; + let name: BoundedVec = b"Test asset".to_vec().try_into().unwrap(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + let symbol: BoundedVec = b"TKN ".to_vec().try_into().unwrap(); + //Act + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + Error::::InvalidSymbol + ); + + let symbol: BoundedVec = b" TKN".to_vec().try_into().unwrap(); + //Act + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + Error::::InvalidSymbol + ); + + let symbol: BoundedVec = b"T KN".to_vec().try_into().unwrap(); + //Act + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + Error::::InvalidSymbol + ); + + let symbol: BoundedVec = b"T\tKN".to_vec().try_into().unwrap(); + //Act + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name.clone()), + AssetType::Token, + Some(ed), + Some(symbol.clone()), + Some(decimals), + Some(asset_location.clone()), + Some(xcm_rate_limit), + is_sufficient + ), + Error::::InvalidSymbol + ); + }); +} diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index 7dc49461c..7960f29c6 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -879,3 +879,103 @@ fn change_sufficiency_should_fail_when_asset_is_sufficient() { ); }); } + +#[test] +fn update_should_not_work_when_symbol_is_not_valid() { + ExtBuilder::default() + .with_assets(vec![( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + )]) + .build() + .execute_with(|| { + let asset_id = 1; + let name: BoundedVec = b"New Tkn 2".to_vec().try_into().unwrap(); + let ed = 10_000 * UNIT; + let xcm_rate_limit = 463; + let decimals = 23; + let is_sufficient = true; + + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); + + let symbol: BoundedVec = b"nTkn2 ".to_vec().try_into().unwrap(); + //Act + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + None + ), + Error::::InvalidSymbol + ); + + let symbol: BoundedVec = b"nTk n2".to_vec().try_into().unwrap(); + //Act + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + None + ), + Error::::InvalidSymbol + ); + + let symbol: BoundedVec = b" nTkn2".to_vec().try_into().unwrap(); + //Act + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + None + ), + Error::::InvalidSymbol + ); + + let symbol: BoundedVec = b"Tk\n2".to_vec().try_into().unwrap(); + //Act + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + None + ), + Error::::InvalidSymbol + ); + }); +} From 378f1575ae03ab7df09f37768c370ea0a408d539 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 26 Jan 2024 15:54:58 +0100 Subject: [PATCH 77/93] assetRegistry: renamed blacklist to banned --- pallets/asset-registry/src/benchmarking.rs | 4 +- pallets/asset-registry/src/lib.rs | 75 +++++----- .../asset-registry/src/tests/inspect_trait.rs | 8 +- pallets/asset-registry/src/tests/mock.rs | 3 + pallets/asset-registry/src/tests/register.rs | 128 +++++++++++++++++ pallets/asset-registry/src/tests/tests.rs | 44 +++--- pallets/asset-registry/src/tests/update.rs | 134 ++++++++++++++++++ pallets/asset-registry/src/weights.rs | 12 +- traits/src/registry.rs | 2 +- 9 files changed, 343 insertions(+), 67 deletions(-) diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index cf6b19c94..7d75b737e 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -104,7 +104,7 @@ benchmarks! { assert_eq!(Pallet::::location_assets(location), Some(expected_asset_id)); } - blacklist_add { + ban_asset { let asset_id = T::AssetId::from(3); let name = vec![97u8; T::StringLimit::get() as usize]; let ed = 1_000_000_u128; @@ -122,7 +122,7 @@ benchmarks! { assert_eq!(Pallet::::blacklists(asset_id), Some(())); } - blacklist_remove { + unban_asset { let asset_id = T::AssetId::from(3); let name = vec![97u8; T::StringLimit::get() as usize]; let ed = 1_000_000_u128; diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index c19c84548..28ded54f8 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -116,6 +116,10 @@ pub mod pallet { #[pallet::constant] type StringLimit: Get + Debug + PartialEq; + /// The min length of a name or symbol stored on-chain. + #[pallet::constant] + type MinStringLimit: Get + Debug + PartialEq; + /// Weight information for the extrinsics type WeightInfo: WeightInfo; } @@ -135,7 +139,10 @@ pub mod pallet { /// Invalid asset name or symbol. AssetNotFound, - /// Asset's symbol can't contain whitespace characters. + /// Length of name or symbol is less than min. length. + TooShort, + + /// Asset's symbol can't contain whitespace characters . InvalidSymbol, /// Asset ID is not registered in the asset-registry. @@ -165,11 +172,11 @@ pub mod pallet { /// Sufficient assets can't be changed to insufficient. ForbiddenSufficiencyChange, - /// Asset is already blacklisted. - AssetAlreadyBlacklisted, + /// Asset is already banned. + AssetAlreadyBanned, - /// Asset is not in assets blacklist. - AssetNotBlacklisted, + /// Asset is not banned. + AssetNotBanned, } #[pallet::type_value] @@ -201,9 +208,9 @@ pub mod pallet { StorageMap<_, Blake2_128Concat, T::AssetId, T::AssetNativeLocation, OptionQuery>; #[pallet::storage] - #[pallet::getter(fn blacklists)] - /// Assets that are blacklisted. - pub type BlacklistedAssets = StorageMap<_, Blake2_128Concat, T::AssetId, (), OptionQuery>; + #[pallet::getter(fn banned_assets)] + /// Non-native assets which transfer is banned. + pub type BannedAssets = StorageMap<_, Blake2_128Concat, T::AssetId, (), OptionQuery>; #[pallet::storage] #[pallet::getter(fn location_assets)] @@ -328,11 +335,11 @@ pub mod pallet { location: T::AssetNativeLocation, }, - /// Asset was added to assets blacklist. - BlacklistAdded { asset_id: T::AssetId }, + /// Asset was banned. + AssetBanned { asset_id: T::AssetId }, - /// Asset was removed from assets blacklist. - BlacklistRemoved { asset_id: T::AssetId }, + /// Asset's ban was removed. + AssetUnbanned { asset_id: T::AssetId }, } #[pallet::call] @@ -366,8 +373,6 @@ pub mod pallet { ) -> DispatchResult { T::RegistryOrigin::ensure_origin(origin)?; - Self::validate_symbol(&symbol)?; - let details = AssetDetails::new( name, asset_type, @@ -411,6 +416,10 @@ pub mod pallet { T::UpdateOrigin::ensure_origin(origin)?; } + if let Some(n) = name.as_ref() { + ensure!(n.len() >= T::MinStringLimit::get() as usize, Error::::TooShort); + } + Self::validate_symbol(&symbol)?; Assets::::try_mutate(asset_id, |maybe_detail| -> DispatchResult { @@ -510,36 +519,33 @@ pub mod pallet { } #[pallet::call_index(5)] - #[pallet::weight(::WeightInfo::blacklist_add())] - pub fn blacklist_add(origin: OriginFor, asset_id: T::AssetId) -> DispatchResult { + #[pallet::weight(::WeightInfo::ban_asset())] + pub fn ban_asset(origin: OriginFor, asset_id: T::AssetId) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; ensure!(Assets::::contains_key(asset_id), Error::::AssetNotFound); ensure!( - !BlacklistedAssets::::contains_key(asset_id), - Error::::AssetAlreadyBlacklisted + !BannedAssets::::contains_key(asset_id), + Error::::AssetAlreadyBanned ); - BlacklistedAssets::::insert(asset_id, ()); + BannedAssets::::insert(asset_id, ()); - Self::deposit_event(Event::BlacklistAdded { asset_id }); + Self::deposit_event(Event::AssetBanned { asset_id }); Ok(()) } #[pallet::call_index(6)] - #[pallet::weight(::WeightInfo::blacklist_remove())] - pub fn blacklist_remove(origin: OriginFor, asset_id: T::AssetId) -> DispatchResult { + #[pallet::weight(::WeightInfo::unban_asset())] + pub fn unban_asset(origin: OriginFor, asset_id: T::AssetId) -> DispatchResult { T::UpdateOrigin::ensure_origin(origin)?; - ensure!( - BlacklistedAssets::::contains_key(asset_id), - Error::::AssetNotBlacklisted - ); + ensure!(BannedAssets::::contains_key(asset_id), Error::::AssetNotBanned); - BlacklistedAssets::::remove(asset_id); + BannedAssets::::remove(asset_id); - Self::deposit_event(Event::BlacklistRemoved { asset_id }); + Self::deposit_event(Event::AssetUnbanned { asset_id }); Ok(()) } } @@ -548,6 +554,8 @@ pub mod pallet { impl Pallet { fn validate_symbol(symbol: &Option>) -> Result<(), DispatchError> { if let Some(s) = symbol.clone() { + ensure!(s.len() >= T::MinStringLimit::get() as usize, Error::::TooShort); + ensure!( s.into_inner().iter().all(|c| !char::is_whitespace(*c as char)), Error::::InvalidSymbol @@ -580,6 +588,8 @@ impl Pallet { details: &AssetDetails, location: Option, ) -> Result { + Self::validate_symbol(&details.symbol)?; + let asset_id = if let Some(id) = selected_asset_id { ensure!(id < T::SequentialIdStartAt::get(), Error::::NotInReservedRange); @@ -601,6 +611,7 @@ impl Pallet { Assets::::insert(asset_id, details); if let Some(name) = details.name.as_ref() { + ensure!(name.len() >= T::MinStringLimit::get() as usize, Error::::TooShort); ensure!(!AssetIds::::contains_key(name), Error::::AssetAlreadyRegistered); AssetIds::::insert(name, asset_id); } @@ -698,7 +709,7 @@ impl Inspect for Pallet { } fn exists(id: Self::AssetId) -> bool { - Assets::::try_get(id).is_ok() + Assets::::contains_key(id) } fn decimals(id: Self::AssetId) -> Option { @@ -706,11 +717,11 @@ impl Inspect for Pallet { } fn asset_type(id: Self::AssetId) -> Option { - Self::assets(id).map(|a| a.asset_type.into()) + Self::assets(id).and_then(|a| Some(a.asset_type.into())) } - fn is_blacklisted(id: Self::AssetId) -> bool { - BlacklistedAssets::::contains_key(id) + fn is_banned(id: Self::AssetId) -> bool { + BannedAssets::::contains_key(id) } fn asset_name(id: Self::AssetId) -> Option> { diff --git a/pallets/asset-registry/src/tests/inspect_trait.rs b/pallets/asset-registry/src/tests/inspect_trait.rs index 3c407e03a..ee57dde96 100644 --- a/pallets/asset-registry/src/tests/inspect_trait.rs +++ b/pallets/asset-registry/src/tests/inspect_trait.rs @@ -157,7 +157,7 @@ fn asset_type_should_work() { } #[test] -fn is_blacklisted_should_work() { +fn is_banned_should_work() { ExtBuilder::default() .with_assets(vec![ ( @@ -183,12 +183,12 @@ fn is_blacklisted_should_work() { .execute_with(|| { //Arrange //NOTE: update origin is set to ensure_signed in tests - assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 1)); + assert_ok!(Registry::ban_asset(RuntimeOrigin::signed(ALICE), 1)); //Act & assert - assert_eq!(::is_blacklisted(1), true); + assert_eq!(::is_banned(1), true); - assert_eq!(::is_blacklisted(2), false); + assert_eq!(::is_banned(2), false); }); } diff --git a/pallets/asset-registry/src/tests/mock.rs b/pallets/asset-registry/src/tests/mock.rs index 261d27a02..e2df307bb 100644 --- a/pallets/asset-registry/src/tests/mock.rs +++ b/pallets/asset-registry/src/tests/mock.rs @@ -58,6 +58,8 @@ parameter_types! { pub const NativeAssetId: AssetId = 0; #[derive(PartialEq, Debug)] pub const RegistryStringLimit: u32 = 10; + #[derive(PartialEq, Debug)] + pub const RegistryMinStringLimit: u32 = 2; pub const SequentialIdStart: u32 = 1_000_000; } @@ -106,6 +108,7 @@ impl pallet_asset_registry::Config for Test { type AssetId = u32; type AssetNativeLocation = AssetLocation; type StringLimit = RegistryStringLimit; + type MinStringLimit = RegistryMinStringLimit; type SequentialIdStartAt = SequentialIdStart; type StorageFeesAssetId = NativeAssetId; type StorageFees = StoreFees; diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index b7d6c0c43..9e387392c 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -708,3 +708,131 @@ fn register_should_not_work_when_symbol_is_not_valid() { ); }); } + +#[test] +fn register_should_not_work_when_name_is_too_short() { + ExtBuilder::default() + .with_assets(vec![ + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ]) + .build() + .execute_with(|| { + let asset_id = 4; + let name: BoundedVec = b"T".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"TKN".to_vec().try_into().unwrap(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name), + AssetType::Token, + Some(ed), + Some(symbol), + Some(decimals), + Some(asset_location), + Some(xcm_rate_limit), + is_sufficient + ), + Error::::TooShort + ); + }); +} + +#[test] +fn register_should_not_work_when_symbol_is_too_short() { + ExtBuilder::default() + .with_assets(vec![ + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"Tkn2".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ]) + .build() + .execute_with(|| { + let asset_id = 4; + let name: BoundedVec = b"TKN".to_vec().try_into().unwrap(); + let symbol: BoundedVec = b"T".to_vec().try_into().unwrap(); + let decimals = 12; + let xcm_rate_limit = 1_000; + let ed = 10_000; + let is_sufficient = true; + + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + //Act + assert_noop!( + Registry::register( + RuntimeOrigin::root(), + Some(asset_id), + Some(name), + AssetType::Token, + Some(ed), + Some(symbol), + Some(decimals), + Some(asset_location), + Some(xcm_rate_limit), + is_sufficient + ), + Error::::TooShort + ); + }); +} diff --git a/pallets/asset-registry/src/tests/tests.rs b/pallets/asset-registry/src/tests/tests.rs index 5e7803d0b..b5c14f673 100644 --- a/pallets/asset-registry/src/tests/tests.rs +++ b/pallets/asset-registry/src/tests/tests.rs @@ -4,7 +4,7 @@ use mock::Registry; use pretty_assertions::assert_eq; #[test] -fn blacklist_add_should_work_when_asset_is_not_blacklisted() { +fn ban_asset_should_work_when_asset_is_not_banned() { ExtBuilder::default() .with_assets(vec![ ( @@ -39,17 +39,17 @@ fn blacklist_add_should_work_when_asset_is_not_blacklisted() { .execute_with(|| { //Act //NOTE: update origin is set to ensure_signed in tests - assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 1)); + assert_ok!(Registry::ban_asset(RuntimeOrigin::signed(ALICE), 1)); //Assert - assert_last_event!(Event::::BlacklistAdded { asset_id: 1 }.into()); + assert_last_event!(Event::::AssetBanned { asset_id: 1 }.into()); - assert_eq!(Registry::blacklists(1), Some(())) + assert_eq!(Registry::banned_assets(1), Some(())) }); } #[test] -fn blacklist_add_should_fial_when_asset_is_already_blacklisted() { +fn ban_asset_should_fial_when_asset_is_already_banned() { let asset_id: u32 = 1; ExtBuilder::default() .with_assets(vec![ @@ -84,20 +84,20 @@ fn blacklist_add_should_fial_when_asset_is_already_blacklisted() { .build() .execute_with(|| { //Arrange - assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 2)); - assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), asset_id)); + assert_ok!(Registry::ban_asset(RuntimeOrigin::signed(ALICE), 2)); + assert_ok!(Registry::ban_asset(RuntimeOrigin::signed(ALICE), asset_id)); //Act //NOTE: update origin is set to ensure_signed in tests assert_noop!( - Registry::blacklist_add(RuntimeOrigin::signed(ALICE), asset_id), - Error::::AssetAlreadyBlacklisted + Registry::ban_asset(RuntimeOrigin::signed(ALICE), asset_id), + Error::::AssetAlreadyBanned ); }); } #[test] -fn blacklist_add_should_fail_when_asset_is_not_registered() { +fn ban_asset_should_fail_when_asset_is_not_registered() { ExtBuilder::default() .with_assets(vec![ ( @@ -135,14 +135,14 @@ fn blacklist_add_should_fail_when_asset_is_not_registered() { //Act //NOTE: update origin is set to ensure_signed in tests assert_noop!( - Registry::blacklist_add(RuntimeOrigin::signed(ALICE), not_existing_asset), + Registry::ban_asset(RuntimeOrigin::signed(ALICE), not_existing_asset), Error::::AssetNotFound ); }); } #[test] -fn blacklist_remove_should_work_when_asset_is_blacklisted() { +fn unban_asset_should_work_when_asset_is_banned() { let asset_id: u32 = 1; ExtBuilder::default() .with_assets(vec![ @@ -177,22 +177,22 @@ fn blacklist_remove_should_work_when_asset_is_blacklisted() { .build() .execute_with(|| { //Arrange - assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 3)); - assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), asset_id)); + assert_ok!(Registry::ban_asset(RuntimeOrigin::signed(ALICE), 3)); + assert_ok!(Registry::ban_asset(RuntimeOrigin::signed(ALICE), asset_id)); //Act //NOTE: update origin is set to ensure_signed in tests - assert_ok!(Registry::blacklist_remove(RuntimeOrigin::signed(ALICE), asset_id),); + assert_ok!(Registry::unban_asset(RuntimeOrigin::signed(ALICE), asset_id),); //Assert - assert_last_event!(Event::::BlacklistRemoved { asset_id }.into()); + assert_last_event!(Event::::AssetUnbanned { asset_id }.into()); - assert_eq!(Registry::blacklists(asset_id), None) + assert_eq!(Registry::banned_assets(asset_id), None) }); } #[test] -fn blacklist_remove_should_fail_when_asset_is_not_blacklisted() { +fn unban_asset_should_fail_when_asset_is_not_banned() { let asset_id: u32 = 1; ExtBuilder::default() .with_assets(vec![ @@ -227,14 +227,14 @@ fn blacklist_remove_should_fail_when_asset_is_not_blacklisted() { .build() .execute_with(|| { //Arrange - assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 3)); - assert_ok!(Registry::blacklist_add(RuntimeOrigin::signed(ALICE), 2)); + assert_ok!(Registry::ban_asset(RuntimeOrigin::signed(ALICE), 3)); + assert_ok!(Registry::ban_asset(RuntimeOrigin::signed(ALICE), 2)); //Act //NOTE: update origin is set to ensure_signed in tests assert_noop!( - Registry::blacklist_remove(RuntimeOrigin::signed(ALICE), asset_id), - Error::::AssetNotBlacklisted + Registry::unban_asset(RuntimeOrigin::signed(ALICE), asset_id), + Error::::AssetNotBanned ); }); } diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index 7960f29c6..6e96a0a0d 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -979,3 +979,137 @@ fn update_should_not_work_when_symbol_is_not_valid() { ); }); } + +#[test] +fn update_should_work_when_name_is_too_short() { + let old_asset_name = b"Tkn2".to_vec(); + ExtBuilder::default() + .with_assets(vec![ + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(old_asset_name.clone().try_into().unwrap()), + UNIT, + None, + None, + None, + false, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + let name: BoundedVec = b"N".to_vec().try_into().unwrap(); + let ed = 10_000 * UNIT; + let xcm_rate_limit = 463; + let symbol: BoundedVec = b"nTkn2".to_vec().try_into().unwrap(); + let decimals = 23; + let is_sufficient = true; + + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); + + //Act + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + None + ), + Error::::TooShort + ); + }); +} + +#[test] +fn update_should_work_when_symbol_is_too_short() { + let old_asset_name = b"Tkn2".to_vec(); + ExtBuilder::default() + .with_assets(vec![ + ( + Some(1), + Some(b"Tkn1".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ( + Some(2), + Some(old_asset_name.clone().try_into().unwrap()), + UNIT, + None, + None, + None, + false, + ), + ( + Some(3), + Some(b"Tkn3".to_vec().try_into().unwrap()), + UNIT, + None, + None, + None, + true, + ), + ]) + .build() + .execute_with(|| { + let asset_id = 2; + let name: BoundedVec = b"Name new".to_vec().try_into().unwrap(); + let ed = 10_000 * UNIT; + let xcm_rate_limit = 463; + let symbol: BoundedVec = b"T".to_vec().try_into().unwrap(); + let decimals = 23; + let is_sufficient = true; + + //Arrange + let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); + + //Act + assert_noop!( + Registry::update( + RuntimeOrigin::root(), + asset_id, + Some(name.clone()), + Some(AssetType::External), + Some(ed), + Some(xcm_rate_limit), + Some(is_sufficient), + Some(symbol.clone()), + Some(decimals), + None + ), + Error::::TooShort + ); + }); +} diff --git a/pallets/asset-registry/src/weights.rs b/pallets/asset-registry/src/weights.rs index 80d04884c..b40d1c585 100644 --- a/pallets/asset-registry/src/weights.rs +++ b/pallets/asset-registry/src/weights.rs @@ -50,8 +50,8 @@ pub trait WeightInfo { fn register() -> Weight; fn update() -> Weight; fn register_external() -> Weight; - fn blacklist_add() -> Weight; - fn blacklist_remove() -> Weight; + fn ban_asset() -> Weight; + fn unban_asset() -> Weight; } /// Weights for pallet_asset_registry using the hydraDX node and recommended hardware. pub struct HydraWeight(PhantomData); @@ -106,7 +106,7 @@ impl WeightInfo for HydraWeight { // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) - fn blacklist_add() -> Weight { + fn ban_asset() -> Weight { // Minimum execution time: 22_677 nanoseconds. Weight::from_parts(22_950_000, 0) .saturating_add(T::DbWeight::get().reads(2 as u64)) @@ -114,7 +114,7 @@ impl WeightInfo for HydraWeight { } // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) - fn blacklist_remove() -> Weight { + fn unban_asset() -> Weight { // Minimum execution time: 17_460 nanoseconds. Weight::from_parts(17_958_000, 0) .saturating_add(T::DbWeight::get().reads(1 as u64)) @@ -172,7 +172,7 @@ impl WeightInfo for () { // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) - fn blacklist_add() -> Weight { + fn ban_asset() -> Weight { // Minimum execution time: 22_677 nanoseconds. Weight::from_parts(22_950_000, 0) .saturating_add(RocksDbWeight::get().reads(2 as u64)) @@ -180,7 +180,7 @@ impl WeightInfo for () { } // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) - fn blacklist_remove() -> Weight { + fn unban_asset() -> Weight { // Minimum execution time: 17_460 nanoseconds. Weight::from_parts(17_958_000, 0) .saturating_add(RocksDbWeight::get().reads(1 as u64)) diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 1cbc84738..393b5cc89 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -41,7 +41,7 @@ pub trait Inspect { fn asset_type(id: Self::AssetId) -> Option; - fn is_blacklisted(id: Self::AssetId) -> bool; + fn is_banned(id: Self::AssetId) -> bool; fn asset_name(id: Self::AssetId) -> Option>; From 51b0f801680e9771a648c49cf2a041a7a1ffc7d9 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 26 Jan 2024 15:58:21 +0100 Subject: [PATCH 78/93] asset-registry: removed duplicate fuction --- pallets/asset-registry/src/lib.rs | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 28ded54f8..42862ab2a 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -634,34 +634,6 @@ impl Pallet { Ok(asset_id) } - /// Create asset for given name or return existing AssetId if such asset already exists. - pub fn get_or_create_asset( - name: Name, - asset_type: AssetType, - existential_deposit: Balance, - asset_id: Option, - is_sufficient: bool, - ) -> Result { - //TODO: remove this fn - if let Some(asset_id) = AssetIds::::get(&name) { - Ok(asset_id) - } else { - Self::do_register_asset( - asset_id, - &AssetDetails::new( - Some(name), - asset_type, - existential_deposit, - None, - None, - None, - is_sufficient, - ), - None, - ) - } - } - /// Return location for given asset. pub fn asset_to_location(asset_id: T::AssetId) -> Option { Self::locations(asset_id) From b0bc54a966140ea34538e3d83d0f290900938e26 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Fri, 26 Jan 2024 17:42:44 +0100 Subject: [PATCH 79/93] asset-registry: fixed asset-registry changes in xyk, bonds, runtime and integration-test --- Cargo.lock | 1 + integration-tests/Cargo.toml | 2 + integration-tests/src/bonds.rs | 4 +- integration-tests/src/dca.rs | 12 +-- integration-tests/src/exchange_asset.rs | 6 +- .../src/insufficient_assets_ed.rs | 12 +-- integration-tests/src/polkadot_test_net.rs | 94 ++++++++++++++++--- integration-tests/src/router.rs | 6 +- node/src/chain_spec/local.rs | 20 +++- node/src/chain_spec/mod.rs | 25 +++-- pallets/bonds/src/lib.rs | 5 +- pallets/xyk/src/lib.rs | 2 +- runtime/hydradx/src/assets.rs | 7 +- runtime/hydradx/src/weights/registry.rs | 4 +- traits/src/registry.rs | 4 +- 15 files changed, 156 insertions(+), 48 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b5ff30af8..06095b320 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11320,6 +11320,7 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", + "sp-state-machine 0.28.0 (git+https://github.com/paritytech/polkadot-sdk?rev=c8d2251cafadc108ba2f1f8a3208dc547ff38901)", "sp-std", "sp-transaction-pool", "sp-trie", diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index e149e86ac..5380fb31b 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -118,6 +118,7 @@ sp-io = { workspace = true } sp-consensus-babe = { workspace = true } sp-authority-discovery = { workspace = true } sc-consensus-grandpa = { workspace = true } +sp-state-machine = { workspace = true } polkadot-primitives = { workspace = true } polkadot-service = { workspace = true, features = ["full-node"] } @@ -193,6 +194,7 @@ std = [ "polkadot-runtime/std", "hydradx-runtime/std", "pallet-staking/std", + "sp-state-machine/std", ] # we don't include integration tests when benchmarking feature is enabled diff --git a/integration-tests/src/bonds.rs b/integration-tests/src/bonds.rs index ecec2fbcb..4542af70d 100644 --- a/integration-tests/src/bonds.rs +++ b/integration-tests/src/bonds.rs @@ -73,7 +73,7 @@ fn issue_bonds_should_work_when_issued_for_share_asset() { let name = b"SHARED".to_vec(); let share_asset_id = AssetRegistry::register_insufficient_asset( None, - Some(&name), + Some(name.try_into().unwrap()), AssetKind::XYK, Some(1_000), None, @@ -132,7 +132,7 @@ fn issue_bonds_should_not_work_when_issued_for_bond_asset() { let name = b"BOND".to_vec(); let underlying_asset_id = AssetRegistry::register_insufficient_asset( None, - Some(&name), + Some(name.try_into().unwrap()), AssetKind::Bond, Some(1_000), None, diff --git a/integration-tests/src/dca.rs b/integration-tests/src/dca.rs index 55db12f0b..61c3f514a 100644 --- a/integration-tests/src/dca.rs +++ b/integration-tests/src/dca.rs @@ -3316,10 +3316,10 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { let name: Vec = idx.to_ne_bytes().to_vec(); let asset_id = AssetRegistry::register_sufficient_asset( None, - Some(name.as_ref()), + Some(name.try_into().unwrap()), AssetKind::Token, 1u128, - Some(b"xDUM".as_ref()), + Some(b"xDUM".to_vec().try_into().unwrap()), Some(18u8), None, None, @@ -3336,7 +3336,7 @@ pub fn init_stableswap() -> Result<(AssetId, AssetId, AssetId), DispatchError> { } let pool_id = AssetRegistry::register_sufficient_asset( None, - Some(b"pool".as_ref()), + Some(b"pool".to_vec().try_into().unwrap()), AssetKind::Token, 1u128, None, @@ -3373,10 +3373,10 @@ pub fn init_stableswap_with_three_assets_having_different_decimals( let asset_id = AssetRegistry::register_sufficient_asset( None, - Some(name.as_ref()), + Some(name.try_into().unwrap()), AssetKind::Token, 1u128, - Some(b"xDUM".as_ref()), + Some(b"xDUM".to_vec().try_into().unwrap()), Some(decimals_for_each_asset[idx as usize]), None, None, @@ -3400,7 +3400,7 @@ pub fn init_stableswap_with_three_assets_having_different_decimals( } let pool_id = AssetRegistry::register_insufficient_asset( None, - Some(b"pool".as_ref()), + Some(b"pool".to_vec().try_into().unwrap()), AssetKind::Token, Some(1u128), None, diff --git a/integration-tests/src/exchange_asset.rs b/integration-tests/src/exchange_asset.rs index 6d64e53d3..96bb03cf4 100644 --- a/integration-tests/src/exchange_asset.rs +++ b/integration-tests/src/exchange_asset.rs @@ -277,7 +277,7 @@ fn register_glmr() { assert_ok!(hydradx_runtime::AssetRegistry::register( hydradx_runtime::RuntimeOrigin::root(), Some(GLMR), - Some(b"GLRM".to_vec()), + Some(b"GLRM".to_vec().try_into().unwrap()), pallet_asset_registry::AssetType::Token, Some(1_000_000), None, @@ -295,7 +295,7 @@ fn register_aca() { assert_ok!(hydradx_runtime::AssetRegistry::register( hydradx_runtime::RuntimeOrigin::root(), Some(ACA), - Some(b"ACAL".to_vec()), + Some(b"ACAL".to_vec().try_into().unwrap()), pallet_asset_registry::AssetType::Token, Some(1_000_000), None, @@ -313,7 +313,7 @@ fn register_ibtc() { assert_ok!(hydradx_runtime::AssetRegistry::register( hydradx_runtime::RuntimeOrigin::root(), Some(IBTC), - Some(b"iBTC".to_vec()), + Some(b"iBTC".to_vec().try_into().unwrap()), pallet_asset_registry::AssetType::Token, Some(1_000_000), None, diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index e684b8d5f..5396ba1ac 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -1339,7 +1339,7 @@ fn tx_should_fail_with_unsupported_currency_error_when_fee_asset_price_was_not_p } #[test] -fn blacklisted_asset_should_not_create_new_account() { +fn banned_asset_should_not_create_new_account() { TestNet::reset(); Hydra::execute_with(|| { let tech_comm = pallet_collective::RawOrigin::::Members(1, 1); @@ -1353,7 +1353,7 @@ fn blacklisted_asset_should_not_create_new_account() { 0, )); - assert_ok!(Registry::blacklist_add(tech_comm.into(), sht1)); + assert_ok!(Registry::ban_asset(tech_comm.into(), sht1)); assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); assert_eq!(treasury_sufficiency_lock(), 0); @@ -1361,13 +1361,13 @@ fn blacklisted_asset_should_not_create_new_account() { //Act & assert assert_noop!( Tokens::transfer(hydra_origin::signed(BOB.into()), ALICE.into(), sht1, 1_000_000 * UNITS), - sp_runtime::DispatchError::Other("BlacklistedAssetTransfer") + sp_runtime::DispatchError::Other("BannedAssetTransfer") ); }); } #[test] -fn blacklisted_asset_should_not_be_transferable_to_existing_account() { +fn banned_asset_should_not_be_transferable_to_existing_account() { TestNet::reset(); Hydra::execute_with(|| { let tech_comm = pallet_collective::RawOrigin::::Members(1, 1); @@ -1389,12 +1389,12 @@ fn blacklisted_asset_should_not_be_transferable_to_existing_account() { 0, )); - assert_ok!(Registry::blacklist_add(tech_comm.into(), sht1)); + assert_ok!(Registry::ban_asset(tech_comm.into(), sht1)); //Act & assert assert_noop!( Tokens::transfer(hydra_origin::signed(BOB.into()), ALICE.into(), sht1, 1_000_000 * UNITS), - sp_runtime::DispatchError::Other("BlacklistedAssetTransfer") + sp_runtime::DispatchError::Other("BannedAssetTransfer") ); }); } diff --git a/integration-tests/src/polkadot_test_net.rs b/integration-tests/src/polkadot_test_net.rs index 2f7885bf1..fbd706ac6 100644 --- a/integration-tests/src/polkadot_test_net.rs +++ b/integration-tests/src/polkadot_test_net.rs @@ -404,20 +404,92 @@ pub mod hydra { }, asset_registry: hydradx_runtime::AssetRegistryConfig { registered_assets: vec![ - (Some(LRNA), Some(b"LRNA".to_vec()), 1_000u128, None, None, None, true), - (Some(DAI), Some(b"DAI".to_vec()), 1_000u128, None, None, None, true), - (Some(DOT), Some(b"DOT".to_vec()), 1_000u128, None, None, None, true), - (Some(ETH), Some(b"ETH".to_vec()), 1_000u128, None, None, None, true), - (Some(BTC), Some(b"BTC".to_vec()), 1_000u128, None, None, None, true), - (Some(ACA), Some(b"ACA".to_vec()), 1_000u128, None, None, None, true), - (Some(WETH), Some(b"WETH".to_vec()), 1_000u128, None, None, None, true), - (Some(PEPE), Some(b"PEPE".to_vec()), 1_000u128, None, None, None, true), + ( + Some(LRNA), + Some(b"LRNA".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(DAI), + Some(b"DAI".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(DOT), + Some(b"DOT".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(ETH), + Some(b"ETH".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(BTC), + Some(b"BTC".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(ACA), + Some(b"ACA".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(WETH), + Some(b"WETH".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(PEPE), + Some(b"PEPE".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), // workaround for next_asset_id() to return correct values - (None, Some(b"DUMMY".to_vec()), 1_000u128, None, None, None, false), + ( + None, + Some(b"DUMMY".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + false, + ), ], - native_asset_name: b"HDX".to_vec(), + native_asset_name: b"HDX".to_vec().try_into().unwrap(), native_existential_deposit: existential_deposit, - native_symbol: b"HDX".to_vec(), + native_symbol: b"HDX".to_vec().try_into().unwrap(), native_decimals: 12, }, parachain_info: hydradx_runtime::ParachainInfoConfig { diff --git a/integration-tests/src/router.rs b/integration-tests/src/router.rs index da8a06e04..f3887b259 100644 --- a/integration-tests/src/router.rs +++ b/integration-tests/src/router.rs @@ -3434,10 +3434,10 @@ pub fn init_stableswap_with_liquidity( let name: Vec = idx.to_ne_bytes().to_vec(); let asset_id = AssetRegistry::register_sufficient_asset( None, - Some(name.as_ref()), + Some(name.try_into().unwrap()), AssetKind::Token, 1u128, - Some(b"xDUM".as_ref()), + Some(b"xDUM".to_vec().try_into().unwrap()), Some(18u8), None, None, @@ -3462,7 +3462,7 @@ pub fn init_stableswap_with_liquidity( } let pool_id = AssetRegistry::register_sufficient_asset( None, - Some(b"pool".as_ref()), + Some(b"pool".to_vec().try_into().unwrap()), AssetKind::Token, 1u128, None, diff --git a/node/src/chain_spec/local.rs b/node/src/chain_spec/local.rs index 738e57e00..d5f4fdb89 100644 --- a/node/src/chain_spec/local.rs +++ b/node/src/chain_spec/local.rs @@ -81,8 +81,24 @@ pub fn parachain_config() -> Result { vec![], // registered assets vec![ - (Some(1), Some(b"KSM".to_vec()), 1_000u128, None, None, None, false), - (Some(2), Some(b"KUSD".to_vec()), 1_000u128, None, None, None, false), + ( + Some(1), + Some(b"KSM".to_vec().try_into().expect("Name is too long")), + 1_000u128, + None, + None, + None, + false, + ), + ( + Some(2), + Some(b"KUSD".to_vec().try_into().expect("Name is too long")), + 1_000u128, + None, + None, + None, + false, + ), ], // accepted assets vec![(1, Price::from_float(0.0000212)), (2, Price::from_float(0.000806))], diff --git a/node/src/chain_spec/mod.rs b/node/src/chain_spec/mod.rs index 373b2f1b8..a9e1ff8cb 100644 --- a/node/src/chain_spec/mod.rs +++ b/node/src/chain_spec/mod.rs @@ -30,8 +30,8 @@ use hex_literal::hex; use hydradx_runtime::{ pallet_claims::EthereumAddress, AccountId, AssetRegistryConfig, AuraId, Balance, BalancesConfig, ClaimsConfig, CollatorSelectionConfig, CouncilConfig, DusterConfig, ElectionsConfig, GenesisHistoryConfig, - MultiTransactionPaymentConfig, ParachainInfoConfig, RuntimeGenesisConfig, SessionConfig, Signature, SystemConfig, - TechnicalCommitteeConfig, TokensConfig, VestingConfig, WASM_BINARY, + MultiTransactionPaymentConfig, ParachainInfoConfig, RegistryStrLimit, RuntimeGenesisConfig, SessionConfig, + Signature, SystemConfig, TechnicalCommitteeConfig, TokensConfig, VestingConfig, WASM_BINARY, }; use primitives::{ constants::currency::{NATIVE_EXISTENTIAL_DEPOSIT, UNITS}, @@ -42,7 +42,10 @@ use sc_service::ChainType; use serde::{Deserialize, Serialize}; use serde_json::map::Map; use sp_core::{crypto::UncheckedInto, sr25519, Pair, Public}; -use sp_runtime::traits::{IdentifyAccount, Verify}; +use sp_runtime::{ + traits::{IdentifyAccount, Verify}, + BoundedVec, +}; const PARA_ID: u32 = 2034; const TOKEN_DECIMALS: u8 = 12; @@ -100,9 +103,9 @@ pub fn parachain_genesis( vesting_list: Vec<(AccountId, BlockNumber, BlockNumber, u32, Balance)>, registered_assets: Vec<( Option, - Option>, + Option>, Balance, - Option>, + Option>, Option, Option, bool, @@ -158,9 +161,17 @@ pub fn parachain_genesis( vesting: VestingConfig { vesting: vesting_list }, asset_registry: AssetRegistryConfig { registered_assets: registered_assets.clone(), - native_asset_name: TOKEN_SYMBOL.as_bytes().to_vec(), + native_asset_name: TOKEN_SYMBOL + .as_bytes() + .to_vec() + .try_into() + .expect("Native asset name is too long."), native_existential_deposit: NATIVE_EXISTENTIAL_DEPOSIT, - native_symbol: TOKEN_SYMBOL.as_bytes().to_vec(), + native_symbol: TOKEN_SYMBOL + .as_bytes() + .to_vec() + .try_into() + .expect("Native symbol is too long."), native_decimals: TOKEN_DECIMALS, }, multi_transaction_payment: MultiTransactionPaymentConfig { diff --git a/pallets/bonds/src/lib.rs b/pallets/bonds/src/lib.rs index d61cc1fac..6e443c04c 100644 --- a/pallets/bonds/src/lib.rs +++ b/pallets/bonds/src/lib.rs @@ -183,6 +183,8 @@ pub mod pallet { DisallowedAsset, /// Asset is not registered in `AssetRegistry` AssetNotFound, + /// Generated name is not valid. + InvalidBondName, } #[pallet::call] @@ -231,9 +233,10 @@ pub mod pallet { ensure!(maturity >= T::TimestampProvider::now(), Error::::InvalidMaturity); let ed = T::ExistentialDeposits::get(&asset_id); + let b_name = Self::bond_name(asset_id, maturity); let bond_id = T::AssetRegistry::register_insufficient_asset( None, - Some(&Self::bond_name(asset_id, maturity)), + Some(b_name.try_into().map_err(|_| Error::::InvalidBondName)?), AssetKind::Bond, Some(ed), None, diff --git a/pallets/xyk/src/lib.rs b/pallets/xyk/src/lib.rs index d04b555c4..5629fe097 100644 --- a/pallets/xyk/src/lib.rs +++ b/pallets/xyk/src/lib.rs @@ -349,7 +349,7 @@ pub mod pallet { let token_name = asset_pair.name(); let share_token = T::AssetRegistry::get_or_register_insufficient_asset( - &token_name, + token_name.try_into().map_err(|_| Error::::CannotCreatePool)?, AssetKind::XYK, None, None, diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index b4748491a..f890d8b5b 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -159,8 +159,8 @@ impl SufficiencyCheck { /// /// Emits `pallet_asset_registry::Event::ExistentialDepositPaid` when ED was paid. fn on_funds(asset: AssetId, paying_account: &AccountId, to: &AccountId) -> DispatchResult { - if AssetRegistry::is_blacklisted(asset) { - return Err(DispatchError::Other("BlacklistedAssetTransfer")); + if AssetRegistry::is_banned(asset) { + return Err(DispatchError::Other("BannedAssetTransfer")); } //NOTE: To prevent duplicate ED collection we assume account already paid ED @@ -356,6 +356,8 @@ impl pallet_claims::Config for Runtime { parameter_types! { #[derive(PartialEq, Debug)] pub const RegistryStrLimit: u32 = 32; + #[derive(PartialEq, Debug)] + pub const MinRegistryStrLimit: u32 = 3; pub const SequentialIdOffset: u32 = 1_000_000; pub const StoreFees: Balance = 100 * UNITS; //TODO: } @@ -368,6 +370,7 @@ impl pallet_asset_registry::Config for Runtime { type AssetId = AssetId; type AssetNativeLocation = AssetLocation; type StringLimit = RegistryStrLimit; + type MinStringLimit = MinRegistryStrLimit; type SequentialIdStartAt = SequentialIdOffset; type StorageFeesAssetId = NativeAssetId; type StorageFees = StoreFees; diff --git a/runtime/hydradx/src/weights/registry.rs b/runtime/hydradx/src/weights/registry.rs index 67a301d42..f52baaafe 100644 --- a/runtime/hydradx/src/weights/registry.rs +++ b/runtime/hydradx/src/weights/registry.rs @@ -100,7 +100,7 @@ impl WeightInfo for HydraWeight { // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) - fn blacklist_add() -> Weight { + fn ban_asset() -> Weight { // Minimum execution time: 22_677 nanoseconds. Weight::from_parts(22_950_000, 0) .saturating_add(T::DbWeight::get().reads(2 as u64)) @@ -108,7 +108,7 @@ impl WeightInfo for HydraWeight { } // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) - fn blacklist_remove() -> Weight { + fn unban_asset() -> Weight { // Minimum execution time: 17_460 nanoseconds. Weight::from_parts(17_958_000, 0) .saturating_add(T::DbWeight::get().reads(1 as u64)) diff --git a/traits/src/registry.rs b/traits/src/registry.rs index 393b5cc89..3dbcac14f 100644 --- a/traits/src/registry.rs +++ b/traits/src/registry.rs @@ -51,8 +51,8 @@ pub trait Inspect { #[allow(clippy::too_many_arguments)] pub trait Create: Inspect { type Error; - type Name: Parameter; - type Symbol: Parameter; + type Name: Parameter + TryFrom>; + type Symbol: Parameter + TryFrom>; fn register_asset( asset_id: Option, From 419db3e597a3219cbe8a34df7400186b5d038033 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 29 Jan 2024 15:00:15 +0100 Subject: [PATCH 80/93] asset-registry: fixed all tests after api change --- pallets/asset-registry/src/benchmarking.rs | 40 ++++++++--------- pallets/asset-registry/src/lib.rs | 2 +- .../asset-registry/src/tests/create_trait.rs | 2 +- pallets/asset-registry/src/tests/register.rs | 12 ++--- pallets/asset-registry/src/tests/update.rs | 28 ++++++------ pallets/bonds/src/tests/mock.rs | 17 ++++--- pallets/circuit-breaker/src/tests/mock.rs | 2 +- pallets/dca/src/tests/mock.rs | 2 +- pallets/liquidity-mining/src/tests/mock.rs | 2 +- .../src/benchmarks.rs | 9 ++-- .../src/tests/mock.rs | 12 ++--- pallets/omnipool/src/tests/mock.rs | 2 +- pallets/otc/src/benchmarks.rs | 6 ++- pallets/otc/src/tests/mock.rs | 12 ++--- pallets/stableswap/src/tests/mock.rs | 2 +- pallets/xcm-rate-limiter/src/tests/mock.rs | 2 +- pallets/xyk/src/tests/creation.rs | 20 +++++---- pallets/xyk/src/tests/mock.rs | 3 ++ runtime/adapters/src/tests/mock.rs | 18 ++++---- runtime/hydradx/src/assets.rs | 16 ++++--- runtime/hydradx/src/benchmarking/dca.rs | 14 ++++-- runtime/hydradx/src/benchmarking/mod.rs | 11 ++++- runtime/hydradx/src/benchmarking/omnipool.rs | 24 ++++++++-- .../src/benchmarking/route_executor.rs | 44 ++++++++++++++++--- 24 files changed, 192 insertions(+), 110 deletions(-) diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index 7d75b737e..75abedb2f 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -35,9 +35,9 @@ benchmarks! { register { let asset_id= T::AssetId::from(3); - let name = vec![97u8; T::StringLimit::get() as usize]; + let name: BoundedVec = vec![97u8; T::StringLimit::get() as usize].try_into().unwrap(); let ed = 1_000_000_u128; - let symbol = vec![97u8; T::StringLimit::get() as usize]; + let symbol: BoundedVec = vec![97u8; T::StringLimit::get() as usize].try_into().unwrap(); let decimals = 12_u8; let location: T::AssetNativeLocation = Default::default(); let xcm_rate_limit = 1_000_u128; @@ -45,17 +45,16 @@ benchmarks! { }: _(RawOrigin::Root, Some(asset_id), Some(name.clone()), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient) verify { - let b_name = Pallet::::try_into_bounded(Some(name)).unwrap().unwrap(); - assert!(Pallet::::asset_ids(b_name).is_some()); + assert!(Pallet::::asset_ids(name).is_some()); assert!(Pallet::::assets(asset_id).is_some()); } update { let asset_id = T::AssetId::from(3); - let name = vec![97u8; T::StringLimit::get() as usize]; + let name = vec![97u8; T::StringLimit::get() as usize].try_into().unwrap(); let ed = 1_000_000_u128; - let symbol = vec![97u8; T::StringLimit::get() as usize]; + let symbol = vec![97u8; T::StringLimit::get() as usize].try_into().unwrap(); let decimals = 12_u8; let location: T::AssetNativeLocation = Default::default(); let xcm_rate_limit = 1_000_u128; @@ -63,27 +62,24 @@ benchmarks! { let _ = Pallet::::register(RawOrigin::Root.into(), Some(asset_id), Some(name), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient); - let new_name= vec![98u8; T::StringLimit::get() as usize]; + let new_name:BoundedVec = vec![98u8; T::StringLimit::get() as usize].try_into().unwrap(); let new_type = AssetType::XYK; let new_ed = 1_000_000_u128; let new_xcm_rate_limit = 1_000_u128; let new_is_sufficient = true; - let new_symbol = vec![98u8; T::StringLimit::get() as usize]; + let new_symbol: BoundedVec = vec![98u8; T::StringLimit::get() as usize].try_into().unwrap(); let new_decimals = 12_u8; }: _(RawOrigin::Root, asset_id, Some(new_name.clone()), Some(new_type), Some(new_ed), Some(new_xcm_rate_limit), Some(new_is_sufficient), Some(new_symbol.clone()), Some(new_decimals), Some(Default::default())) verify { - let b_name = Pallet::::try_into_bounded(Some(new_name)).unwrap().unwrap(); - let b_symbol = Pallet::::try_into_bounded(Some(new_symbol)).unwrap().unwrap(); - - assert_eq!(Pallet::::asset_ids(&b_name), Some(asset_id)); + assert_eq!(Pallet::::asset_ids(&new_name), Some(asset_id)); assert_eq!(crate::Pallet::::assets(asset_id), Some(AssetDetails { - name: Some(b_name), + name: Some(new_name), asset_type: new_type, existential_deposit: new_ed, - symbol: Some(b_symbol), + symbol: Some(new_symbol), decimals: Some(new_decimals), xcm_rate_limit: Some(xcm_rate_limit), is_sufficient: new_is_sufficient, @@ -106,9 +102,9 @@ benchmarks! { ban_asset { let asset_id = T::AssetId::from(3); - let name = vec![97u8; T::StringLimit::get() as usize]; + let name = vec![97u8; T::StringLimit::get() as usize].try_into().unwrap(); let ed = 1_000_000_u128; - let symbol = vec![97u8; T::StringLimit::get() as usize]; + let symbol = vec![97u8; T::StringLimit::get() as usize].try_into().unwrap(); let decimals = 12_u8; let location: T::AssetNativeLocation = Default::default(); let xcm_rate_limit = 1_000_u128; @@ -119,14 +115,14 @@ benchmarks! { let origin = T::UpdateOrigin::try_successful_origin().unwrap(); }: _(origin, asset_id) verify { - assert_eq!(Pallet::::blacklists(asset_id), Some(())); + assert_eq!(Pallet::::banned_assets(asset_id), Some(())); } unban_asset { let asset_id = T::AssetId::from(3); - let name = vec![97u8; T::StringLimit::get() as usize]; + let name = vec![97u8; T::StringLimit::get() as usize].try_into().unwrap(); let ed = 1_000_000_u128; - let symbol = vec![97u8; T::StringLimit::get() as usize]; + let symbol = vec![97u8; T::StringLimit::get() as usize].try_into().unwrap(); let decimals = 12_u8; let location: T::AssetNativeLocation = Default::default(); let xcm_rate_limit = 1_000_u128; @@ -134,12 +130,12 @@ benchmarks! { let origin = T::UpdateOrigin::try_successful_origin().unwrap(); let _ = Pallet::::register(RawOrigin::Root.into(), Some(asset_id), Some(name), AssetType::Token, Some(ed), Some(symbol), Some(decimals), Some(location), Some(xcm_rate_limit), is_sufficient); - let _ = Pallet::::blacklist_add(origin.clone(), asset_id); + let _ = Pallet::::ban_asset(origin.clone(), asset_id); - assert_eq!(Pallet::::blacklists(asset_id), Some(())); + assert_eq!(Pallet::::banned_assets(asset_id), Some(())); }: _(origin, asset_id) verify { - assert_eq!(Pallet::::blacklists(asset_id), None); + assert_eq!(Pallet::::banned_assets(asset_id), None); } diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index 42862ab2a..ac99a01e7 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -689,7 +689,7 @@ impl Inspect for Pallet { } fn asset_type(id: Self::AssetId) -> Option { - Self::assets(id).and_then(|a| Some(a.asset_type.into())) + Self::assets(id).map(|a| a.asset_type.into()) } fn is_banned(id: Self::AssetId) -> bool { diff --git a/pallets/asset-registry/src/tests/create_trait.rs b/pallets/asset-registry/src/tests/create_trait.rs index a658e5fba..8c39bb0fe 100644 --- a/pallets/asset-registry/src/tests/create_trait.rs +++ b/pallets/asset-registry/src/tests/create_trait.rs @@ -337,7 +337,7 @@ fn get_or_register_asset_should_return_asset_id_when_asset_exists() { name.clone(), AssetKind::XYK, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), Some(asset_location), Some(xcm_rate_limit), diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index 9e387392c..573d9a321 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -644,7 +644,7 @@ fn register_should_not_work_when_symbol_is_not_valid() { Some(name.clone()), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), @@ -662,7 +662,7 @@ fn register_should_not_work_when_symbol_is_not_valid() { Some(name.clone()), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), @@ -680,7 +680,7 @@ fn register_should_not_work_when_symbol_is_not_valid() { Some(name.clone()), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), Some(asset_location.clone()), Some(xcm_rate_limit), @@ -695,12 +695,12 @@ fn register_should_not_work_when_symbol_is_not_valid() { Registry::register( RuntimeOrigin::root(), Some(asset_id), - Some(name.clone()), + Some(name), AssetType::Token, Some(ed), - Some(symbol.clone()), + Some(symbol), Some(decimals), - Some(asset_location.clone()), + Some(asset_location), Some(xcm_rate_limit), is_sufficient ), diff --git a/pallets/asset-registry/src/tests/update.rs b/pallets/asset-registry/src/tests/update.rs index 6e96a0a0d..d657f87be 100644 --- a/pallets/asset-registry/src/tests/update.rs +++ b/pallets/asset-registry/src/tests/update.rs @@ -904,7 +904,7 @@ fn update_should_not_work_when_symbol_is_not_valid() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location).unwrap(); let symbol: BoundedVec = b"nTkn2 ".to_vec().try_into().unwrap(); //Act @@ -917,7 +917,7 @@ fn update_should_not_work_when_symbol_is_not_valid() { Some(ed), Some(xcm_rate_limit), Some(is_sufficient), - Some(symbol.clone()), + Some(symbol), Some(decimals), None ), @@ -935,7 +935,7 @@ fn update_should_not_work_when_symbol_is_not_valid() { Some(ed), Some(xcm_rate_limit), Some(is_sufficient), - Some(symbol.clone()), + Some(symbol), Some(decimals), None ), @@ -953,7 +953,7 @@ fn update_should_not_work_when_symbol_is_not_valid() { Some(ed), Some(xcm_rate_limit), Some(is_sufficient), - Some(symbol.clone()), + Some(symbol), Some(decimals), None ), @@ -966,12 +966,12 @@ fn update_should_not_work_when_symbol_is_not_valid() { Registry::update( RuntimeOrigin::root(), asset_id, - Some(name.clone()), + Some(name), Some(AssetType::External), Some(ed), Some(xcm_rate_limit), Some(is_sufficient), - Some(symbol.clone()), + Some(symbol), Some(decimals), None ), @@ -996,7 +996,7 @@ fn update_should_work_when_name_is_too_short() { ), ( Some(2), - Some(old_asset_name.clone().try_into().unwrap()), + Some(old_asset_name.try_into().unwrap()), UNIT, None, None, @@ -1026,19 +1026,19 @@ fn update_should_work_when_name_is_too_short() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location).unwrap(); //Act assert_noop!( Registry::update( RuntimeOrigin::root(), asset_id, - Some(name.clone()), + Some(name), Some(AssetType::External), Some(ed), Some(xcm_rate_limit), Some(is_sufficient), - Some(symbol.clone()), + Some(symbol), Some(decimals), None ), @@ -1063,7 +1063,7 @@ fn update_should_work_when_symbol_is_too_short() { ), ( Some(2), - Some(old_asset_name.clone().try_into().unwrap()), + Some(old_asset_name.try_into().unwrap()), UNIT, None, None, @@ -1093,19 +1093,19 @@ fn update_should_work_when_symbol_is_too_short() { //Arrange let key = Junction::from(BoundedVec::try_from(asset_id.encode()).unwrap()); let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - Pallet::::set_location(asset_id, asset_location.clone()).unwrap(); + Pallet::::set_location(asset_id, asset_location).unwrap(); //Act assert_noop!( Registry::update( RuntimeOrigin::root(), asset_id, - Some(name.clone()), + Some(name), Some(AssetType::External), Some(ed), Some(xcm_rate_limit), Some(is_sufficient), - Some(symbol.clone()), + Some(symbol), Some(decimals), None ), diff --git a/pallets/bonds/src/tests/mock.rs b/pallets/bonds/src/tests/mock.rs index fe5527237..4ac045b33 100644 --- a/pallets/bonds/src/tests/mock.rs +++ b/pallets/bonds/src/tests/mock.rs @@ -28,6 +28,7 @@ use frame_support::{ }; use frame_system::EnsureSignedBy; use sp_core::H256; +use sp_runtime::BoundedVec; use std::{cell::RefCell, collections::HashMap}; use hydradx_traits::registry::{Create, Inspect}; @@ -171,13 +172,15 @@ pub struct DummyRegistry(sp_std::marker::PhantomData); impl Create for DummyRegistry { type Error = DispatchError; + type Name = BoundedVec>; + type Symbol = BoundedVec>; fn register_asset( _asset_id: Option, - _name: Option<&[u8]>, + _name: Option, _kind: AssetKind, _existential_deposit: Option, - _symbol: Option<&[u8]>, + _symbol: Option, _decimals: Option, _location: Option, _xcm_rate_limit: Option, @@ -188,10 +191,10 @@ impl Create for DummyRegistry { fn register_insufficient_asset( _asset_id: Option, - _name: Option<&[u8]>, + _name: Option, _kind: AssetKind, existential_deposit: Option, - _symbol: Option<&[u8]>, + _symbol: Option, _decimals: Option, _location: Option, _xcm_rate_limit: Option, @@ -205,10 +208,10 @@ impl Create for DummyRegistry { Ok(assigned) } fn get_or_register_asset( - _name: &[u8], + _name: Self::Name, _kind: AssetKind, _existential_deposit: Option, - _symbol: Option<&[u8]>, + _symbol: Option, _decimals: Option, _location: Option, _xcm_rate_limit: Option, @@ -238,7 +241,7 @@ impl Inspect for DummyRegistry { unimplemented!() } - fn is_blacklisted(_id: Self::AssetId) -> bool { + fn is_banned(_id: Self::AssetId) -> bool { unimplemented!() } diff --git a/pallets/circuit-breaker/src/tests/mock.rs b/pallets/circuit-breaker/src/tests/mock.rs index 7a1f4afca..fe6a0e6db 100644 --- a/pallets/circuit-breaker/src/tests/mock.rs +++ b/pallets/circuit-breaker/src/tests/mock.rs @@ -392,7 +392,7 @@ where matches!(asset, Some(_)) } - fn is_blacklisted(_id: Self::AssetId) -> bool { + fn is_banned(_id: Self::AssetId) -> bool { unimplemented!() } diff --git a/pallets/dca/src/tests/mock.rs b/pallets/dca/src/tests/mock.rs index ad655aa38..75e31d006 100644 --- a/pallets/dca/src/tests/mock.rs +++ b/pallets/dca/src/tests/mock.rs @@ -758,7 +758,7 @@ where matches!(asset, Some(_)) } - fn is_blacklisted(_id: Self::AssetId) -> bool { + fn is_banned(_id: Self::AssetId) -> bool { unimplemented!() } diff --git a/pallets/liquidity-mining/src/tests/mock.rs b/pallets/liquidity-mining/src/tests/mock.rs index fd9b5e54f..53b64b631 100644 --- a/pallets/liquidity-mining/src/tests/mock.rs +++ b/pallets/liquidity-mining/src/tests/mock.rs @@ -445,7 +445,7 @@ impl Inspect for DummyRegistry { name != UNKNOWN_ASSET } - fn is_blacklisted(_id: Self::AssetId) -> bool { + fn is_banned(_id: Self::AssetId) -> bool { unimplemented!() } diff --git a/pallets/omnipool-liquidity-mining/src/benchmarks.rs b/pallets/omnipool-liquidity-mining/src/benchmarks.rs index e8c28816a..7e01ed4a7 100644 --- a/pallets/omnipool-liquidity-mining/src/benchmarks.rs +++ b/pallets/omnipool-liquidity-mining/src/benchmarks.rs @@ -128,11 +128,12 @@ where acc.clone(), )?; + let name = b"BSX".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; // Register new asset in asset registry with_transaction(|| { TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( None, - Some(b"BSX".as_ref()), + Some(name), AssetKind::Token, Balance::one(), None, @@ -141,10 +142,11 @@ where None, )) })?; + let name = b"ETH".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; with_transaction(|| { TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( None, - Some(b"ETH".as_ref()), + Some(name), AssetKind::Token, Balance::one(), None, @@ -153,10 +155,11 @@ where None, )) })?; + let name = b"BTC".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; with_transaction(|| { TransactionOutcome::Commit(T::AssetRegistry::register_sufficient_asset( None, - Some(b"BTC".as_ref()), + Some(name), AssetKind::Token, Balance::one(), None, diff --git a/pallets/omnipool-liquidity-mining/src/tests/mock.rs b/pallets/omnipool-liquidity-mining/src/tests/mock.rs index 373c330bc..6df5d991c 100644 --- a/pallets/omnipool-liquidity-mining/src/tests/mock.rs +++ b/pallets/omnipool-liquidity-mining/src/tests/mock.rs @@ -660,7 +660,7 @@ where matches!(asset, Some(_)) } - fn is_blacklisted(_id: Self::AssetId) -> bool { + fn is_banned(_id: Self::AssetId) -> bool { unimplemented!() } @@ -681,13 +681,15 @@ where T::AssetId: Into + From, { type Error = DispatchError; + type Name = BoundedVec>; + type Symbol = BoundedVec>; fn register_asset( _asset_id: Option, - _name: Option<&[u8]>, + _name: Option, _kind: AssetKind, _existential_deposit: Option, - _symbol: Option<&[u8]>, + _symbol: Option, _decimals: Option, _location: Option, _xcm_rate_limit: Option, @@ -707,10 +709,10 @@ where } fn get_or_register_asset( - _name: &[u8], + _name: Self::Name, _kind: AssetKind, _existential_deposit: Option, - _symbol: Option<&[u8]>, + _symbol: Option, _decimals: Option, _location: Option, _xcm_rate_limit: Option, diff --git a/pallets/omnipool/src/tests/mock.rs b/pallets/omnipool/src/tests/mock.rs index 81e749ecf..aac0fb912 100644 --- a/pallets/omnipool/src/tests/mock.rs +++ b/pallets/omnipool/src/tests/mock.rs @@ -540,7 +540,7 @@ where unimplemented!() } - fn is_blacklisted(_id: Self::AssetId) -> bool { + fn is_banned(_id: Self::AssetId) -> bool { unimplemented!() } diff --git a/pallets/otc/src/benchmarks.rs b/pallets/otc/src/benchmarks.rs index 19901ea9b..e1e14cfff 100644 --- a/pallets/otc/src/benchmarks.rs +++ b/pallets/otc/src/benchmarks.rs @@ -90,10 +90,11 @@ where use sp_runtime::TransactionOutcome; // Register new asset in asset registry + let name = b"DOT".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; let dot = with_transaction(|| { TransactionOutcome::Commit(::AssetRegistry::register_sufficient_asset( None, - Some(b"DOT".as_ref()), + Some(name), AssetKind::Token, ONE, None, @@ -102,10 +103,11 @@ where None, )) })?; + let name = b"DAI".to_vec().try_into().map_err(|_| "BoundedConvertionFailed")?; let dai = with_transaction(|| { TransactionOutcome::Commit(::AssetRegistry::register_sufficient_asset( None, - Some(b"DAI".as_ref()), + Some(name), AssetKind::Token, ONE, None, diff --git a/pallets/otc/src/tests/mock.rs b/pallets/otc/src/tests/mock.rs index dbdbab395..67b9cb65e 100644 --- a/pallets/otc/src/tests/mock.rs +++ b/pallets/otc/src/tests/mock.rs @@ -153,7 +153,7 @@ impl Inspect for DummyRegistry { matches!(asset, Some(_)) } - fn is_blacklisted(_id: Self::AssetId) -> bool { + fn is_banned(_id: Self::AssetId) -> bool { unimplemented!() } @@ -176,13 +176,15 @@ where T::AssetId: Into + From, { type Error = DispatchError; + type Name = sp_runtime::BoundedVec>; + type Symbol = sp_runtime::BoundedVec>; fn register_asset( _asset_id: Option, - _name: Option<&[u8]>, + _name: Option, _kind: AssetKind, _existential_deposit: Option, - _symbol: Option<&[u8]>, + _symbol: Option, _decimals: Option, _location: Option, _xcm_rate_limit: Option, @@ -202,10 +204,10 @@ where } fn get_or_register_asset( - _name: &[u8], + _name: Self::Name, _kind: AssetKind, _existential_deposit: Option, - _symbol: Option<&[u8]>, + _symbol: Option, _decimals: Option, _location: Option, _xcm_rate_limit: Option, diff --git a/pallets/stableswap/src/tests/mock.rs b/pallets/stableswap/src/tests/mock.rs index 0be9c47df..12cd80dec 100644 --- a/pallets/stableswap/src/tests/mock.rs +++ b/pallets/stableswap/src/tests/mock.rs @@ -332,7 +332,7 @@ impl Inspect for DummyRegistry { unimplemented!() } - fn is_blacklisted(_id: Self::AssetId) -> bool { + fn is_banned(_id: Self::AssetId) -> bool { unimplemented!() } diff --git a/pallets/xcm-rate-limiter/src/tests/mock.rs b/pallets/xcm-rate-limiter/src/tests/mock.rs index a9aa22b93..41ff345a4 100644 --- a/pallets/xcm-rate-limiter/src/tests/mock.rs +++ b/pallets/xcm-rate-limiter/src/tests/mock.rs @@ -334,7 +334,7 @@ where matches!(asset, Some(_)) } - fn is_blacklisted(_id: Self::AssetId) -> bool { + fn is_banned(_id: Self::AssetId) -> bool { unimplemented!() } diff --git a/pallets/xyk/src/tests/creation.rs b/pallets/xyk/src/tests/creation.rs index 21f6aa148..c37fbc48e 100644 --- a/pallets/xyk/src/tests/creation.rs +++ b/pallets/xyk/src/tests/creation.rs @@ -379,7 +379,7 @@ fn share_asset_id_should_be_offset() { assert_ok!(AssetRegistry::register( RuntimeOrigin::signed(ALICE), Some(next_asset_id), - Some(asset_pair.name()), + Some(asset_pair.name().try_into().unwrap()), AssetType::XYK, Some(::MinPoolLiquidity::get()), None, @@ -402,10 +402,11 @@ fn share_asset_id_should_be_offset() { let share_token = XYK::share_token(pair_account); assert_eq!(share_token, next_asset_id); - let bounded_name = AssetRegistry::try_into_bounded(Some(asset_pair.name())) - .unwrap() - .unwrap(); - assert_eq!(AssetRegistry::asset_ids(bounded_name).unwrap(), share_token); + assert_eq!( + AssetRegistry::asset_ids::>(asset_pair.name().try_into().unwrap()) + .unwrap(), + share_token + ); // Act let next_asset_id = AssetRegistry::next_asset_id().unwrap(); @@ -429,9 +430,10 @@ fn share_asset_id_should_be_offset() { // Assert assert_eq!(share_token, next_asset_id); - let bounded_name = AssetRegistry::try_into_bounded(Some(asset_pair.name())) - .unwrap() - .unwrap(); - assert_eq!(AssetRegistry::asset_ids(bounded_name).unwrap(), share_token); + assert_eq!( + AssetRegistry::asset_ids::>(asset_pair.name().try_into().unwrap()) + .unwrap(), + share_token + ); }); } diff --git a/pallets/xyk/src/tests/mock.rs b/pallets/xyk/src/tests/mock.rs index 472c9966a..b6d2844cb 100644 --- a/pallets/xyk/src/tests/mock.rs +++ b/pallets/xyk/src/tests/mock.rs @@ -98,6 +98,8 @@ parameter_types! { pub const NativeAssetId: AssetId = HDX; #[derive(PartialEq, Debug)] pub RegistryStringLimit: u32 = 100; + #[derive(PartialEq, Debug)] + pub MinRegistryStringLimit: u32 = 2; pub const SequentialIdOffset: u32 = 1_000_000; pub const StoreFees: Balance = 10 * ONE; pub const FeesBeneficiarry: u64 = TREASURY; @@ -111,6 +113,7 @@ impl pallet_asset_registry::Config for Test { type AssetId = AssetId; type AssetNativeLocation = AssetLocation; type StringLimit = RegistryStringLimit; + type MinStringLimit = MinRegistryStringLimit; type SequentialIdStartAt = SequentialIdOffset; type StorageFeesAssetId = NativeAssetId; type StorageFees = StoreFees; diff --git a/runtime/adapters/src/tests/mock.rs b/runtime/adapters/src/tests/mock.rs index 83e8bf0a0..3c1820c29 100644 --- a/runtime/adapters/src/tests/mock.rs +++ b/runtime/adapters/src/tests/mock.rs @@ -44,11 +44,11 @@ use pallet_omnipool::traits::ExternalPriceProvider; use primitive_types::{U128, U256}; use sp_core::H256; use sp_runtime::traits::Zero; -use sp_runtime::Permill; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, BuildStorage, DispatchError, DispatchResult, FixedU128, }; +use sp_runtime::{BoundedVec, Permill}; use std::cell::RefCell; use std::collections::HashMap; @@ -600,7 +600,7 @@ where matches!(asset, Some(_)) } - fn is_blacklisted(_id: Self::AssetId) -> bool { + fn is_banned(_id: Self::AssetId) -> bool { unimplemented!() } @@ -618,13 +618,15 @@ where T::AssetId: Into + From, { type Error = DispatchError; + type Name = BoundedVec>; + type Symbol = BoundedVec>; fn register_asset( _asset_id: Option, - _name: Option<&[u8]>, + _name: Option, _kind: AssetKind, _existential_deposit: Option, - _symbol: Option<&[u8]>, + _symbol: Option, _decimals: Option, _location: Option, _xcm_rate_limit: Option, @@ -635,10 +637,10 @@ where fn register_insufficient_asset( _asset_id: Option, - _name: Option<&[u8]>, + _name: Option, _kind: AssetKind, _existential_deposit: Option, - _symbol: Option<&[u8]>, + _symbol: Option, _decimals: Option, _location: Option, _xcm_rate_limit: Option, @@ -646,10 +648,10 @@ where unimplemented!() } fn get_or_register_asset( - _name: &[u8], + _name: Self::Name, _kind: AssetKind, _existential_deposit: Option, - _symbol: Option<&[u8]>, + _symbol: Option, _decimals: Option, _location: Option, _xcm_rate_limit: Option, diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index f890d8b5b..b2a094022 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -1041,13 +1041,17 @@ pub struct RegisterAsset(PhantomData); #[cfg(feature = "runtime-benchmarks")] impl BenchmarkHelper for RegisterAsset { fn register_asset(asset_id: AssetId, decimals: u8) -> DispatchResult { - let asset_name = asset_id.to_le_bytes().to_vec(); + let asset_name: BoundedVec = asset_id + .to_le_bytes() + .to_vec() + .try_into() + .map_err(|_| "BoundedConversionFailed")?; AssetRegistry::register_sufficient_asset( Some(asset_id), - Some(&asset_name), + Some(asset_name.clone()), AssetKind::Token, 1, - Some(&asset_name), + Some(asset_name), Some(decimals), None, None, @@ -1349,14 +1353,14 @@ pub struct ReferralsBenchmarkHelper; impl RefBenchmarkHelper for ReferralsBenchmarkHelper { fn prepare_convertible_asset_and_amount() -> (AssetId, Balance) { let asset_id: u32 = 1234u32; - let asset_name = asset_id.to_le_bytes().to_vec(); + let asset_name: BoundedVec = asset_id.to_le_bytes().to_vec().try_into().unwrap(); AssetRegistry::register_asset( Some(asset_id), - Some(&asset_name), + Some(asset_name.clone()), AssetKind::Token, Some(1_000_000), - Some(&asset_name), + Some(asset_name), Some(18), None, None, diff --git a/runtime/hydradx/src/benchmarking/dca.rs b/runtime/hydradx/src/benchmarking/dca.rs index 7b6a2e469..9ca9ef5d3 100644 --- a/runtime/hydradx/src/benchmarking/dca.rs +++ b/runtime/hydradx/src/benchmarking/dca.rs @@ -461,11 +461,19 @@ mod tests { .unwrap(); pallet_asset_registry::GenesisConfig:: { - registered_assets: vec![(Some(DAI), Some(b"DAI".to_vec()), 1_000u128, None, None, None, false)], - native_asset_name: b"HDX".to_vec(), + registered_assets: vec![( + Some(DAI), + Some(b"DAI".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + false, + )], + native_asset_name: b"HDX".to_vec().try_into().unwrap(), native_existential_deposit: NativeExistentialDeposit::get(), native_decimals: 12, - native_symbol: b"HDX".to_vec(), + native_symbol: b"HDX".to_vec().try_into().unwrap(), } .assimilate_storage(&mut t) .unwrap(); diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index 849234096..afc647c04 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -23,10 +23,11 @@ use frame_support::storage::with_transaction; use sp_runtime::TransactionOutcome; pub fn register_asset(name: Vec, deposit: Balance) -> Result { + let n = name.try_into().map_err(|_| ())?; with_transaction(|| { TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( None, - Some(&name), + Some(n), AssetKind::Token, deposit, None, @@ -40,11 +41,17 @@ pub fn register_asset(name: Vec, deposit: Balance) -> Result { #[allow(dead_code)] pub fn update_asset(asset_id: AssetId, name: Option>, deposit: Balance) -> Result<(), ()> { + let nm = if let Some(n) = name { + Some(n.try_into().map_err(|_| ())?) + } else { + None + }; + with_transaction(|| { TransactionOutcome::Commit(AssetRegistry::update( RawOrigin::Root.into(), asset_id, - name, + nm, None, Some(deposit), None, diff --git a/runtime/hydradx/src/benchmarking/omnipool.rs b/runtime/hydradx/src/benchmarking/omnipool.rs index 3694806eb..e1b43a0ae 100644 --- a/runtime/hydradx/src/benchmarking/omnipool.rs +++ b/runtime/hydradx/src/benchmarking/omnipool.rs @@ -531,13 +531,29 @@ mod tests { pallet_asset_registry::GenesisConfig:: { registered_assets: vec![ - (Some(1), Some(b"LRNA".to_vec()), 1_000u128, None, None, None, true), - (Some(2), Some(b"DAI".to_vec()), 1_000u128, None, None, None, true), + ( + Some(1), + Some(b"LRNA".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"DAI".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), ], - native_asset_name: b"HDX".to_vec(), + native_asset_name: b"HDX".to_vec().try_into().unwrap(), native_existential_deposit: NativeExistentialDeposit::get(), native_decimals: 12, - native_symbol: b"HDX".to_vec(), + native_symbol: b"HDX".to_vec().try_into().unwrap(), } .assimilate_storage(&mut t) .unwrap(); diff --git a/runtime/hydradx/src/benchmarking/route_executor.rs b/runtime/hydradx/src/benchmarking/route_executor.rs index 997e71ca1..e73448407 100644 --- a/runtime/hydradx/src/benchmarking/route_executor.rs +++ b/runtime/hydradx/src/benchmarking/route_executor.rs @@ -262,14 +262,46 @@ mod tests { pallet_asset_registry::GenesisConfig:: { registered_assets: vec![ - (Some(1), Some(b"LRNA".to_vec()), 1_000u128, None, None, None, true), - (Some(2), Some(b"DAI".to_vec()), 1_000u128, None, None, None, true), - (Some(3), Some(b"FCA".to_vec()), 1_000u128, None, None, None, true), - (Some(4), Some(b"FCB".to_vec()), 1_000u128, None, None, None, true), + ( + Some(1), + Some(b"LRNA".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(2), + Some(b"DAI".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(3), + Some(b"FCA".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), + ( + Some(4), + Some(b"FCB".to_vec().try_into().unwrap()), + 1_000u128, + None, + None, + None, + true, + ), ], - native_asset_name: b"HDX".to_vec(), + native_asset_name: b"HDX".to_vec().try_into().unwrap(), native_existential_deposit: NativeExistentialDeposit::get(), - native_symbol: b"HDX".to_vec(), + native_symbol: b"HDX".to_vec().try_into().unwrap(), native_decimals: 12, } .assimilate_storage(&mut t) From 1a9a429e830e5d1d6b8660d3f158f8f5c3b89da5 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 29 Jan 2024 16:05:03 +0100 Subject: [PATCH 81/93] sufficiency-check: collect little bit more than pay back on account killed --- .../src/insufficient_assets_ed.rs | 83 ++++++++++--------- runtime/hydradx/src/assets.rs | 16 ++-- 2 files changed, 52 insertions(+), 47 deletions(-) diff --git a/integration-tests/src/insufficient_assets_ed.rs b/integration-tests/src/insufficient_assets_ed.rs index 5396ba1ac..8b83607b5 100644 --- a/integration-tests/src/insufficient_assets_ed.rs +++ b/integration-tests/src/insufficient_assets_ed.rs @@ -8,7 +8,7 @@ use frame_system::RawOrigin; use hydradx_runtime::RuntimeOrigin as hydra_origin; use hydradx_runtime::{ AssetRegistry as Registry, Currencies, DustRemovalWhitelist, InsufficientEDinHDX, MultiTransactionPayment, - RuntimeEvent, TechnicalCollective, Tokens, TreasuryAccount, SUFFICIENCY_LOCK, + NativeExistentialDeposit, RuntimeEvent, TechnicalCollective, Tokens, TreasuryAccount, SUFFICIENCY_LOCK, }; use hydradx_traits::NativePriceOracle; use orml_traits::MultiCurrency; @@ -57,7 +57,7 @@ fn sender_should_pay_ed_in_hdx_when_it_is_not_whitelisted() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_balance + InsufficientEDinHDX::get() ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -109,7 +109,7 @@ fn reciever_should_pay_ed_in_hdx_when_insuficcient_asset_was_deposited() { treasury_balance + InsufficientEDinHDX::get() ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -145,7 +145,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_hdx() { let alice_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); //Act assert_ok!(Tokens::transfer( @@ -158,13 +158,13 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_hdx() { //Assert assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), - alice_balance + InsufficientEDinHDX::get() + alice_balance + NativeExistentialDeposit::get() ); assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_balance - InsufficientEDinHDX::get() + treasury_balance - NativeExistentialDeposit::get() ); assert_eq!(treasury_sufficiency_lock(), 0); @@ -251,7 +251,7 @@ fn sender_should_pay_ed_only_when_dest_didnt_pay_yet() { .unwrap() .saturating_mul_int(InsufficientEDinHDX::get()); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -319,7 +319,7 @@ fn dest_should_pay_ed_only_once_when_insufficient_asset_was_depsitted() { .unwrap() .saturating_mul_int(InsufficientEDinHDX::get()); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -372,7 +372,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); let treasury_fee_asset_balance = Currencies::free_balance(fee_asset, &TreasuryAccount::get()); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); //Act assert_ok!(Tokens::transfer( @@ -386,7 +386,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset //NOTE: we always returns ED in HDX assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance + InsufficientEDinHDX::get() + alice_hdx_balance + NativeExistentialDeposit::get() ); assert_eq!(Currencies::free_balance(sht1, &ALICE.into()), 0); assert_eq!( @@ -396,7 +396,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_balance - InsufficientEDinHDX::get() + treasury_hdx_balance - NativeExistentialDeposit::get() ); assert_eq!( Currencies::free_balance(fee_asset, &TreasuryAccount::get()), @@ -410,6 +410,7 @@ fn hdx_ed_should_be_released_when_account_is_killed_and_ed_was_paid_in_fee_asset 0_u128 ); + //NOTE: this is colected amount, not locked amount. assert_event_times!( RuntimeEvent::AssetRegistry(pallet_asset_registry::Event::ExistentialDepositPaid { who: ALICE.into(), @@ -513,7 +514,7 @@ fn sender_should_pay_ed_in_fee_asset_when_sending_insufficient_asset() { treasury_fee_asset_balance + ed_in_fee_asset ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), @@ -573,7 +574,7 @@ fn account_with_zero_sufficients_should_not_release_ed() { treasury_hdx_balance ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -604,7 +605,7 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() let alice_sufficient_asset_balance = Currencies::free_balance(DAI, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -629,7 +630,7 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -654,7 +655,7 @@ fn ed_should_not_be_collected_when_transfering_or_depositing_sufficient_assets() Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -689,7 +690,7 @@ fn ed_should_not_be_released_when_sufficient_asset_killed_account() { let alice_sufficient_asset_balance = Currencies::free_balance(DAI, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -717,7 +718,7 @@ fn ed_should_not_be_released_when_sufficient_asset_killed_account() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -814,7 +815,7 @@ fn ed_should_be_collected_for_each_insufficient_asset_when_transfered_or_deposit Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance + InsufficientEDinHDX::get() * 4 ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get() * 4); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get() * 4); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 4_u128 @@ -871,7 +872,7 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get() * 4); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get() * 4); //Act 1 assert_ok!(Tokens::transfer( @@ -884,13 +885,13 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { //Assert 1 assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance + InsufficientEDinHDX::get() + alice_hdx_balance + NativeExistentialDeposit::get() ); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_balance - InsufficientEDinHDX::get() + treasury_hdx_balance - NativeExistentialDeposit::get() ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get() * 3); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get() * 3); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 3_u128 @@ -907,13 +908,13 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { //Assert 2 assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance + InsufficientEDinHDX::get() * 2 + alice_hdx_balance + NativeExistentialDeposit::get() * 2 ); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_balance - InsufficientEDinHDX::get() * 2 + treasury_hdx_balance - NativeExistentialDeposit::get() * 2 ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get() * 2); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get() * 2); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 2_u128 @@ -930,13 +931,13 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { //Assert 3 assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance + InsufficientEDinHDX::get() * 3 + alice_hdx_balance + NativeExistentialDeposit::get() * 3 ); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_balance - InsufficientEDinHDX::get() * 3 + treasury_hdx_balance - NativeExistentialDeposit::get() * 3 ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -953,11 +954,11 @@ fn ed_should_be_released_for_each_insufficient_asset_when_account_is_killed() { //Assert 3 assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance + InsufficientEDinHDX::get() * 4 + alice_hdx_balance + NativeExistentialDeposit::get() * 4 ); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_balance - InsufficientEDinHDX::get() * 4 + treasury_hdx_balance - NativeExistentialDeposit::get() * 4 ); assert_eq!(treasury_sufficiency_lock(), 0); assert_eq!( @@ -1011,7 +1012,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { let alice_hdx_balance = Currencies::free_balance(HDX, &ALICE.into()); let treasury_hdx_balance = Currencies::free_balance(HDX, &TreasuryAccount::get()); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get() * 2); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get() * 2); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 2_u128 @@ -1028,13 +1029,13 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { //Assert 1 assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance + InsufficientEDinHDX::get() + alice_hdx_balance + NativeExistentialDeposit::get() ); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_balance - InsufficientEDinHDX::get() + treasury_hdx_balance - NativeExistentialDeposit::get() ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -1059,7 +1060,7 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { Currencies::free_balance(HDX, &TreasuryAccount::get()), treasury_hdx_balance ); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -1080,11 +1081,11 @@ fn mix_of_sufficinet_and_insufficient_assets_should_lock_unlock_ed_correctly() { //Assert 3 assert_eq!( Currencies::free_balance(HDX, &ALICE.into()), - alice_hdx_balance + InsufficientEDinHDX::get() + alice_hdx_balance + NativeExistentialDeposit::get() ); assert_eq!( Currencies::free_balance(HDX, &TreasuryAccount::get()), - treasury_hdx_balance - InsufficientEDinHDX::get() + treasury_hdx_balance - NativeExistentialDeposit::get() ); assert_eq!(treasury_sufficiency_lock(), 0); assert_eq!( @@ -1183,7 +1184,7 @@ fn sender_should_pay_ed_when_tranferred_or_deposited_to_whitelisted_dest() { bob_fee_asset_balance - InsufficientEDinHDX::get() ); assert_eq!(Currencies::free_balance(sht1, &treasury), 10); - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 @@ -1200,7 +1201,7 @@ fn sender_should_pay_ed_when_tranferred_or_deposited_to_whitelisted_dest() { assert_eq!(Currencies::free_balance(sht1, &treasury), 10); assert_eq!(Currencies::free_balance(sht2, &treasury), 20); //NOTE: treasury paid ED in hdx so hdx balance didn't changed but locked was increased. - assert_eq!(treasury_sufficiency_lock(), 2 * InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), 2 * NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 2_u128 @@ -1261,7 +1262,7 @@ fn ed_should_be_released_when_whitelisted_account_was_killed() { let treasury_hdx_balance = Currencies::free_balance(HDX, &treasury); //NOTE: set_balance bypass mutation hooks so only Bob paid ED for Treasury. - assert_eq!(treasury_sufficiency_lock(), InsufficientEDinHDX::get()); + assert_eq!(treasury_sufficiency_lock(), NativeExistentialDeposit::get()); assert_eq!( pallet_asset_registry::pallet::ExistentialDepositCounter::::get(), 1_u128 diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index b2a094022..144f7c5a1 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -122,6 +122,8 @@ impl MutationHooks for CurrencyHooks { pub const SUFFICIENCY_LOCK: LockIdentifier = *b"insuffED"; parameter_types! { + //NOTE: This should always be > 1 otherwise we will payout more than we collected as ED for + //insufficient assets. pub InsufficientEDinHDX: Balance = FixedU128::from_rational(11, 10) .saturating_mul_int(::ExistentialDeposit::get()); } @@ -133,7 +135,8 @@ impl SufficiencyCheck { /// If transferred asset is not sufficient asset, it calculates ED amount in user's fee asset /// and transfers it from user to treasury account. /// Function also locks corresponding HDX amount in the treasury because returned ED to the users - /// when the account is killed is in the HDX. + /// when the account is killed is in the HDX. We are collecting little bit more (currencty 10%)than + /// we are paying back when account is killed. /// /// We assume account already paid ED if it holds transferred insufficient asset so additional /// ED payment is not necessary. @@ -182,12 +185,13 @@ impl SufficiencyCheck { ) .map_err(|_| orml_tokens::Error::::ExistentialDeposit)?; + //NOTE: we are locking little bit less than charging. let to_lock = pallet_balances::Locks::::get(TreasuryAccount::get()) .iter() .find(|x| x.id == SUFFICIENCY_LOCK) .map(|p| p.amount) .unwrap_or_default() - .saturating_add(InsufficientEDinHDX::get()); + .saturating_add(::ExistentialDeposit::get()); >::set_lock( SUFFICIENCY_LOCK, @@ -244,9 +248,9 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { .map(|p| p.amount) .unwrap_or_default(); - let paid_accounts = pallet_asset_registry::ExistentialDepositCounter::::get(); - let ed_to_refund = if paid_accounts != 0 { - locked_ed.saturating_div(paid_accounts) + let paid_counts = pallet_asset_registry::ExistentialDepositCounter::::get(); + let ed_to_refund = if paid_counts != 0 { + locked_ed.saturating_div(paid_counts) } else { 0 }; @@ -277,7 +281,7 @@ impl Happened<(AccountId, AssetId)> for OnKilledTokenAccount { ); frame_system::Pallet::::dec_sufficients(who); - pallet_asset_registry::ExistentialDepositCounter::::set(paid_accounts.saturating_sub(1)); + pallet_asset_registry::ExistentialDepositCounter::::set(paid_counts.saturating_sub(1)); } } From 374b3cea6300ca561bb7f6e02b930f9cd78af0b8 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 30 Jan 2024 10:30:45 +0100 Subject: [PATCH 82/93] asset-registry: README update --- pallets/asset-registry/README.md | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/pallets/asset-registry/README.md b/pallets/asset-registry/README.md index 73e676aaa..170b522e5 100644 --- a/pallets/asset-registry/README.md +++ b/pallets/asset-registry/README.md @@ -8,22 +8,17 @@ Asset registry provides functionality to create, store and keep tracking of exis - **CoreAssetId** - asset id of native/core asset. Usually 0. - **NextAssetId** - asset id to be assigned for next asset added to the system. - **AssetIds** - list of existing asset ids -- **AssetDetail** - details of an asset such as type, name or whether it is locked or not. -- **AssetMetadata** - additional optional metadata of an asset ( symbol, decimals) +- **AssetDetail** - details of an asset such as type, name, symbol, decimals. - **AssetLocation** - information of native location of an asset. Used in XCM. ### Implementation detail For each newly registered asset, a sequential id is assigned to that asset. This id identifies the asset and can be used directly in transfers or any other operation which works with an asset ( without performing any additioanl asset check or asset retrieval). -There is a mapping between the name and asset id stored as well, which helps and is used in AMM Implementation where there is a need to register a pool asset and only name is provided ( see `get_or_create_asset` ). +There is a mapping between the name and asset id stored as well, which helps and is used in AMM Implementation where there is a need to register a pool asset and only name is provided. An asset has additional details stored on chain such as name and type. -Optional metadata can be also set for an asset. - The registry pallet supports storing of native location of an asset. This can be used in XCM where it is possible to create mapping between native location and local system asset ids. -### Interface -- `get_or_create_asset` - creates new asset id for give asset name. If such asset already exists, it returns the corresponding asset id. - +The registry pallet implements single ppermissionles extrinsic `register_external` that collects storage deposit for created asset. From 50aa50e455adbc60a54451a2e3fe58dadd138b44 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Wed, 31 Jan 2024 10:19:34 +0100 Subject: [PATCH 83/93] bumb versions --- Cargo.lock | 28 ++++++++++---------- integration-tests/Cargo.toml | 2 +- node/Cargo.toml | 2 +- pallets/circuit-breaker/Cargo.toml | 2 +- pallets/dca/Cargo.toml | 2 +- pallets/lbp/Cargo.toml | 2 +- pallets/omnipool/Cargo.toml | 2 +- pallets/stableswap/Cargo.toml | 2 +- pallets/staking/Cargo.toml | 2 +- pallets/transaction-multi-payment/Cargo.toml | 2 +- pallets/xcm-rate-limiter/Cargo.toml | 2 +- runtime/adapters/Cargo.toml | 2 +- 12 files changed, 25 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 06095b320..6017c7552 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4482,7 +4482,7 @@ dependencies = [ [[package]] name = "hydradx" -version = "12.0.0" +version = "12.1.0" dependencies = [ "async-trait", "clap 4.4.11", @@ -4571,7 +4571,7 @@ dependencies = [ [[package]] name = "hydradx-adapters" -version = "1.0.0" +version = "1.0.1" dependencies = [ "cumulus-pallet-parachain-system", "cumulus-primitives-core", @@ -4597,7 +4597,7 @@ dependencies = [ "pallet-referrals", "pallet-route-executor", "pallet-stableswap", - "pallet-staking 2.1.2", + "pallet-staking 2.1.3", "pallet-transaction-multi-payment", "pallet-uniques", "pallet-xyk", @@ -4691,7 +4691,7 @@ dependencies = [ "pallet-scheduler", "pallet-session", "pallet-stableswap", - "pallet-staking 2.1.2", + "pallet-staking 2.1.3", "pallet-timestamp", "pallet-tips", "pallet-transaction-multi-payment", @@ -7223,7 +7223,7 @@ dependencies = [ [[package]] name = "pallet-circuit-breaker" -version = "1.1.19" +version = "1.1.20" dependencies = [ "frame-benchmarking", "frame-support", @@ -7366,7 +7366,7 @@ dependencies = [ [[package]] name = "pallet-dca" -version = "1.3.3" +version = "1.3.4" dependencies = [ "cumulus-pallet-parachain-system", "cumulus-primitives-core", @@ -7750,7 +7750,7 @@ dependencies = [ [[package]] name = "pallet-lbp" -version = "4.7.3" +version = "4.7.4" dependencies = [ "frame-benchmarking", "frame-support", @@ -7997,7 +7997,7 @@ dependencies = [ [[package]] name = "pallet-omnipool" -version = "4.1.1" +version = "4.1.2" dependencies = [ "bitflags 1.3.2", "frame-benchmarking", @@ -8292,7 +8292,7 @@ dependencies = [ [[package]] name = "pallet-stableswap" -version = "3.4.2" +version = "3.4.3" dependencies = [ "bitflags 1.3.2", "frame-benchmarking", @@ -8316,7 +8316,7 @@ dependencies = [ [[package]] name = "pallet-staking" -version = "2.1.2" +version = "2.1.3" dependencies = [ "frame-benchmarking", "frame-support", @@ -8462,7 +8462,7 @@ dependencies = [ [[package]] name = "pallet-transaction-multi-payment" -version = "9.2.1" +version = "9.3.0" dependencies = [ "frame-support", "frame-system", @@ -8670,7 +8670,7 @@ dependencies = [ [[package]] name = "pallet-xcm-rate-limiter" -version = "0.1.4" +version = "0.1.5" dependencies = [ "cumulus-pallet-xcmp-queue", "frame-benchmarking", @@ -11227,7 +11227,7 @@ dependencies = [ [[package]] name = "runtime-integration-tests" -version = "1.17.1" +version = "1.18.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", @@ -11286,7 +11286,7 @@ dependencies = [ "pallet-scheduler", "pallet-session", "pallet-stableswap", - "pallet-staking 2.1.2", + "pallet-staking 2.1.3", "pallet-timestamp", "pallet-tips", "pallet-transaction-multi-payment", diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index 5380fb31b..7878a6d56 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runtime-integration-tests" -version = "1.17.1" +version = "1.18.0" description = "Integration tests" authors = ["GalacticCouncil"] edition = "2021" diff --git a/node/Cargo.toml b/node/Cargo.toml index c5591126c..d246a8cd5 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx" -version = "12.0.0" +version = "12.1.0" description = "HydraDX node" authors = ["GalacticCouncil"] edition = "2021" diff --git a/pallets/circuit-breaker/Cargo.toml b/pallets/circuit-breaker/Cargo.toml index 408d5bc35..926a8872d 100644 --- a/pallets/circuit-breaker/Cargo.toml +++ b/pallets/circuit-breaker/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-circuit-breaker" -version = "1.1.19" +version = "1.1.20" authors = ["GalacticCouncil "] edition = "2021" license = "Apache-2.0" diff --git a/pallets/dca/Cargo.toml b/pallets/dca/Cargo.toml index 5296ec4ad..481420ca1 100644 --- a/pallets/dca/Cargo.toml +++ b/pallets/dca/Cargo.toml @@ -1,6 +1,6 @@ [package] name = 'pallet-dca' -version = "1.3.3" +version = "1.3.4" description = 'A pallet to manage DCA scheduling' authors = ['GalacticCouncil'] edition = '2021' diff --git a/pallets/lbp/Cargo.toml b/pallets/lbp/Cargo.toml index 297c239b1..dd2eda000 100644 --- a/pallets/lbp/Cargo.toml +++ b/pallets/lbp/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-lbp" -version = "4.7.3" +version = "4.7.4" description = "HydraDX Liquidity Bootstrapping Pool Pallet" authors = ["GalacticCouncil"] edition = "2021" diff --git a/pallets/omnipool/Cargo.toml b/pallets/omnipool/Cargo.toml index e6bb6e41a..c71c6967c 100644 --- a/pallets/omnipool/Cargo.toml +++ b/pallets/omnipool/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-omnipool" -version = "4.1.1" +version = "4.1.2" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/stableswap/Cargo.toml b/pallets/stableswap/Cargo.toml index e9b2cd21b..59ed741ea 100644 --- a/pallets/stableswap/Cargo.toml +++ b/pallets/stableswap/Cargo.toml @@ -1,6 +1,6 @@ [package] name = 'pallet-stableswap' -version = '3.4.2' +version = '3.4.3' description = 'AMM for correlated assets' authors = ['GalacticCouncil'] edition = '2021' diff --git a/pallets/staking/Cargo.toml b/pallets/staking/Cargo.toml index 09b1b3807..bf9f34ac7 100644 --- a/pallets/staking/Cargo.toml +++ b/pallets/staking/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-staking" -version = "2.1.2" +version = "2.1.3" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/transaction-multi-payment/Cargo.toml b/pallets/transaction-multi-payment/Cargo.toml index 1b1dbf76b..cb2114ac1 100644 --- a/pallets/transaction-multi-payment/Cargo.toml +++ b/pallets/transaction-multi-payment/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-transaction-multi-payment" -version = "9.2.1" +version = "9.3.0" description = "Transaction multi currency payment support module" authors = ["GalacticCoucil"] edition = "2021" diff --git a/pallets/xcm-rate-limiter/Cargo.toml b/pallets/xcm-rate-limiter/Cargo.toml index c56229927..a657534ed 100644 --- a/pallets/xcm-rate-limiter/Cargo.toml +++ b/pallets/xcm-rate-limiter/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-xcm-rate-limiter" -version = "0.1.4" +version = "0.1.5" authors = ["GalacticCouncil "] edition = "2021" license = "Apache-2.0" diff --git a/runtime/adapters/Cargo.toml b/runtime/adapters/Cargo.toml index 0779550af..c9ceee6f8 100644 --- a/runtime/adapters/Cargo.toml +++ b/runtime/adapters/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-adapters" -version = "1.0.0" +version = "1.0.1" description = "Structs and other generic types for building runtimes." authors = ["GalacticCouncil"] edition = "2021" From c157817cc76eb1857cb35fad607b8988f416d1c6 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 1 Feb 2024 10:06:29 +0100 Subject: [PATCH 84/93] orml-tokens: update benchmarks worst case, account with sufficiency check --- runtime/hydradx/src/benchmarking/mod.rs | 18 ++++ runtime/hydradx/src/benchmarking/tokens.rs | 109 +++++++++++++++++---- 2 files changed, 108 insertions(+), 19 deletions(-) diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index afc647c04..7541d576c 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -14,6 +14,7 @@ use frame_system::RawOrigin; use hydradx_traits::{registry::Create, AssetKind}; use primitives::{AssetId, Balance}; +use sp_runtime::traits::One; use sp_std::vec; use sp_std::vec::Vec; @@ -39,6 +40,23 @@ pub fn register_asset(name: Vec, deposit: Balance) -> Result { .map_err(|_| ()) } +pub fn register_external_asset(name: Vec) -> Result { + let n = name.try_into().map_err(|_| ())?; + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_insufficient_asset( + None, + Some(n), + AssetKind::External, + Some(Balance::one()), + None, + None, + None, + None, + )) + }) + .map_err(|_| ()) +} + #[allow(dead_code)] pub fn update_asset(asset_id: AssetId, name: Option>, deposit: Balance) -> Result<(), ()> { let nm = if let Some(n) = name { diff --git a/runtime/hydradx/src/benchmarking/tokens.rs b/runtime/hydradx/src/benchmarking/tokens.rs index c20000524..3477b0eab 100644 --- a/runtime/hydradx/src/benchmarking/tokens.rs +++ b/runtime/hydradx/src/benchmarking/tokens.rs @@ -1,21 +1,24 @@ -use crate::{AccountId, AssetId, Balance, Runtime, Tokens}; +use crate::{AccountId, AssetId, Balance, Currencies, MultiTransactionPayment, Runtime, Tokens}; use sp_std::prelude::*; +use frame_benchmarking::account; use frame_benchmarking::BenchmarkError; -use frame_benchmarking::{account, whitelisted_caller}; use frame_system::RawOrigin; use frame_support::assert_ok; use orml_benchmarking::runtime_benchmarks; use orml_traits::MultiCurrency; use orml_traits::MultiCurrencyExtended; +use primitives::Price; use super::*; use sp_runtime::traits::{SaturatedConversion, StaticLookup}; const SEED: u32 = 0; +const HDX: AssetId = 0; +const UNIT: Balance = 1_000_000_000_000; pub fn lookup_of_account(who: AccountId) -> <::Lookup as StaticLookup>::Source { ::Lookup::unlookup(who) @@ -33,60 +36,128 @@ runtime_benchmarks! { { Runtime, orml_tokens } transfer { - let amount: Balance = BSX; + let amount: Balance = 2 * UNIT; - let asset_id = register_asset(b"TST".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_id = register_external_asset(b"TST".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - let from: AccountId = whitelisted_caller(); + let from: AccountId = account("from", 0, SEED); + >::update_balance(HDX, &from, (10_000 * UNIT) as i128)?; update_balance(asset_id, &from, amount); + update_balance(fee_asset, &from, 1_000 * UNIT); - let to: AccountId = account("to", 0, SEED); + MultiTransactionPayment::add_currency(RawOrigin::Root.into(), fee_asset, Price::from(1)).map_err(|_| BenchmarkError::Stop("Failed to add supported currency"))?; + pallet_transaction_multi_payment::pallet::AcceptedCurrencyPrice::::insert(fee_asset, Price::from(1)); + + MultiTransactionPayment::set_currency( + RawOrigin::Signed(from.clone().into()).into(), + fee_asset + )?; + + let to: AccountId = account("to", 1, SEED); let to_lookup = lookup_of_account(to.clone()); - }: _(RawOrigin::Signed(from), to_lookup, asset_id, amount) + }: _(RawOrigin::Signed(from.clone()), to_lookup, asset_id, amount) verify { assert_eq!(>::total_balance(asset_id, &to), amount); + assert_eq!(frame_system::Pallet::::account(to).sufficients, 1); + + //NOTE: make sure from was killed + assert_eq!(orml_tokens::Accounts::::contains_key(from.clone(), asset_id), false); + assert_eq!(pallet_asset_registry::ExistentialDepositCounter::::get(), 1); + assert_eq!(frame_system::Pallet::::account(from).sufficients, 0); } transfer_all { - let amount: Balance = BSX; + let amount: Balance = 1 * UNIT; - let asset_id = register_asset(b"TST".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_id = register_external_asset(b"TST".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - let from: AccountId = whitelisted_caller(); + let from: AccountId = account("from", 0, SEED); + >::update_balance(HDX, &from, (10_000 * UNIT) as i128)?; update_balance(asset_id, &from, amount); + update_balance(fee_asset, &from, 1_000 * UNIT); + + MultiTransactionPayment::add_currency(RawOrigin::Root.into(), fee_asset, Price::from(1)).map_err(|_| BenchmarkError::Stop("Failed to add supported currency"))?; + pallet_transaction_multi_payment::pallet::AcceptedCurrencyPrice::::insert(fee_asset, Price::from(1)); + + MultiTransactionPayment::set_currency( + RawOrigin::Signed(from.clone().into()).into(), + fee_asset + )?; let to: AccountId = account("to", 0, SEED); let to_lookup = lookup_of_account(to); }: _(RawOrigin::Signed(from.clone()), to_lookup, asset_id, false) verify { assert_eq!(>::total_balance(asset_id, &from), 0); + + //NOTE: make sure from was killed + assert_eq!(orml_tokens::Accounts::::contains_key(from.clone(), asset_id), false); + assert_eq!(pallet_asset_registry::ExistentialDepositCounter::::get(), 1); + assert_eq!(frame_system::Pallet::::account(from).sufficients, 0); } transfer_keep_alive { - let from: AccountId = whitelisted_caller(); - let asset_id = register_asset(b"TST".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - update_balance(asset_id, &from, 2 * BSX); + let asset_id = register_external_asset(b"TST".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + + let from: AccountId = account("from", 0, SEED); + >::update_balance(HDX, &from, (10_000 * UNIT) as i128)?; + update_balance(asset_id, &from, 2 * UNIT); + update_balance(fee_asset, &from, 1_000 * UNIT); + + MultiTransactionPayment::add_currency(RawOrigin::Root.into(), fee_asset, Price::from(1)).map_err(|_| BenchmarkError::Stop("Failed to add supported currency"))?; + pallet_transaction_multi_payment::pallet::AcceptedCurrencyPrice::::insert(fee_asset, Price::from(1)); + + MultiTransactionPayment::set_currency( + RawOrigin::Signed(from.clone().into()).into(), + fee_asset + )?; let to: AccountId = account("to", 0, SEED); let to_lookup = lookup_of_account(to.clone()); - }: _(RawOrigin::Signed(from), to_lookup, asset_id, BSX) + }: _(RawOrigin::Signed(from), to_lookup, asset_id, UNIT) verify { - assert_eq!(>::total_balance(asset_id, &to), BSX); + assert_eq!(>::total_balance(asset_id, &to), UNIT); + + //NOTE: make sure none was killed + assert_eq!(pallet_asset_registry::ExistentialDepositCounter::::get(), 2); } force_transfer { + let amount = 2 * UNIT; + + let asset_id = register_external_asset(b"TST".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let from: AccountId = account("from", 0, SEED); let from_lookup = lookup_of_account(from.clone()); - let asset_id = register_asset(b"TST".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; - update_balance(asset_id, &from, 2 * BSX); + >::update_balance(HDX, &from, (10_000 * UNIT) as i128)?; + update_balance(asset_id, &from, amount); + update_balance(fee_asset, &from, 1_000 * UNIT); + + MultiTransactionPayment::add_currency(RawOrigin::Root.into(), fee_asset, Price::from(1)).map_err(|_| BenchmarkError::Stop("Failed to add supported currency"))?; + pallet_transaction_multi_payment::pallet::AcceptedCurrencyPrice::::insert(fee_asset, Price::from(1)); + + MultiTransactionPayment::set_currency( + RawOrigin::Signed(from.clone().into()).into(), + fee_asset + )?; let to: AccountId = account("to", 0, SEED); let to_lookup = lookup_of_account(to.clone()); - }: _(RawOrigin::Root, from_lookup, to_lookup, asset_id, BSX) + }: _(RawOrigin::Root, from_lookup, to_lookup, asset_id, amount) verify { - assert_eq!(>::total_balance(asset_id, &to), BSX); + assert_eq!(>::total_balance(asset_id, &to), amount); + + //NOTE: make sure from was killed + assert_eq!(orml_tokens::Accounts::::contains_key(from.clone(), asset_id), false); + assert_eq!(pallet_asset_registry::ExistentialDepositCounter::::get(), 1); + assert_eq!(frame_system::Pallet::::account(from).sufficients, 0); } + //NOTE: set balance bypass MutationHooks so sufficiency check is never triggered. set_balance { let who: AccountId = account("who", 0, SEED); let who_lookup = lookup_of_account(who.clone()); From 1e9be748198b27dee2470b6b67928c82485b242b Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Mon, 12 Feb 2024 17:21:39 +0100 Subject: [PATCH 85/93] xyk: benchmarks update --- pallets/xyk/src/benchmarking.rs | 210 ------------------ pallets/xyk/src/lib.rs | 2 - runtime/hydradx/src/benchmarking/mod.rs | 1 + runtime/hydradx/src/benchmarking/xyk.rs | 282 ++++++++++++++++++++++++ runtime/hydradx/src/lib.rs | 4 +- 5 files changed, 285 insertions(+), 214 deletions(-) delete mode 100644 pallets/xyk/src/benchmarking.rs create mode 100644 runtime/hydradx/src/benchmarking/xyk.rs diff --git a/pallets/xyk/src/benchmarking.rs b/pallets/xyk/src/benchmarking.rs deleted file mode 100644 index 19b1adf07..000000000 --- a/pallets/xyk/src/benchmarking.rs +++ /dev/null @@ -1,210 +0,0 @@ -// This file is part of HydraDX-node. - -// Copyright (C) 2022 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#![cfg(feature = "runtime-benchmarks")] - -use super::*; - -use frame_benchmarking::{account, benchmarks}; -use frame_system::RawOrigin; -use sp_std::prelude::*; - -use crate::Pallet as XYK; - -use crate::types::{AssetId, Balance}; -use hydradx_traits::router::{PoolType, TradeExecution}; - -const SEED: u32 = 1; - -fn funded_account(name: &'static str, index: u32) -> T::AccountId { - let caller: T::AccountId = account(name, index, SEED); - //Necessary for ED for insufficient assets. - T::Currency::update_balance(0, &caller, 1_000_000_000_000_000).unwrap(); - - T::Currency::update_balance(1, &caller, 1_000_000_000_000_000).unwrap(); - T::Currency::update_balance(2, &caller, 1_000_000_000_000_000).unwrap(); - caller -} - -benchmarks! { - create_pool { - let caller = funded_account::("caller", 0); - - let asset_a: AssetId = 1; - let asset_b: AssetId = 2; - let amount_a : Balance = 10 * 1_000_000_000; - let amount_b : Balance = 20 * 1_000_000_000; - - }: _(RawOrigin::Signed(caller.clone()), asset_a, amount_a, asset_b, amount_b) - verify { - assert_eq!(T::Currency::free_balance(asset_a, &caller), 999990000000000); - } - - add_liquidity { - let maker = funded_account::("maker", 0); - let caller = funded_account::("caller", 0); - - let asset_a: AssetId = 1; - let asset_b: AssetId = 2; - let amount : Balance = 10 * 1_000_000_000; - let max_limit : Balance = 10 * 1_000_000_000_000; - - XYK::::create_pool(RawOrigin::Signed(maker).into(), asset_a, 1_000_000_000,asset_b, 1_000_000_000)?; - - }: _(RawOrigin::Signed(caller.clone()), asset_a, asset_b, amount, max_limit) - verify { - assert_eq!(T::Currency::free_balance(asset_a, &caller), 999990000000000); - assert_eq!(T::Currency::free_balance(asset_b, &caller), 999990000000000 - 1); // Due to rounding in favor of pool - } - - remove_liquidity { - let maker = funded_account::("maker", 0); - let caller = funded_account::("caller", 0); - - let asset_a: AssetId = 1; - let asset_b: AssetId = 2; - let amount : Balance = 1_000_000_000; - - XYK::::create_pool(RawOrigin::Signed(maker).into(), 1, 10_000_000_000, 2, 20_000_000_000)?; - XYK::::add_liquidity(RawOrigin::Signed(caller.clone()).into(), 1, 2, 5_000_000_000, 10_100_000_000)?; - - assert_eq!(T::Currency::free_balance(asset_a, &caller), 999995000000000); - assert_eq!(T::Currency::free_balance(asset_b, &caller), 999990000000000 - 1);// Due to rounding in favor of pool - - }: _(RawOrigin::Signed(caller.clone()), asset_a, asset_b, amount) - verify { - assert_eq!(T::Currency::free_balance(asset_a, &caller), 999996000000000); - assert_eq!(T::Currency::free_balance(asset_b, &caller), 999992000000000 - 1);// Due to rounding in favor of pool - } - - sell { - let maker = funded_account::("maker", 0); - let caller = funded_account::("caller", 0); - - let asset_a: AssetId = 1; - let asset_b: AssetId = 2; - let amount : Balance = 1_000_000_000; - let discount = false; - - let min_bought: Balance = 10 * 1_000; - - XYK::::create_pool(RawOrigin::Signed(maker).into(), asset_a, 1_000_000_000_000, asset_b, 3_000_000_000_000)?; - - }: _(RawOrigin::Signed(caller.clone()), asset_a, asset_b, amount, min_bought, discount) - verify{ - assert_eq!(T::Currency::free_balance(asset_a, &caller), 999999000000000); - } - - buy { - let maker = funded_account::("maker", 0); - let caller = funded_account::("caller", 0); - - let asset_a: AssetId = 1; - let asset_b: AssetId = 2; - let amount : Balance = 1_000_000_000; - let discount = false; - - let max_sold: Balance = 6_000_000_000; - - XYK::::create_pool(RawOrigin::Signed(maker).into(), asset_a, 1_000_000_000_000, asset_b, 3_000_000_000_000)?; - - }: _(RawOrigin::Signed(caller.clone()), asset_a, asset_b, amount, max_sold, discount) - verify{ - assert_eq!(T::Currency::free_balance(asset_a, &caller), 1000001000000000); - } - - router_execution_sell { - let c in 1..2; // if c == 1, calculate_sell is executed - let e in 0..1; // if e == 1, execute_sell is executed - - let maker = funded_account::("maker", 0); - let caller = funded_account::("caller", 0); - - let asset_a: AssetId = 1; - let asset_b: AssetId = 2; - let amount : Balance = 1_000_000_000; - let discount = false; - - let min_bought: Balance = 10 * 1_000; - - XYK::::create_pool(RawOrigin::Signed(maker).into(), asset_a, 1_000_000_000_000, asset_b, 3_000_000_000_000)?; - - }: { - for _ in 1..c { - assert!( as TradeExecution>::calculate_sell(PoolType::XYK, asset_a, asset_b, amount).is_ok()); - } - if e != 0 { - assert!( as TradeExecution>::execute_sell(RawOrigin::Signed(caller.clone()).into(), PoolType::XYK, asset_a, asset_b, amount, min_bought).is_ok()); - } - } - verify{ - if e != 0 { - assert_eq!(T::Currency::free_balance(asset_a, &caller), 999999000000000); - } - } - - router_execution_buy { - let c in 1..3; // number of times calculate_buy is executed - let e in 0..1; // if e == 1, execute_buy is executed - - let maker = funded_account::("maker", 0); - let caller = funded_account::("caller", 0); - - let asset_a: AssetId = 1; - let asset_b: AssetId = 2; - let amount : Balance = 1_000_000_000; - let discount = false; - - let max_sold: Balance = 6_000_000_000; - - XYK::::create_pool(RawOrigin::Signed(maker).into(), asset_a, 1_000_000_000_000, asset_b, 3_000_000_000_000)?; - - }: { - for _ in 1..c { - assert!( as TradeExecution>::calculate_buy(PoolType::XYK, asset_a, asset_b, amount).is_ok()); - } - if e != 0 { - assert!( as TradeExecution>::execute_buy(RawOrigin::Signed(caller.clone()).into(), PoolType::XYK, asset_a, asset_b, amount, max_sold).is_ok()); - } - } - verify{ - if e != 0 { - assert_eq!(T::Currency::free_balance(asset_b, &caller), 1000001000000000); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::tests::mock::{ExtBuilder, System, Test}; - use frame_support::assert_ok; - - #[test] - fn test_benchmarks() { - ExtBuilder::default().build().execute_with(|| { - System::set_block_number(1); - assert_ok!(Pallet::::test_benchmark_create_pool()); - assert_ok!(Pallet::::test_benchmark_add_liquidity()); - assert_ok!(Pallet::::test_benchmark_remove_liquidity()); - assert_ok!(Pallet::::test_benchmark_sell()); - assert_ok!(Pallet::::test_benchmark_buy()); - assert_ok!(Pallet::::test_benchmark_router_execution_sell()); - assert_ok!(Pallet::::test_benchmark_router_execution_buy()); - }); - } -} diff --git a/pallets/xyk/src/lib.rs b/pallets/xyk/src/lib.rs index 5629fe097..c75ca97ba 100644 --- a/pallets/xyk/src/lib.rs +++ b/pallets/xyk/src/lib.rs @@ -45,8 +45,6 @@ use orml_traits::{MultiCurrency, MultiCurrencyExtended}; #[cfg(test)] mod tests; -mod benchmarking; - mod impls; mod trade_execution; pub mod types; diff --git a/runtime/hydradx/src/benchmarking/mod.rs b/runtime/hydradx/src/benchmarking/mod.rs index 7541d576c..f380d1188 100644 --- a/runtime/hydradx/src/benchmarking/mod.rs +++ b/runtime/hydradx/src/benchmarking/mod.rs @@ -8,6 +8,7 @@ pub mod omnipool; pub mod route_executor; pub mod tokens; pub mod vesting; +pub mod xyk; use crate::AssetRegistry; use frame_system::RawOrigin; diff --git a/runtime/hydradx/src/benchmarking/xyk.rs b/runtime/hydradx/src/benchmarking/xyk.rs new file mode 100644 index 000000000..0d2b41472 --- /dev/null +++ b/runtime/hydradx/src/benchmarking/xyk.rs @@ -0,0 +1,282 @@ +use crate::{AccountId, AssetId, Balance, Currencies, MultiTransactionPayment, Price, Runtime, RuntimeOrigin, XYK}; + +use super::*; + +use frame_benchmarking::{account, BenchmarkError}; +use frame_system::RawOrigin; +use orml_benchmarking::runtime_benchmarks; +use orml_traits::{MultiCurrency, MultiCurrencyExtended}; +use sp_std::prelude::*; + +use hydradx_traits::router::{PoolType, TradeExecution}; + +const SEED: u32 = 1; + +const INITIAL_BALANCE: Balance = 1_000_000_000_000_000; + +fn funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> T::AccountId { + let caller: T::AccountId = account(name, index, SEED); + //Necessary for ED for insufficient assets. + T::Currency::update_balance(0, &caller, INITIAL_BALANCE as i128).unwrap(); + + for a in assets { + T::Currency::update_balance(*a, &caller, INITIAL_BALANCE as i128).unwrap(); + } + + caller +} + +fn init_fee_asset(fee_asset: AssetId) -> Result<(), BenchmarkError> { + MultiTransactionPayment::add_currency(RawOrigin::Root.into(), fee_asset, Price::from(1)) + .map_err(|_| BenchmarkError::Stop("Failed to add fee asset as supported currency"))?; + + pallet_transaction_multi_payment::pallet::AcceptedCurrencyPrice::::insert(fee_asset, Price::from(1)); + + Ok(()) +} + +runtime_benchmarks! { + { Runtime, pallet_xyk } + + create_pool { + let asset_a = register_external_asset(b"TKNA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_b = register_external_asset(b"TKNB".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + + let caller = funded_account::("caller", 0, &[asset_a, asset_b, fee_asset]); + + init_fee_asset(fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + + let amount_a : Balance = INITIAL_BALANCE; + let amount_b : Balance = INITIAL_BALANCE; + + assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 2); + }: _(RawOrigin::Signed(caller.clone()), asset_a, amount_a, asset_b, amount_b) + verify { + assert_eq!(Currencies::free_balance(asset_a, &caller), 0); + assert_eq!(Currencies::free_balance(asset_b, &caller), 0); + + assert_eq!(orml_tokens::Accounts::::contains_key(caller.clone(), asset_a), false); + assert_eq!(orml_tokens::Accounts::::contains_key(caller.clone(), asset_b), false); + + //NOTE: xyk shares are insufficinet so that's why not 0. + assert_eq!(frame_system::Pallet::::account(caller).sufficients, 1); + } + + add_liquidity { + let asset_a = register_external_asset(b"TKNA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_b = register_external_asset(b"TKNB".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + + let caller = funded_account::("caller", 0, &[asset_a, asset_b, fee_asset]); + let maker = funded_account::("maker", 1, &[asset_a, asset_b, fee_asset]); + + init_fee_asset(fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + + let amount_a : Balance = INITIAL_BALANCE; + let amount_b : Balance = INITIAL_BALANCE; + + let amount : Balance = INITIAL_BALANCE/2; + let max_limit : Balance = INITIAL_BALANCE; + + + XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE - 10, asset_b, INITIAL_BALANCE - 10)?; + + >::transfer(asset_a, &caller, &maker, INITIAL_BALANCE - amount)?; + + assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 2); + }: _(RawOrigin::Signed(caller.clone()), asset_a, asset_b, amount, max_limit) + verify { + assert_eq!(Currencies::free_balance(asset_a, &caller), 0); + assert_eq!(Currencies::free_balance(asset_b, &caller), 499_999_999_999_999_u128);// Due to rounding in favor of pool + + //NOTE: xyk shares are insufficinet. + assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 2); + } + + remove_liquidity { + let asset_a = register_external_asset(b"TKNA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_b = register_external_asset(b"TKNB".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + + let maker = funded_account::("maker", 0, &[asset_a, asset_b, fee_asset]); + + + init_fee_asset(fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; + + XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE, asset_b, INITIAL_BALANCE)?; + + //Only for XYK shares + assert_eq!(frame_system::Pallet::::account(maker.clone()).sufficients, 1); + }: _(RawOrigin::Signed(maker.clone()), asset_a, asset_b, INITIAL_BALANCE) + verify { + assert_eq!(Currencies::free_balance(asset_a, &maker), INITIAL_BALANCE); + assert_eq!(Currencies::free_balance(asset_b, &maker), INITIAL_BALANCE); + + assert_eq!(frame_system::Pallet::::account(maker.clone()).sufficients, 2); + } + + sell { + let asset_a = register_external_asset(b"TKNA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_b = register_external_asset(b"TKNB".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + + let maker = funded_account::("maker", 0, &[asset_a, asset_b, fee_asset]); + let caller = funded_account::("caller", 1, &[asset_a, fee_asset]); + + + init_fee_asset(fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + + let discount = false; + let amount: Balance = 250_000_000_000_000; + let min_bought: Balance = 1; + + XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE, asset_b, INITIAL_BALANCE)?; + + >::transfer(asset_a, &caller, &maker.clone(), INITIAL_BALANCE - amount)?; + + assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); + }: _(RawOrigin::Signed(caller.clone()), asset_a, asset_b, amount, min_bought, discount) + verify{ + assert_eq!(Currencies::free_balance(asset_a, &caller), 0); + assert_eq!(Currencies::free_balance(asset_b, &caller), 199400000000000); + + //NOTE: `asset_a`'s ED was released `asset_b`'s ED was collected. + assert_eq!(frame_system::Pallet::::account(caller).sufficients, 1); + } + + buy { + let asset_a = register_external_asset(b"TKNA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_b = register_external_asset(b"TKNB".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + + let maker = funded_account::("maker", 0, &[asset_a, asset_b, fee_asset]); + let caller = funded_account::("caller", 1, &[asset_a, fee_asset]); + + + init_fee_asset(fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + + let discount = false; + let amount: Balance = 200_000_000_000_000; + let max_sold: Balance = INITIAL_BALANCE; + + XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE, asset_b, INITIAL_BALANCE)?; + + >::transfer(asset_a, &caller, &maker.clone(), 749_249_999_999_999_u128)?; + + assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); + }: _(RawOrigin::Signed(caller.clone()), asset_b, asset_a, amount, max_sold, discount) + verify{ + assert_eq!(Currencies::free_balance(asset_a, &caller), 0); + assert_eq!(Currencies::free_balance(asset_b, &caller), amount); + + assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); + } + + router_execution_sell { + let c in 1..2; // if c == 1, calculate_sell is executed + let e in 0..1; // if e == 1, execute_sell is executed + + let asset_a = register_external_asset(b"TKNA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_b = register_external_asset(b"TKNB".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + + let maker = funded_account::("maker", 0, &[asset_a, asset_b, fee_asset]); + let caller = funded_account::("caller", 1, &[asset_a, fee_asset]); + + + init_fee_asset(fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + + let discount = false; + let amount: Balance = 250_000_000_000_000; + let min_bought: Balance = 1; + + XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE, asset_b, INITIAL_BALANCE)?; + + >::transfer(asset_a, &caller, &maker.clone(), INITIAL_BALANCE - amount)?; + assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); + }: { + for _ in 1..c { + assert!(>::calculate_sell(PoolType::XYK, asset_a, asset_b, amount).is_ok()); + } + if e != 0 { + assert!(>::execute_sell(RawOrigin::Signed(caller.clone()).into(), PoolType::XYK, asset_a, asset_b, amount, min_bought).is_ok()); + } + } + verify{ + if e != 0 { + assert_eq!(Currencies::free_balance(asset_a, &caller), 0); + assert_eq!(Currencies::free_balance(asset_b, &caller), 199400000000000); + + assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); + } + } + + router_execution_buy { + let c in 1..3; // number of times calculate_buy is executed + let e in 0..1; // if e == 1, execute_buy is executed + + let asset_a = register_external_asset(b"TKNA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_b = register_external_asset(b"TKNB".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + + let maker = funded_account::("maker", 0, &[asset_a, asset_b, fee_asset]); + let caller = funded_account::("caller", 1, &[asset_a, fee_asset]); + + + init_fee_asset(fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + + let discount = false; + let amount: Balance = 200_000_000_000_000; + let max_sold: Balance = INITIAL_BALANCE; + + XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE, asset_b, INITIAL_BALANCE)?; + + >::transfer(asset_a, &caller, &maker.clone(), 749_249_999_999_999_u128)?; + + assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); + }: { + for _ in 1..c { + assert!(>::calculate_buy(PoolType::XYK, asset_a, asset_b, amount).is_ok()); + } + if e != 0 { + assert!(>::execute_buy(RawOrigin::Signed(caller.clone()).into(), PoolType::XYK, asset_a, asset_b, amount, max_sold).is_ok()); + } + } + verify{ + if e != 0 { + assert_eq!(Currencies::free_balance(asset_a, &caller), 0); + assert_eq!(Currencies::free_balance(asset_b, &caller), amount); + + assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use orml_benchmarking::impl_benchmark_test_suite; + use sp_runtime::BuildStorage; + + fn new_test_ext() -> sp_io::TestExternalities { + frame_system::GenesisConfig::::default() + .build_storage() + .unwrap() + .into() + } + + impl_benchmark_test_suite!(new_test_ext(),); +} diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index ed07a09b6..97ae9ef26 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -621,7 +621,6 @@ impl_runtime_apis! { list_benchmark!(list, extra, pallet_ema_oracle, EmaOracle); list_benchmark!(list, extra, pallet_staking, Staking); list_benchmark!(list, extra, pallet_lbp, LBP); - list_benchmark!(list, extra, pallet_xyk, XYK); list_benchmark!(list, extra, cumulus_pallet_xcmp_queue, XcmpQueue); list_benchmark!(list, extra, pallet_transaction_pause, TransactionPause); @@ -637,6 +636,7 @@ impl_runtime_apis! { orml_list_benchmark!(list, extra, pallet_omnipool, benchmarking::omnipool); orml_list_benchmark!(list, extra, pallet_route_executor, benchmarking::route_executor); orml_list_benchmark!(list, extra, pallet_dca, benchmarking::dca); + orml_list_benchmark!(list, extra, pallet_xyk, benchmarking::xyk); let storage_info = AllPalletsWithSystem::storage_info(); @@ -700,7 +700,6 @@ impl_runtime_apis! { add_benchmark!(params, batches, pallet_bonds, Bonds); add_benchmark!(params, batches, pallet_staking, Staking); add_benchmark!(params, batches, pallet_lbp, LBP); - add_benchmark!(params, batches, pallet_xyk, XYK); add_benchmark!(params, batches, pallet_stableswap, Stableswap); add_benchmark!(params, batches, pallet_referrals, Referrals); @@ -718,6 +717,7 @@ impl_runtime_apis! { orml_add_benchmark!(params, batches, pallet_omnipool, benchmarking::omnipool); orml_add_benchmark!(params, batches, pallet_route_executor, benchmarking::route_executor); orml_add_benchmark!(params, batches, pallet_dca, benchmarking::dca); + orml_add_benchmark!(params, batches, pallet_xyk, benchmarking::xyk); if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } Ok(batches) From 1d9371181f7e5b0e0d2d2d7893d6d6f27ffbfd78 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 13 Feb 2024 11:36:13 +0100 Subject: [PATCH 86/93] make clippy happy --- runtime/hydradx/src/benchmarking/tokens.rs | 16 ++++---- runtime/hydradx/src/benchmarking/xyk.rs | 46 +++++++++++----------- 2 files changed, 31 insertions(+), 31 deletions(-) diff --git a/runtime/hydradx/src/benchmarking/tokens.rs b/runtime/hydradx/src/benchmarking/tokens.rs index 3477b0eab..6edeae8f6 100644 --- a/runtime/hydradx/src/benchmarking/tokens.rs +++ b/runtime/hydradx/src/benchmarking/tokens.rs @@ -50,7 +50,7 @@ runtime_benchmarks! { pallet_transaction_multi_payment::pallet::AcceptedCurrencyPrice::::insert(fee_asset, Price::from(1)); MultiTransactionPayment::set_currency( - RawOrigin::Signed(from.clone().into()).into(), + RawOrigin::Signed(from.clone()).into(), fee_asset )?; @@ -62,13 +62,13 @@ runtime_benchmarks! { assert_eq!(frame_system::Pallet::::account(to).sufficients, 1); //NOTE: make sure from was killed - assert_eq!(orml_tokens::Accounts::::contains_key(from.clone(), asset_id), false); + assert!(!orml_tokens::Accounts::::contains_key(from.clone(), asset_id)); assert_eq!(pallet_asset_registry::ExistentialDepositCounter::::get(), 1); assert_eq!(frame_system::Pallet::::account(from).sufficients, 0); } transfer_all { - let amount: Balance = 1 * UNIT; + let amount: Balance = UNIT; let asset_id = register_external_asset(b"TST".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; let fee_asset = register_asset(b"FEE".to_vec(), 1u128).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; @@ -82,7 +82,7 @@ runtime_benchmarks! { pallet_transaction_multi_payment::pallet::AcceptedCurrencyPrice::::insert(fee_asset, Price::from(1)); MultiTransactionPayment::set_currency( - RawOrigin::Signed(from.clone().into()).into(), + RawOrigin::Signed(from.clone()).into(), fee_asset )?; @@ -93,7 +93,7 @@ runtime_benchmarks! { assert_eq!(>::total_balance(asset_id, &from), 0); //NOTE: make sure from was killed - assert_eq!(orml_tokens::Accounts::::contains_key(from.clone(), asset_id), false); + assert!(!orml_tokens::Accounts::::contains_key(from.clone(), asset_id)); assert_eq!(pallet_asset_registry::ExistentialDepositCounter::::get(), 1); assert_eq!(frame_system::Pallet::::account(from).sufficients, 0); } @@ -111,7 +111,7 @@ runtime_benchmarks! { pallet_transaction_multi_payment::pallet::AcceptedCurrencyPrice::::insert(fee_asset, Price::from(1)); MultiTransactionPayment::set_currency( - RawOrigin::Signed(from.clone().into()).into(), + RawOrigin::Signed(from.clone()).into(), fee_asset )?; @@ -141,7 +141,7 @@ runtime_benchmarks! { pallet_transaction_multi_payment::pallet::AcceptedCurrencyPrice::::insert(fee_asset, Price::from(1)); MultiTransactionPayment::set_currency( - RawOrigin::Signed(from.clone().into()).into(), + RawOrigin::Signed(from.clone()).into(), fee_asset )?; @@ -152,7 +152,7 @@ runtime_benchmarks! { assert_eq!(>::total_balance(asset_id, &to), amount); //NOTE: make sure from was killed - assert_eq!(orml_tokens::Accounts::::contains_key(from.clone(), asset_id), false); + assert!(!orml_tokens::Accounts::::contains_key(from.clone(), asset_id)); assert_eq!(pallet_asset_registry::ExistentialDepositCounter::::get(), 1); assert_eq!(frame_system::Pallet::::account(from).sufficients, 0); } diff --git a/runtime/hydradx/src/benchmarking/xyk.rs b/runtime/hydradx/src/benchmarking/xyk.rs index 0d2b41472..e4b29f928 100644 --- a/runtime/hydradx/src/benchmarking/xyk.rs +++ b/runtime/hydradx/src/benchmarking/xyk.rs @@ -46,7 +46,7 @@ runtime_benchmarks! { let caller = funded_account::("caller", 0, &[asset_a, asset_b, fee_asset]); init_fee_asset(fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone()).into(), fee_asset)?; let amount_a : Balance = INITIAL_BALANCE; let amount_b : Balance = INITIAL_BALANCE; @@ -57,8 +57,8 @@ runtime_benchmarks! { assert_eq!(Currencies::free_balance(asset_a, &caller), 0); assert_eq!(Currencies::free_balance(asset_b, &caller), 0); - assert_eq!(orml_tokens::Accounts::::contains_key(caller.clone(), asset_a), false); - assert_eq!(orml_tokens::Accounts::::contains_key(caller.clone(), asset_b), false); + assert!(!orml_tokens::Accounts::::contains_key(caller.clone(), asset_a)); + assert!(!orml_tokens::Accounts::::contains_key(caller.clone(), asset_b)); //NOTE: xyk shares are insufficinet so that's why not 0. assert_eq!(frame_system::Pallet::::account(caller).sufficients, 1); @@ -73,8 +73,8 @@ runtime_benchmarks! { let maker = funded_account::("maker", 1, &[asset_a, asset_b, fee_asset]); init_fee_asset(fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone()).into(), fee_asset)?; let amount_a : Balance = INITIAL_BALANCE; let amount_b : Balance = INITIAL_BALANCE; @@ -94,7 +94,7 @@ runtime_benchmarks! { assert_eq!(Currencies::free_balance(asset_b, &caller), 499_999_999_999_999_u128);// Due to rounding in favor of pool //NOTE: xyk shares are insufficinet. - assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 2); + assert_eq!(frame_system::Pallet::::account(caller).sufficients, 2); } remove_liquidity { @@ -106,7 +106,7 @@ runtime_benchmarks! { init_fee_asset(fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone()).into(), fee_asset)?; XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE, asset_b, INITIAL_BALANCE)?; @@ -117,7 +117,7 @@ runtime_benchmarks! { assert_eq!(Currencies::free_balance(asset_a, &maker), INITIAL_BALANCE); assert_eq!(Currencies::free_balance(asset_b, &maker), INITIAL_BALANCE); - assert_eq!(frame_system::Pallet::::account(maker.clone()).sufficients, 2); + assert_eq!(frame_system::Pallet::::account(maker).sufficients, 2); } sell { @@ -130,8 +130,8 @@ runtime_benchmarks! { init_fee_asset(fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone()).into(), fee_asset)?; let discount = false; let amount: Balance = 250_000_000_000_000; @@ -139,7 +139,7 @@ runtime_benchmarks! { XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE, asset_b, INITIAL_BALANCE)?; - >::transfer(asset_a, &caller, &maker.clone(), INITIAL_BALANCE - amount)?; + >::transfer(asset_a, &caller, &maker, INITIAL_BALANCE - amount)?; assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); }: _(RawOrigin::Signed(caller.clone()), asset_a, asset_b, amount, min_bought, discount) @@ -161,8 +161,8 @@ runtime_benchmarks! { init_fee_asset(fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone()).into(), fee_asset)?; let discount = false; let amount: Balance = 200_000_000_000_000; @@ -170,7 +170,7 @@ runtime_benchmarks! { XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE, asset_b, INITIAL_BALANCE)?; - >::transfer(asset_a, &caller, &maker.clone(), 749_249_999_999_999_u128)?; + >::transfer(asset_a, &caller, &maker, 749_249_999_999_999_u128)?; assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); }: _(RawOrigin::Signed(caller.clone()), asset_b, asset_a, amount, max_sold, discount) @@ -178,7 +178,7 @@ runtime_benchmarks! { assert_eq!(Currencies::free_balance(asset_a, &caller), 0); assert_eq!(Currencies::free_balance(asset_b, &caller), amount); - assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); + assert_eq!(frame_system::Pallet::::account(caller).sufficients, 1); } router_execution_sell { @@ -194,8 +194,8 @@ runtime_benchmarks! { init_fee_asset(fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone()).into(), fee_asset)?; let discount = false; let amount: Balance = 250_000_000_000_000; @@ -203,7 +203,7 @@ runtime_benchmarks! { XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE, asset_b, INITIAL_BALANCE)?; - >::transfer(asset_a, &caller, &maker.clone(), INITIAL_BALANCE - amount)?; + >::transfer(asset_a, &caller, &maker, INITIAL_BALANCE - amount)?; assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); }: { for _ in 1..c { @@ -218,7 +218,7 @@ runtime_benchmarks! { assert_eq!(Currencies::free_balance(asset_a, &caller), 0); assert_eq!(Currencies::free_balance(asset_b, &caller), 199400000000000); - assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); + assert_eq!(frame_system::Pallet::::account(caller).sufficients, 1); } } @@ -235,8 +235,8 @@ runtime_benchmarks! { init_fee_asset(fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone().into()).into(), fee_asset)?; - MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone().into()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(maker.clone()).into(), fee_asset)?; + MultiTransactionPayment::set_currency(RawOrigin::Signed(caller.clone()).into(), fee_asset)?; let discount = false; let amount: Balance = 200_000_000_000_000; @@ -244,7 +244,7 @@ runtime_benchmarks! { XYK::create_pool(RawOrigin::Signed(maker.clone()).into(), asset_a, INITIAL_BALANCE, asset_b, INITIAL_BALANCE)?; - >::transfer(asset_a, &caller, &maker.clone(), 749_249_999_999_999_u128)?; + >::transfer(asset_a, &caller, &maker, 749_249_999_999_999_u128)?; assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); }: { @@ -260,7 +260,7 @@ runtime_benchmarks! { assert_eq!(Currencies::free_balance(asset_a, &caller), 0); assert_eq!(Currencies::free_balance(asset_b, &caller), amount); - assert_eq!(frame_system::Pallet::::account(caller.clone()).sufficients, 1); + assert_eq!(frame_system::Pallet::::account(caller).sufficients, 1); } } } From 19f700f74c1a9d97e78ac33833fd777b775baf76 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 13 Feb 2024 11:49:45 +0100 Subject: [PATCH 87/93] bump versions --- Cargo.lock | 6 +++--- pallets/omnipool/Cargo.toml | 2 +- pallets/stableswap/Cargo.toml | 2 +- runtime/hydradx/Cargo.toml | 2 +- runtime/hydradx/src/lib.rs | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1bad31eb3..aef01e81a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4618,7 +4618,7 @@ dependencies = [ [[package]] name = "hydradx-runtime" -version = "206.0.0" +version = "207.0.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", @@ -7997,7 +7997,7 @@ dependencies = [ [[package]] name = "pallet-omnipool" -version = "4.1.2" +version = "4.1.3" dependencies = [ "bitflags 1.3.2", "frame-benchmarking", @@ -8292,7 +8292,7 @@ dependencies = [ [[package]] name = "pallet-stableswap" -version = "3.4.3" +version = "3.4.4" dependencies = [ "bitflags 1.3.2", "frame-benchmarking", diff --git a/pallets/omnipool/Cargo.toml b/pallets/omnipool/Cargo.toml index c71c6967c..2abae4039 100644 --- a/pallets/omnipool/Cargo.toml +++ b/pallets/omnipool/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-omnipool" -version = "4.1.2" +version = "4.1.3" authors = ['GalacticCouncil'] edition = "2021" license = "Apache-2.0" diff --git a/pallets/stableswap/Cargo.toml b/pallets/stableswap/Cargo.toml index 59ed741ea..fda85f6b9 100644 --- a/pallets/stableswap/Cargo.toml +++ b/pallets/stableswap/Cargo.toml @@ -1,6 +1,6 @@ [package] name = 'pallet-stableswap' -version = '3.4.3' +version = '3.4.4' description = 'AMM for correlated assets' authors = ['GalacticCouncil'] edition = '2021' diff --git a/runtime/hydradx/Cargo.toml b/runtime/hydradx/Cargo.toml index 501190821..038c7086b 100644 --- a/runtime/hydradx/Cargo.toml +++ b/runtime/hydradx/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-runtime" -version = "206.0.0" +version = "207.0.0" authors = ["GalacticCouncil"] edition = "2021" license = "Apache 2.0" diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index 97ae9ef26..55de5f3fe 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -107,7 +107,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("hydradx"), impl_name: create_runtime_str!("hydradx"), authoring_version: 1, - spec_version: 206, + spec_version: 207, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, From 36079cf20210937e0a821e8f8db410721db90a3f Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 15 Feb 2024 06:44:30 +0100 Subject: [PATCH 88/93] router: allow to store insufficient assets route and fixed benchmarks --- pallets/route-executor/src/lib.rs | 7 ++ .../src/benchmarking/route_executor.rs | 83 +++++-------------- 2 files changed, 27 insertions(+), 63 deletions(-) diff --git a/pallets/route-executor/src/lib.rs b/pallets/route-executor/src/lib.rs index e9f026222..4cc5425da 100644 --- a/pallets/route-executor/src/lib.rs +++ b/pallets/route-executor/src/lib.rs @@ -511,6 +511,13 @@ impl Pallet { with_transaction(|| { let origin: OriginFor = Origin::::Signed(Self::router_account()).into(); + //NOTE: This is necessary so router's account can pay ED for insufficient assets in the + //route. Value is 10K to make sure we can pay ED for really long routes. + let _ = T::Currency::mint_into( + T::NativeAssetId::get(), + &Self::router_account(), + 10_000_000_000_000_000_u128.into(), + ); let _ = T::Currency::mint_into(asset_in, &Self::router_account(), amount_in); let sell_result = Self::sell(origin, asset_in, asset_out, amount_in, u128::MIN.into(), route.clone()); diff --git a/runtime/hydradx/src/benchmarking/route_executor.rs b/runtime/hydradx/src/benchmarking/route_executor.rs index e73448407..d26bfe169 100644 --- a/runtime/hydradx/src/benchmarking/route_executor.rs +++ b/runtime/hydradx/src/benchmarking/route_executor.rs @@ -20,7 +20,9 @@ use crate::{ AccountId, AssetId, Balance, Currencies, InsufficientEDinHDX, Router, Runtime, RuntimeOrigin, System, LBP, XYK, }; -use frame_benchmarking::account; +use super::*; + +use frame_benchmarking::{account, BenchmarkError}; use frame_support::dispatch::DispatchResult; use frame_support::{assert_ok, ensure}; use frame_system::RawOrigin; @@ -35,6 +37,9 @@ pub const INITIAL_BALANCE: Balance = 10_000_000 * UNITS; fn funded_account(name: &'static str, index: u32, assets: &[AssetId]) -> AccountId { let account: AccountId = account(name, index, 0); + //Necessary to pay ED for insufficient assets. + >::update_balance(0, &account, INITIAL_BALANCE as i128).unwrap(); + for asset in assets { assert_ok!(>::update_balance( *asset, @@ -96,7 +101,7 @@ fn setup_lbp(caller: AccountId, asset_in: AssetId, asset_out: AssetId) -> Dispat } fn create_xyk_pool(asset_a: u32, asset_b: u32) { - let caller: AccountId = funded_account("caller", 0, &[asset_a, asset_b]); + let caller: AccountId = funded_account("caller", 3, &[asset_a, asset_b]); assert_ok!(Currencies::update_balance( RawOrigin::Root.into(), @@ -136,8 +141,8 @@ runtime_benchmarks! { calculate_and_execute_sell_in_lbp { let c in 0..1; // if c == 1, calculate_sell_trade_amounts is executed - let asset_in = 1u32; - let asset_out = 2u32; + let asset_in = register_external_asset(b"FCA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_out = register_external_asset(b"FCB".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; let caller: AccountId = funded_account("caller", 7, &[asset_in, asset_out]); let seller: AccountId = funded_account("seller", 8, &[asset_in, asset_out]); @@ -169,8 +174,8 @@ runtime_benchmarks! { let c in 1..2; // number of times `calculate_buy_trade_amounts` is executed let b in 0..1; // if e == 1, buy is executed - let asset_in = 1u32; - let asset_out = 2u32; + let asset_in = register_external_asset(b"FCA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_out = register_external_asset(b"FCB".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; let caller: AccountId = funded_account("caller", 0, &[asset_in, asset_out]); let buyer: AccountId = funded_account("buyer", 1, &[asset_in, asset_out]); @@ -203,12 +208,13 @@ runtime_benchmarks! { // Calculates the weight of xyk set route. Used in the calculation to determine the weight of the overhead. set_route_for_xyk { - let asset_1 = 1u32; - let asset_2 = 3u32; - let asset_3 = 4u32; + let asset_1 = register_external_asset(b"FCA".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_2 = register_external_asset(b"FCB".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + let asset_3 = register_external_asset(b"FCC".to_vec()).map_err(|_| BenchmarkError::Stop("Failed to register asset"))?; + + let caller: AccountId = funded_account("caller", 0, &[asset_1, asset_2, asset_3]); + let buyer: AccountId = funded_account("buyer", 1, &[asset_1, asset_2, asset_3]); - let caller: AccountId = funded_account("caller", 0, &[asset_1, asset_2,asset_3]); - let buyer: AccountId = funded_account("buyer", 1, &[asset_1, asset_2,asset_3]); create_xyk_pool(asset_1, asset_2); create_xyk_pool(asset_1, asset_3); create_xyk_pool(asset_2, asset_3); @@ -251,63 +257,14 @@ runtime_benchmarks! { #[cfg(test)] mod tests { use super::*; - use crate::NativeExistentialDeposit; use orml_benchmarking::impl_benchmark_test_suite; use sp_runtime::BuildStorage; fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::::default() + frame_system::GenesisConfig::::default() .build_storage() - .unwrap(); - - pallet_asset_registry::GenesisConfig:: { - registered_assets: vec![ - ( - Some(1), - Some(b"LRNA".to_vec().try_into().unwrap()), - 1_000u128, - None, - None, - None, - true, - ), - ( - Some(2), - Some(b"DAI".to_vec().try_into().unwrap()), - 1_000u128, - None, - None, - None, - true, - ), - ( - Some(3), - Some(b"FCA".to_vec().try_into().unwrap()), - 1_000u128, - None, - None, - None, - true, - ), - ( - Some(4), - Some(b"FCB".to_vec().try_into().unwrap()), - 1_000u128, - None, - None, - None, - true, - ), - ], - native_asset_name: b"HDX".to_vec().try_into().unwrap(), - native_existential_deposit: NativeExistentialDeposit::get(), - native_symbol: b"HDX".to_vec().try_into().unwrap(), - native_decimals: 12, - } - .assimilate_storage(&mut t) - .unwrap(); - - sp_io::TestExternalities::new(t) + .unwrap() + .into() } impl_benchmark_test_suite!(new_test_ext(),); From 1b6c46545314d496e1a90c601e39eb9b3fb48f08 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 15 Feb 2024 12:25:17 +0100 Subject: [PATCH 89/93] fixed broken benchmarks --- node/src/chain_spec/local.rs | 4 +-- pallets/bonds/src/benchmarks.rs | 3 +- runtime/hydradx/src/assets.rs | 50 +++++++++++++++++++-------------- runtime/hydradx/src/lib.rs | 1 + 4 files changed, 34 insertions(+), 24 deletions(-) diff --git a/node/src/chain_spec/local.rs b/node/src/chain_spec/local.rs index d5f4fdb89..38246ddd4 100644 --- a/node/src/chain_spec/local.rs +++ b/node/src/chain_spec/local.rs @@ -88,7 +88,7 @@ pub fn parachain_config() -> Result { None, None, None, - false, + true, ), ( Some(2), @@ -97,7 +97,7 @@ pub fn parachain_config() -> Result { None, None, None, - false, + true, ), ], // accepted assets diff --git a/pallets/bonds/src/benchmarks.rs b/pallets/bonds/src/benchmarks.rs index 332e358ab..53f867a12 100644 --- a/pallets/bonds/src/benchmarks.rs +++ b/pallets/bonds/src/benchmarks.rs @@ -60,7 +60,8 @@ benchmarks! { let origin = T::IssueOrigin::try_successful_origin().unwrap(); let issuer = T::IssueOrigin::ensure_origin(origin).unwrap(); let amount: T::Balance = (200 * ONE).into(); - T::Currency::deposit(HDX, &issuer, amount)?; + //NOTE: bonds are insufficient so issuer must ED for it + T::Currency::deposit(HDX, &issuer, amount + (100 * ONE).into())?; let maturity = NOW + MONTH; diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 144f7c5a1..4e8899288 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -1030,6 +1030,8 @@ use pallet_currencies::fungibles::FungibleCurrencies; #[cfg(not(feature = "runtime-benchmarks"))] use hydradx_adapters::price::OraclePriceProviderUsingRoute; +#[cfg(feature = "runtime-benchmarks")] +use frame_support::storage::with_transaction; #[cfg(feature = "runtime-benchmarks")] use hydradx_traits::price::PriceProvider; #[cfg(feature = "runtime-benchmarks")] @@ -1039,6 +1041,7 @@ use pallet_referrals::{FeeDistribution, Level}; #[cfg(feature = "runtime-benchmarks")] use pallet_stableswap::BenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] +use sp_runtime::TransactionOutcome; #[cfg(feature = "runtime-benchmarks")] pub struct RegisterAsset(PhantomData); @@ -1050,16 +1053,19 @@ impl BenchmarkHelper for RegisterAsse .to_vec() .try_into() .map_err(|_| "BoundedConversionFailed")?; - AssetRegistry::register_sufficient_asset( - Some(asset_id), - Some(asset_name.clone()), - AssetKind::Token, - 1, - Some(asset_name), - Some(decimals), - None, - None, - )?; + + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_sufficient_asset( + Some(asset_id), + Some(asset_name.clone()), + AssetKind::Token, + 1, + Some(asset_name), + Some(decimals), + None, + None, + )) + })?; Ok(()) } @@ -1359,17 +1365,19 @@ impl RefBenchmarkHelper for ReferralsBenchmarkHelper { let asset_id: u32 = 1234u32; let asset_name: BoundedVec = asset_id.to_le_bytes().to_vec().try_into().unwrap(); - AssetRegistry::register_asset( - Some(asset_id), - Some(asset_name.clone()), - AssetKind::Token, - Some(1_000_000), - Some(asset_name), - Some(18), - None, - None, - true, - ) + with_transaction(|| { + TransactionOutcome::Commit(AssetRegistry::register_asset( + Some(asset_id), + Some(asset_name.clone()), + AssetKind::Token, + Some(1_000_000), + Some(asset_name), + Some(18), + None, + None, + true, + )) + }) .unwrap(); let native_price = FixedU128::from_inner(1201500000000000); diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index 55de5f3fe..9e1811ea8 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -621,6 +621,7 @@ impl_runtime_apis! { list_benchmark!(list, extra, pallet_ema_oracle, EmaOracle); list_benchmark!(list, extra, pallet_staking, Staking); list_benchmark!(list, extra, pallet_lbp, LBP); + list_benchmark!(list, extra, pallet_referrals, Referrals); list_benchmark!(list, extra, cumulus_pallet_xcmp_queue, XcmpQueue); list_benchmark!(list, extra, pallet_transaction_pause, TransactionPause); From a84d9808c221a36778abf7625c24a6ab9b1f6700 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 15 Feb 2024 14:42:13 +0100 Subject: [PATCH 90/93] rebenchmark everything --- runtime/hydradx/src/weights/balances.rs | 103 +++--- runtime/hydradx/src/weights/bonds.rs | 89 ++--- .../hydradx/src/weights/circuit_breaker.rs | 104 +++--- runtime/hydradx/src/weights/claims.rs | 39 +-- .../hydradx/src/weights/collator_selection.rs | 137 ++++---- runtime/hydradx/src/weights/council.rs | 259 +++++++-------- runtime/hydradx/src/weights/currencies.rs | 97 +++--- runtime/hydradx/src/weights/dca.rs | 42 ++- runtime/hydradx/src/weights/democracy.rs | 313 +++++++++--------- runtime/hydradx/src/weights/duster.rs | 67 ++-- runtime/hydradx/src/weights/ema_oracle.rs | 83 +++-- runtime/hydradx/src/weights/identity.rs | 305 +++++++++-------- runtime/hydradx/src/weights/lbp.rs | 178 +++++----- runtime/hydradx/src/weights/omnipool.rs | 192 ++++++----- runtime/hydradx/src/weights/omnipool_lm.rs | 161 +++++---- runtime/hydradx/src/weights/otc.rs | 129 ++++---- runtime/hydradx/src/weights/payment.rs | 34 +- runtime/hydradx/src/weights/preimage.rs | 150 ++++----- runtime/hydradx/src/weights/proxy.rs | 181 +++++----- runtime/hydradx/src/weights/referrals.rs | 46 ++- runtime/hydradx/src/weights/registry.rs | 143 ++++---- runtime/hydradx/src/weights/route_executor.rs | 107 +++--- runtime/hydradx/src/weights/scheduler.rs | 156 +++++---- runtime/hydradx/src/weights/stableswap.rs | 201 +++++------ runtime/hydradx/src/weights/staking.rs | 77 ++--- runtime/hydradx/src/weights/system.rs | 103 +++--- .../src/weights/technical_committee.rs | 261 +++++++-------- runtime/hydradx/src/weights/timestamp.rs | 49 ++- runtime/hydradx/src/weights/tokens.rs | 199 ++++++----- .../hydradx/src/weights/transaction_pause.rs | 57 ++-- runtime/hydradx/src/weights/treasury.rs | 97 +++--- runtime/hydradx/src/weights/utility.rs | 75 ++--- runtime/hydradx/src/weights/vesting.rs | 79 ++--- runtime/hydradx/src/weights/xcm.rs | 131 ++++---- runtime/hydradx/src/weights/xcmp_queue.rs | 49 ++- runtime/hydradx/src/weights/xyk.rs | 309 +++++++++++------ 36 files changed, 2448 insertions(+), 2354 deletions(-) diff --git a/runtime/hydradx/src/weights/balances.rs b/runtime/hydradx/src/weights/balances.rs index 6e7229980..82d13eb48 100644 --- a/runtime/hydradx/src/weights/balances.rs +++ b/runtime/hydradx/src/weights/balances.rs @@ -18,53 +18,46 @@ //! Autogenerated weights for `pallet_balances` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-balances +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_balances +// --output=./weights/balances.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/balances.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_balances::weights::WeightInfo; - -/// Weights for pallet_balances using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_balances`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_balances::WeightInfo for HydraWeight { /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_allow_death() -> Weight { // Proof Size summary in bytes: // Measured: `103` // Estimated: `6196` - // Minimum execution time: 99_306_000 picoseconds. - Weight::from_parts(99_852_000, 6196) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 95_388_000 picoseconds. + Weight::from_parts(96_245_000, 6196) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -72,10 +65,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 57_733_000 picoseconds. - Weight::from_parts(58_369_000, 3593) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 56_336_000 picoseconds. + Weight::from_parts(56_960_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -83,10 +76,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 23_571_000 picoseconds. - Weight::from_parts(24_090_000, 3593) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 23_156_000 picoseconds. + Weight::from_parts(23_520_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -94,10 +87,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 33_669_000 picoseconds. - Weight::from_parts(34_145_000, 3593) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 32_737_000 picoseconds. + Weight::from_parts(33_142_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `System::Account` (r:3 w:3) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -105,10 +98,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `206` // Estimated: `8799` - // Minimum execution time: 99_790_000 picoseconds. - Weight::from_parts(100_634_000, 8799) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 97_418_000 picoseconds. + Weight::from_parts(98_398_000, 8799) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -116,10 +109,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 71_626_000 picoseconds. - Weight::from_parts(72_046_000, 3593) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 70_382_000 picoseconds. + Weight::from_parts(71_293_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -127,24 +120,24 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 27_226_000 picoseconds. - Weight::from_parts(27_500_000, 3593) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 26_552_000 picoseconds. + Weight::from_parts(26_832_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `System::Account` (r:1000 w:1000) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `u` is `[1, 1000]`. - fn upgrade_accounts(u: u32) -> Weight { + fn upgrade_accounts(u: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + u * (136 ±0)` // Estimated: `990 + u * (2603 ±0)` - // Minimum execution time: 25_150_000 picoseconds. - Weight::from_parts(25_357_000, 990) - // Standard Error: 34_523 - .saturating_add(Weight::from_parts(19_216_979, 0).saturating_mul(u.into())) + // Minimum execution time: 24_327_000 picoseconds. + Weight::from_parts(24_625_000, 990) + // Standard Error: 18_294 + .saturating_add(Weight::from_parts(18_506_542, 0).saturating_mul(u.into())) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(u.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(u.into()))) .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/bonds.rs b/runtime/hydradx/src/weights/bonds.rs index 045ba325d..73b8867e0 100644 --- a/runtime/hydradx/src/weights/bonds.rs +++ b/runtime/hydradx/src/weights/bonds.rs @@ -18,73 +18,74 @@ //! Autogenerated weights for `pallet_bonds` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-bonds +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_bonds +// --output=./weights/bonds.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/bonds.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_bonds::weights::WeightInfo; - -/// Weights for pallet_bonds using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_bonds`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_bonds::WeightInfo for HydraWeight { /// Storage: `AssetRegistry::Assets` (r:1 w:1) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Bonds::BondIds` (r:1 w:1) /// Proof: `Bonds::BondIds` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `MaxEncodedLen`) /// Storage: `Timestamp::Now` (r:1 w:0) /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::NextAssetId` (r:1 w:1) /// Proof: `AssetRegistry::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::AssetIds` (r:1 w:1) + /// Proof: `AssetRegistry::AssetIds` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:3) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:1 w:1) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `Tokens::TotalIssuance` (r:1 w:1) - /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:1) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `Bonds::Bonds` (r:0 w:1) /// Proof: `Bonds::Bonds` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::AssetIds` (r:0 w:1) - /// Proof: `AssetRegistry::AssetIds` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) fn issue() -> Weight { // Proof Size summary in bytes: - // Measured: `1240` + // Measured: `1327` // Estimated: `8799` - // Minimum execution time: 208_163_000 picoseconds. - Weight::from_parts(209_241_000, 8799) - .saturating_add(T::DbWeight::get().reads(11_u64)) - .saturating_add(T::DbWeight::get().writes(10_u64)) + // Minimum execution time: 295_545_000 picoseconds. + Weight::from_parts(297_850_000, 8799) + .saturating_add(T::DbWeight::get().reads(16)) + .saturating_add(T::DbWeight::get().writes(12)) } /// Storage: `Bonds::Bonds` (r:1 w:0) /// Proof: `Bonds::Bonds` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `MaxEncodedLen`) @@ -93,20 +94,26 @@ impl WeightInfo for HydraWeight { /// Storage: `Tokens::Accounts` (r:1 w:1) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) + /// Storage: `System::Account` (r:3 w:3) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:0 w:1) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) fn redeem() -> Weight { // Proof Size summary in bytes: - // Measured: `1415` - // Estimated: `6196` - // Minimum execution time: 146_646_000 picoseconds. - Weight::from_parts(147_343_000, 6196) - .saturating_add(T::DbWeight::get().reads(7_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Measured: `1744` + // Estimated: `8799` + // Minimum execution time: 215_448_000 picoseconds. + Weight::from_parts(216_795_000, 8799) + .saturating_add(T::DbWeight::get().reads(12)) + .saturating_add(T::DbWeight::get().writes(7)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/circuit_breaker.rs b/runtime/hydradx/src/weights/circuit_breaker.rs index c3929949d..bb2901ac9 100644 --- a/runtime/hydradx/src/weights/circuit_breaker.rs +++ b/runtime/hydradx/src/weights/circuit_breaker.rs @@ -18,76 +18,69 @@ //! Autogenerated weights for `pallet_circuit_breaker` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-circuit-breaker +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_circuit_breaker +// --output=./weights/circuit_breaker.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/circuit_breaker.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_circuit_breaker::weights::WeightInfo; - -/// Weights for pallet_circuit_breaker using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_circuit_breaker`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_circuit_breaker::WeightInfo for HydraWeight { /// The range of component `n` is `[0, 400]`. /// The range of component `m` is `[0, 400]`. - fn on_finalize(n: u32, m: u32) -> Weight { + fn on_finalize(n: u32, m: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `105 + m * (113 ±0) + n * (56 ±0)` + // Measured: `81 + m * (113 ±0) + n * (56 ±0)` // Estimated: `0` - // Minimum execution time: 336_709_000 picoseconds. - Weight::from_parts(338_100_000, 0) - // Standard Error: 34_770 - .saturating_add(Weight::from_parts(304_235, 0).saturating_mul(n.into())) - // Standard Error: 34_770 - .saturating_add(Weight::from_parts(1_161_474, 0).saturating_mul(m.into())) + // Minimum execution time: 337_114_000 picoseconds. + Weight::from_parts(338_524_000, 0) + // Standard Error: 18_748 + .saturating_add(Weight::from_parts(304_800, 0).saturating_mul(n.into())) + // Standard Error: 18_748 + .saturating_add(Weight::from_parts(1_167_299, 0).saturating_mul(m.into())) } fn on_finalize_single_liquidity_limit_entry() -> Weight { // Proof Size summary in bytes: // Measured: `208` // Estimated: `0` - // Minimum execution time: 9_370_000 picoseconds. - Weight::from_parts(9_492_000, 0) + // Minimum execution time: 9_057_000 picoseconds. + Weight::from_parts(9_236_000, 0) } fn on_finalize_single_trade_limit_entry() -> Weight { // Proof Size summary in bytes: // Measured: `208` // Estimated: `0` - // Minimum execution time: 9_297_000 picoseconds. - Weight::from_parts(9_518_000, 0) + // Minimum execution time: 9_038_000 picoseconds. + Weight::from_parts(9_276_000, 0) } fn on_finalize_empty() -> Weight { // Proof Size summary in bytes: // Measured: `208` // Estimated: `0` - // Minimum execution time: 9_320_000 picoseconds. - Weight::from_parts(9_566_000, 0) + // Minimum execution time: 8_991_000 picoseconds. + Weight::from_parts(9_236_000, 0) } /// Storage: `CircuitBreaker::TradeVolumeLimitPerAsset` (r:0 w:1) /// Proof: `CircuitBreaker::TradeVolumeLimitPerAsset` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) @@ -95,8 +88,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_401_000 picoseconds. - Weight::from_parts(12_601_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 12_675_000 picoseconds. + Weight::from_parts(12_914_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `CircuitBreaker::LiquidityAddLimitPerAsset` (r:0 w:1) /// Proof: `CircuitBreaker::LiquidityAddLimitPerAsset` (`max_values`: None, `max_size`: Some(29), added: 2504, mode: `MaxEncodedLen`) @@ -104,8 +98,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_366_000 picoseconds. - Weight::from_parts(12_660_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 12_902_000 picoseconds. + Weight::from_parts(13_224_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `CircuitBreaker::LiquidityRemoveLimitPerAsset` (r:0 w:1) /// Proof: `CircuitBreaker::LiquidityRemoveLimitPerAsset` (`max_values`: None, `max_size`: Some(29), added: 2504, mode: `MaxEncodedLen`) @@ -113,8 +108,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_543_000 picoseconds. - Weight::from_parts(12_729_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 12_583_000 picoseconds. + Weight::from_parts(12_901_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `CircuitBreaker::LiquidityAddLimitPerAsset` (r:1 w:0) /// Proof: `CircuitBreaker::LiquidityAddLimitPerAsset` (`max_values`: None, `max_size`: Some(29), added: 2504, mode: `MaxEncodedLen`) @@ -128,10 +124,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `262` // Estimated: `3517` - // Minimum execution time: 20_930_000 picoseconds. - Weight::from_parts(21_398_000, 3517) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 20_836_000 picoseconds. + Weight::from_parts(21_079_000, 3517) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `CircuitBreaker::LiquidityAddLimitPerAsset` (r:1 w:0) /// Proof: `CircuitBreaker::LiquidityAddLimitPerAsset` (`max_values`: None, `max_size`: Some(29), added: 2504, mode: `MaxEncodedLen`) @@ -145,10 +141,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `208` // Estimated: `3517` - // Minimum execution time: 17_808_000 picoseconds. - Weight::from_parts(18_193_000, 3517) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 17_939_000 picoseconds. + Weight::from_parts(18_095_000, 3517) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `CircuitBreaker::AllowedTradeVolumeLimitPerAsset` (r:2 w:2) /// Proof: `CircuitBreaker::AllowedTradeVolumeLimitPerAsset` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) @@ -158,9 +154,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `208` // Estimated: `6076` - // Minimum execution time: 18_243_000 picoseconds. - Weight::from_parts(18_729_000, 6076) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 18_569_000 picoseconds. + Weight::from_parts(18_816_000, 6076) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/claims.rs b/runtime/hydradx/src/weights/claims.rs index 631a69ff6..e32c1935b 100644 --- a/runtime/hydradx/src/weights/claims.rs +++ b/runtime/hydradx/src/weights/claims.rs @@ -18,42 +18,37 @@ //! Autogenerated weights for `pallet_claims` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-claims +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_claims +// --output=./weights/claims.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/claims.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_claims::weights::WeightInfo; -/// Weights for pallet_claims using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_claims`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `Claims::Claims` (r:1 w:1) /// Proof: `Claims::Claims` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) @@ -63,9 +58,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `382` // Estimated: `3593` - // Minimum execution time: 82_736_000 picoseconds. - Weight::from_parts(83_275_000, 3593) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 82_475_000 picoseconds. + Weight::from_parts(82_992_000, 3593) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) } } diff --git a/runtime/hydradx/src/weights/collator_selection.rs b/runtime/hydradx/src/weights/collator_selection.rs index e1f72a306..efb4407a0 100644 --- a/runtime/hydradx/src/weights/collator_selection.rs +++ b/runtime/hydradx/src/weights/collator_selection.rs @@ -18,7 +18,7 @@ //! Autogenerated weights for `pallet_collator_selection` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 @@ -33,8 +33,8 @@ // --wasm-execution=compiled // --heap-pages=4096 // --template=.maintain/pallet-weight-template-no-back.hbs -// --pallet=pallet-collator-selection -// --output=weights-1.1.0/collator-selection.rs +// --pallet=pallet_collator_selection +// --output=./weights/collator_selection.rs // --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] @@ -42,17 +42,12 @@ #![allow(unused_imports)] #![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; - -use pallet_collator_selection::weights::WeightInfo; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; +/// Weight functions for `pallet_collator_selection`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_collator_selection::WeightInfo for HydraWeight { /// Storage: `Session::NextKeys` (r:50 w:0) /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `CollatorSelection::Invulnerables` (r:0 w:1) @@ -62,10 +57,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `205 + b * (79 ±0)` // Estimated: `1194 + b * (2554 ±0)` - // Minimum execution time: 20_455_000 picoseconds. - Weight::from_parts(19_594_151, 1194) - // Standard Error: 8_370 - .saturating_add(Weight::from_parts(3_470_262, 0).saturating_mul(b.into())) + // Minimum execution time: 20_628_000 picoseconds. + Weight::from_parts(19_568_734, 1194) + // Standard Error: 7_340 + .saturating_add(Weight::from_parts(3_478_925, 0).saturating_mul(b.into())) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(b.into()))) .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(Weight::from_parts(0, 2554).saturating_mul(b.into())) @@ -75,39 +70,39 @@ impl WeightInfo for HydraWeight { /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(1601), added: 2096, mode: `MaxEncodedLen`) /// Storage: `CollatorSelection::Candidates` (r:1 w:1) - /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(193), added: 688, mode: `MaxEncodedLen`) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(2401), added: 2896, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `b` is `[1, 49]`. - /// The range of component `c` is `[1, 3]`. + /// The range of component `c` is `[1, 49]`. fn add_invulnerable(b: u32, c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `835 + b * (44 ±0) + c * (48 ±0)` - // Estimated: `4283 + b * (45 ±0) + c * (56 ±2)` - // Minimum execution time: 58_595_000 picoseconds. - Weight::from_parts(58_147_234, 4283) - // Standard Error: 2_112 - .saturating_add(Weight::from_parts(110_403, 0).saturating_mul(b.into())) - // Standard Error: 41_169 - .saturating_add(Weight::from_parts(341_824, 0).saturating_mul(c.into())) + // Measured: `1444 + b * (32 ±0) + c * (48 ±0)` + // Estimated: `4909 + b * (32 ±0) + c * (48 ±0)` + // Minimum execution time: 62_617_000 picoseconds. + Weight::from_parts(62_633_538, 4909) + // Standard Error: 1_299 + .saturating_add(Weight::from_parts(19_587, 0).saturating_mul(b.into())) + // Standard Error: 1_299 + .saturating_add(Weight::from_parts(43_332, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) - .saturating_add(Weight::from_parts(0, 45).saturating_mul(b.into())) - .saturating_add(Weight::from_parts(0, 56).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(0, 32).saturating_mul(b.into())) + .saturating_add(Weight::from_parts(0, 48).saturating_mul(c.into())) } /// Storage: `CollatorSelection::Candidates` (r:1 w:0) - /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(193), added: 688, mode: `MaxEncodedLen`) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(2401), added: 2896, mode: `MaxEncodedLen`) /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(1601), added: 2096, mode: `MaxEncodedLen`) /// The range of component `b` is `[5, 50]`. fn remove_invulnerable(b: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `285 + b * (32 ±0)` - // Estimated: `3086` - // Minimum execution time: 22_755_000 picoseconds. - Weight::from_parts(23_093_354, 3086) - // Standard Error: 1_094 - .saturating_add(Weight::from_parts(46_083, 0).saturating_mul(b.into())) + // Estimated: `3886` + // Minimum execution time: 22_662_000 picoseconds. + Weight::from_parts(23_030_075, 3886) + // Standard Error: 939 + .saturating_add(Weight::from_parts(41_972, 0).saturating_mul(b.into())) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -117,8 +112,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 11_217_000 picoseconds. - Weight::from_parts(11_385_000, 0) + // Minimum execution time: 11_095_000 picoseconds. + Weight::from_parts(11_241_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `CollatorSelection::CandidacyBond` (r:0 w:1) @@ -127,12 +122,12 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 11_244_000 picoseconds. - Weight::from_parts(11_602_000, 0) + // Minimum execution time: 11_004_000 picoseconds. + Weight::from_parts(11_197_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `CollatorSelection::Candidates` (r:1 w:1) - /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(193), added: 688, mode: `MaxEncodedLen`) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(2401), added: 2896, mode: `MaxEncodedLen`) /// Storage: `CollatorSelection::DesiredCandidates` (r:1 w:0) /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) @@ -143,34 +138,34 @@ impl WeightInfo for HydraWeight { /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) - /// The range of component `c` is `[1, 3]`. + /// The range of component `c` is `[1, 49]`. fn register_as_candidate(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `700 + c * (82 ±0)` - // Estimated: `4179 + c * (71 ±0)` - // Minimum execution time: 55_650_000 picoseconds. - Weight::from_parts(56_276_004, 4179) - // Standard Error: 19_512 - .saturating_add(Weight::from_parts(185_775, 0).saturating_mul(c.into())) + // Measured: `730 + c * (60 ±0)` + // Estimated: `4213 + c * (59 ±0)` + // Minimum execution time: 55_657_000 picoseconds. + Weight::from_parts(57_084_118, 4213) + // Standard Error: 2_209 + .saturating_add(Weight::from_parts(101_671, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) - .saturating_add(Weight::from_parts(0, 71).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(0, 59).saturating_mul(c.into())) } /// Storage: `CollatorSelection::Candidates` (r:1 w:1) - /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(193), added: 688, mode: `MaxEncodedLen`) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(2401), added: 2896, mode: `MaxEncodedLen`) /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(1601), added: 2096, mode: `MaxEncodedLen`) /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) - /// The range of component `c` is `[3, 4]`. + /// The range of component `c` is `[3, 50]`. fn leave_intent(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `445 + c * (82 ±0)` - // Estimated: `3086` - // Minimum execution time: 45_906_000 picoseconds. - Weight::from_parts(45_386_687, 3086) - // Standard Error: 27_981 - .saturating_add(Weight::from_parts(387_687, 0).saturating_mul(c.into())) + // Measured: `556 + c * (50 ±0)` + // Estimated: `3886` + // Minimum execution time: 46_120_000 picoseconds. + Weight::from_parts(46_397_357, 3886) + // Standard Error: 1_574 + .saturating_add(Weight::from_parts(90_362, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -184,36 +179,36 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `192` // Estimated: `6196` - // Minimum execution time: 64_565_000 picoseconds. - Weight::from_parts(65_177_000, 6196) + // Minimum execution time: 63_730_000 picoseconds. + Weight::from_parts(64_351_000, 6196) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `CollatorSelection::Candidates` (r:1 w:0) - /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(193), added: 688, mode: `MaxEncodedLen`) - /// Storage: `CollatorSelection::LastAuthoredBlock` (r:4 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(2401), added: 2896, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:50 w:0) /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(1601), added: 2096, mode: `MaxEncodedLen`) /// Storage: `System::BlockWeight` (r:1 w:1) /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) + /// Storage: `System::Account` (r:44 w:44) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// The range of component `r` is `[1, 4]`. - /// The range of component `c` is `[1, 4]`. + /// The range of component `r` is `[1, 50]`. + /// The range of component `c` is `[1, 50]`. fn new_session(r: u32, c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `764 + c * (101 ±0)` - // Estimated: `3593 + c * (2519 ±0) + r * (1302 ±64)` - // Minimum execution time: 28_492_000 picoseconds. - Weight::from_parts(43_856_926, 3593) - // Standard Error: 1_235_538 - .saturating_add(Weight::from_parts(17_366_925, 0).saturating_mul(c.into())) + // Measured: `1276 + c * (98 ±0) + r * (116 ±0)` + // Estimated: `3886 + c * (2519 ±0) + r * (2603 ±0)` + // Minimum execution time: 28_836_000 picoseconds. + Weight::from_parts(29_061_000, 3886) + // Standard Error: 714_438 + .saturating_add(Weight::from_parts(16_538_136, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) - .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) .saturating_add(Weight::from_parts(0, 2519).saturating_mul(c.into())) - .saturating_add(Weight::from_parts(0, 1302).saturating_mul(r.into())) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(r.into())) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/council.rs b/runtime/hydradx/src/weights/council.rs index aa07c42de..caa01468f 100644 --- a/runtime/hydradx/src/weights/council.rs +++ b/runtime/hydradx/src/weights/council.rs @@ -18,42 +18,37 @@ //! Autogenerated weights for `council` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=council +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=council +// --output=./weights/council.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/council.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_collective::WeightInfo; -/// Weights for council using the hydraDX node and recommended hardware. +/// Weight functions for `council`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `Council::Members` (r:1 w:1) /// Proof: `Council::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) @@ -66,40 +61,38 @@ impl WeightInfo for HydraWeight { /// The range of component `m` is `[0, 13]`. /// The range of component `n` is `[0, 13]`. /// The range of component `p` is `[0, 30]`. - fn set_members(m: u32, _n: u32, p: u32) -> Weight { + fn set_members(m: u32, _n: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + m * (992 ±0) + p * (405 ±0)` - // Estimated: `21811 + m * (615 ±25) + p * (2394 ±10)` - // Minimum execution time: 13_593_000 picoseconds. - Weight::from_parts(13_892_000, 21811) - // Standard Error: 392_175 - .saturating_add(Weight::from_parts(4_636_136, 0).saturating_mul(m.into())) - // Standard Error: 170_899 - .saturating_add(Weight::from_parts(3_787_560, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(m.into()))) + // Estimated: `10288 + m * (587 ±12) + p * (2585 ±5)` + // Minimum execution time: 13_811_000 picoseconds. + Weight::from_parts(13_892_000, 10288) + // Standard Error: 175_369 + .saturating_add(Weight::from_parts(2_946_800, 0).saturating_mul(m.into())) + // Standard Error: 76_976 + .saturating_add(Weight::from_parts(4_083_732, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) - .saturating_add(T::DbWeight::get().writes(2_u64)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(m.into()))) + .saturating_add(T::DbWeight::get().writes(2)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) - .saturating_add(Weight::from_parts(0, 615).saturating_mul(m.into())) - .saturating_add(Weight::from_parts(0, 2394).saturating_mul(p.into())) + .saturating_add(Weight::from_parts(0, 587).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 2585).saturating_mul(p.into())) } /// Storage: `Council::Members` (r:1 w:0) /// Proof: `Council::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// The range of component `b` is `[2, 1024]`. /// The range of component `m` is `[1, 13]`. - fn execute(b: u32, m: u32) -> Weight { + fn execute(b: u32, m: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `104 + m * (32 ±0)` - // Estimated: `1588 + m * (32 ±0)` - // Minimum execution time: 21_886_000 picoseconds. - Weight::from_parts(21_919_709, 1588) - // Standard Error: 49 - .saturating_add(Weight::from_parts(1_347, 0).saturating_mul(b.into())) - // Standard Error: 4_183 - .saturating_add(Weight::from_parts(26_796, 0).saturating_mul(m.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) + // Estimated: `1589 + m * (32 ±0)` + // Minimum execution time: 21_838_000 picoseconds. + Weight::from_parts(21_813_079, 1589) + // Standard Error: 23 + .saturating_add(Weight::from_parts(1_429, 0).saturating_mul(b.into())) + // Standard Error: 1_981 + .saturating_add(Weight::from_parts(26_339, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) } /// Storage: `Council::Members` (r:1 w:0) @@ -108,17 +101,17 @@ impl WeightInfo for HydraWeight { /// Proof: `Council::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `b` is `[2, 1024]`. /// The range of component `m` is `[1, 13]`. - fn propose_execute(b: u32, m: u32) -> Weight { + fn propose_execute(b: u32, m: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `104 + m * (32 ±0)` - // Estimated: `3568 + m * (32 ±0)` - // Minimum execution time: 25_705_000 picoseconds. - Weight::from_parts(25_390_343, 3568) - // Standard Error: 58 - .saturating_add(Weight::from_parts(1_400, 0).saturating_mul(b.into())) - // Standard Error: 4_956 - .saturating_add(Weight::from_parts(39_729, 0).saturating_mul(m.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) + // Estimated: `3569 + m * (32 ±0)` + // Minimum execution time: 25_493_000 picoseconds. + Weight::from_parts(25_297_365, 3569) + // Standard Error: 28 + .saturating_add(Weight::from_parts(1_433, 0).saturating_mul(b.into())) + // Standard Error: 2_368 + .saturating_add(Weight::from_parts(52_183, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) } /// Storage: `Council::Members` (r:1 w:0) @@ -134,36 +127,36 @@ impl WeightInfo for HydraWeight { /// The range of component `b` is `[2, 1024]`. /// The range of component `m` is `[2, 13]`. /// The range of component `p` is `[1, 30]`. - fn propose_proposed(b: u32, m: u32, p: u32) -> Weight { + fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `187 + m * (32 ±0) + p * (49 ±0)` - // Estimated: `3617 + m * (33 ±0) + p * (51 ±0)` - // Minimum execution time: 32_994_000 picoseconds. - Weight::from_parts(32_250_127, 3617) - // Standard Error: 206 - .saturating_add(Weight::from_parts(2_216, 0).saturating_mul(b.into())) - // Standard Error: 7_213 - .saturating_add(Weight::from_parts(339_379, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Measured: `269 + m * (32 ±0) + p * (46 ±0)` + // Estimated: `3676 + m * (33 ±0) + p * (48 ±0)` + // Minimum execution time: 32_929_000 picoseconds. + Weight::from_parts(33_435_771, 3676) + // Standard Error: 121 + .saturating_add(Weight::from_parts(2_403, 0).saturating_mul(b.into())) + // Standard Error: 4_207 + .saturating_add(Weight::from_parts(303_367, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) .saturating_add(Weight::from_parts(0, 33).saturating_mul(m.into())) - .saturating_add(Weight::from_parts(0, 51).saturating_mul(p.into())) + .saturating_add(Weight::from_parts(0, 48).saturating_mul(p.into())) } /// Storage: `Council::Members` (r:1 w:0) /// Proof: `Council::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `Council::Voting` (r:1 w:1) /// Proof: `Council::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `m` is `[5, 13]`. - fn vote(m: u32) -> Weight { + fn vote(m: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `638 + m * (64 ±0)` // Estimated: `4103 + m * (64 ±0)` - // Minimum execution time: 26_864_000 picoseconds. - Weight::from_parts(26_990_860, 4103) - // Standard Error: 5_236 - .saturating_add(Weight::from_parts(51_000, 0).saturating_mul(m.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 26_460_000 picoseconds. + Weight::from_parts(26_812_332, 4103) + // Standard Error: 3_093 + .saturating_add(Weight::from_parts(29_350, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) } /// Storage: `Council::Voting` (r:1 w:1) @@ -176,20 +169,20 @@ impl WeightInfo for HydraWeight { /// Proof: `Council::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `m` is `[4, 13]`. /// The range of component `p` is `[1, 30]`. - fn close_early_disapproved(m: u32, p: u32) -> Weight { + fn close_early_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `208 + m * (64 ±0) + p * (46 ±0)` - // Estimated: `3673 + m * (69 ±1) + p * (45 ±0)` - // Minimum execution time: 34_511_000 picoseconds. - Weight::from_parts(34_588_685, 3673) - // Standard Error: 14_766 - .saturating_add(Weight::from_parts(54_177, 0).saturating_mul(m.into())) - // Standard Error: 4_664 - .saturating_add(Weight::from_parts(280_182, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) - .saturating_add(Weight::from_parts(0, 69).saturating_mul(m.into())) - .saturating_add(Weight::from_parts(0, 45).saturating_mul(p.into())) + // Measured: `298 + m * (64 ±0) + p * (43 ±0)` + // Estimated: `3710 + m * (70 ±0) + p * (44 ±0)` + // Minimum execution time: 34_584_000 picoseconds. + Weight::from_parts(34_586_760, 3710) + // Standard Error: 9_925 + .saturating_add(Weight::from_parts(93_668, 0).saturating_mul(m.into())) + // Standard Error: 3_040 + .saturating_add(Weight::from_parts(263_683, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 70).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 44).saturating_mul(p.into())) } /// Storage: `Council::Voting` (r:1 w:1) /// Proof: `Council::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -202,23 +195,23 @@ impl WeightInfo for HydraWeight { /// The range of component `b` is `[2, 1024]`. /// The range of component `m` is `[4, 13]`. /// The range of component `p` is `[1, 30]`. - fn close_early_approved(b: u32, m: u32, p: u32) -> Weight { + fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `305 + m * (64 ±0) + p * (59 ±0)` - // Estimated: `3683 + b * (1 ±0) + m * (71 ±2) + p * (61 ±0)` - // Minimum execution time: 49_998_000 picoseconds. - Weight::from_parts(48_993_560, 3683) - // Standard Error: 191 - .saturating_add(Weight::from_parts(1_582, 0).saturating_mul(b.into())) - // Standard Error: 21_188 - .saturating_add(Weight::from_parts(44_398, 0).saturating_mul(m.into())) - // Standard Error: 6_705 - .saturating_add(Weight::from_parts(306_716, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Measured: `543 + m * (64 ±0) + p * (56 ±0)` + // Estimated: `3803 + b * (1 ±0) + m * (73 ±1) + p * (58 ±0)` + // Minimum execution time: 49_680_000 picoseconds. + Weight::from_parts(50_379_903, 3803) + // Standard Error: 120 + .saturating_add(Weight::from_parts(589, 0).saturating_mul(b.into())) + // Standard Error: 13_657 + .saturating_add(Weight::from_parts(65_319, 0).saturating_mul(m.into())) + // Standard Error: 4_179 + .saturating_add(Weight::from_parts(296_427, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(b.into())) - .saturating_add(Weight::from_parts(0, 71).saturating_mul(m.into())) - .saturating_add(Weight::from_parts(0, 61).saturating_mul(p.into())) + .saturating_add(Weight::from_parts(0, 73).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 58).saturating_mul(p.into())) } /// Storage: `Council::Voting` (r:1 w:1) /// Proof: `Council::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -232,20 +225,20 @@ impl WeightInfo for HydraWeight { /// Proof: `Council::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `m` is `[4, 13]`. /// The range of component `p` is `[1, 30]`. - fn close_disapproved(m: u32, p: u32) -> Weight { + fn close_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `228 + m * (64 ±0) + p * (46 ±0)` - // Estimated: `3693 + m * (69 ±1) + p * (45 ±0)` - // Minimum execution time: 37_803_000 picoseconds. - Weight::from_parts(37_595_157, 3693) - // Standard Error: 15_571 - .saturating_add(Weight::from_parts(76_506, 0).saturating_mul(m.into())) - // Standard Error: 4_918 - .saturating_add(Weight::from_parts(273_488, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) - .saturating_add(Weight::from_parts(0, 69).saturating_mul(m.into())) - .saturating_add(Weight::from_parts(0, 45).saturating_mul(p.into())) + // Measured: `318 + m * (64 ±0) + p * (43 ±0)` + // Estimated: `3730 + m * (70 ±0) + p * (44 ±0)` + // Minimum execution time: 37_700_000 picoseconds. + Weight::from_parts(38_156_308, 3730) + // Standard Error: 10_153 + .saturating_add(Weight::from_parts(60_234, 0).saturating_mul(m.into())) + // Standard Error: 3_109 + .saturating_add(Weight::from_parts(263_287, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 70).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 44).saturating_mul(p.into())) } /// Storage: `Council::Voting` (r:1 w:1) /// Proof: `Council::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -260,23 +253,23 @@ impl WeightInfo for HydraWeight { /// The range of component `b` is `[2, 1024]`. /// The range of component `m` is `[4, 13]`. /// The range of component `p` is `[1, 30]`. - fn close_approved(b: u32, m: u32, p: u32) -> Weight { + fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `325 + m * (64 ±0) + p * (59 ±0)` - // Estimated: `3703 + b * (1 ±0) + m * (71 ±2) + p * (61 ±0)` - // Minimum execution time: 52_723_000 picoseconds. - Weight::from_parts(52_530_548, 3703) - // Standard Error: 221 - .saturating_add(Weight::from_parts(1_271, 0).saturating_mul(b.into())) - // Standard Error: 24_430 - .saturating_add(Weight::from_parts(29_682, 0).saturating_mul(m.into())) - // Standard Error: 7_731 - .saturating_add(Weight::from_parts(308_096, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Measured: `563 + m * (64 ±0) + p * (56 ±0)` + // Estimated: `3823 + b * (1 ±0) + m * (73 ±1) + p * (58 ±0)` + // Minimum execution time: 52_927_000 picoseconds. + Weight::from_parts(54_289_519, 3823) + // Standard Error: 189 + .saturating_add(Weight::from_parts(215, 0).saturating_mul(b.into())) + // Standard Error: 21_474 + .saturating_add(Weight::from_parts(60_622, 0).saturating_mul(m.into())) + // Standard Error: 6_571 + .saturating_add(Weight::from_parts(292_243, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(b.into())) - .saturating_add(Weight::from_parts(0, 71).saturating_mul(m.into())) - .saturating_add(Weight::from_parts(0, 61).saturating_mul(p.into())) + .saturating_add(Weight::from_parts(0, 73).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 58).saturating_mul(p.into())) } /// Storage: `Council::Proposals` (r:1 w:1) /// Proof: `Council::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) @@ -285,16 +278,16 @@ impl WeightInfo for HydraWeight { /// Storage: `Council::ProposalOf` (r:0 w:1) /// Proof: `Council::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `p` is `[1, 30]`. - fn disapprove_proposal(p: u32) -> Weight { + fn disapprove_proposal(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `260 + p * (32 ±0)` - // Estimated: `1744 + p * (32 ±0)` - // Minimum execution time: 22_405_000 picoseconds. - Weight::from_parts(23_004_470, 1744) - // Standard Error: 5_058 - .saturating_add(Weight::from_parts(217_141, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Estimated: `1745 + p * (32 ±0)` + // Minimum execution time: 22_476_000 picoseconds. + Weight::from_parts(23_113_774, 1745) + // Standard Error: 2_083 + .saturating_add(Weight::from_parts(201_829, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(3)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(p.into())) } } diff --git a/runtime/hydradx/src/weights/currencies.rs b/runtime/hydradx/src/weights/currencies.rs index 370d11e43..429c4d4cd 100644 --- a/runtime/hydradx/src/weights/currencies.rs +++ b/runtime/hydradx/src/weights/currencies.rs @@ -18,47 +18,44 @@ //! Autogenerated weights for `pallet_currencies` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-currencies +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet-currencies +// --output=./weights/currencies.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/currencies.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +#![allow(missing_docs)] -use pallet_currencies::WeightInfo; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -/// Weights for pallet_currencies using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_currencies`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_currencies::WeightInfo for HydraWeight { + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:2 w:2) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:1) @@ -67,28 +64,30 @@ impl WeightInfo for HydraWeight { /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) fn transfer_non_native_currency() -> Weight { // Proof Size summary in bytes: - // Measured: `2335` + // Measured: `2513` // Estimated: `6156` - // Minimum execution time: 96_394_000 picoseconds. - Weight::from_parts(96_942_000, 6156) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Minimum execution time: 108_145_000 picoseconds. + Weight::from_parts(109_086_000, 6156) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_native_currency() -> Weight { // Proof Size summary in bytes: - // Measured: `1668` + // Measured: `1672` // Estimated: `3593` - // Minimum execution time: 92_953_000 picoseconds. - Weight::from_parts(94_336_000, 3593) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 89_180_000 picoseconds. + Weight::from_parts(89_986_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:1 w:1) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) @@ -99,33 +98,33 @@ impl WeightInfo for HydraWeight { /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) fn update_balance_non_native_currency() -> Weight { // Proof Size summary in bytes: - // Measured: `2127` + // Measured: `2143` // Estimated: `3593` - // Minimum execution time: 73_636_000 picoseconds. - Weight::from_parts(74_177_000, 3593) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 78_116_000 picoseconds. + Weight::from_parts(78_984_000, 3593) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn update_balance_native_currency_creating() -> Weight { // Proof Size summary in bytes: - // Measured: `1528` + // Measured: `1532` // Estimated: `3593` - // Minimum execution time: 54_370_000 picoseconds. - Weight::from_parts(55_148_000, 3593) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 52_733_000 picoseconds. + Weight::from_parts(53_610_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn update_balance_native_currency_killing() -> Weight { // Proof Size summary in bytes: - // Measured: `1616` + // Measured: `1620` // Estimated: `3593` - // Minimum execution time: 54_487_000 picoseconds. - Weight::from_parts(55_170_000, 3593) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 52_641_000 picoseconds. + Weight::from_parts(53_186_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/dca.rs b/runtime/hydradx/src/weights/dca.rs index 5a8715eac..143e19da8 100644 --- a/runtime/hydradx/src/weights/dca.rs +++ b/runtime/hydradx/src/weights/dca.rs @@ -18,7 +18,7 @@ //! Autogenerated weights for `pallet_dca` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-27, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 @@ -33,26 +33,22 @@ // --wasm-execution=compiled // --heap-pages=4096 // --template=.maintain/pallet-weight-template-no-back.hbs -// --pallet=pallet-dca -// --output=weights-1.1.0/dca.rs +// --pallet=pallet_dca +// --output=./weights/dca.rs // --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_dca::weights::WeightInfo; -/// Weights for pallet_dca using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_dca`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `DCA::ScheduleIdsPerBlock` (r:12 w:2) /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(101), added: 2576, mode: `MaxEncodedLen`) @@ -70,8 +66,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `54411` // Estimated: `31902` - // Minimum execution time: 244_530_000 picoseconds. - Weight::from_parts(249_044_000, 31902) + // Minimum execution time: 237_105_000 picoseconds. + Weight::from_parts(240_959_000, 31902) .saturating_add(T::DbWeight::get().reads(17)) .saturating_add(T::DbWeight::get().writes(7)) } @@ -91,8 +87,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `54411` // Estimated: `31902` - // Minimum execution time: 244_929_000 picoseconds. - Weight::from_parts(249_576_000, 31902) + // Minimum execution time: 238_379_000 picoseconds. + Weight::from_parts(241_004_000, 31902) .saturating_add(T::DbWeight::get().reads(17)) .saturating_add(T::DbWeight::get().writes(7)) } @@ -102,8 +98,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `1075` // Estimated: `3566` - // Minimum execution time: 17_904_000 picoseconds. - Weight::from_parts(18_177_000, 3566) + // Minimum execution time: 17_306_000 picoseconds. + Weight::from_parts(17_642_000, 3566) .saturating_add(T::DbWeight::get().reads(1)) } /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) @@ -117,7 +113,7 @@ impl WeightInfo for HydraWeight { /// Storage: `Tokens::Accounts` (r:1 w:1) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `DCA::ScheduleIdsPerBlock` (r:11 w:1) /// Proof: `DCA::ScheduleIdsPerBlock` (`max_values`: None, `max_size`: Some(101), added: 2576, mode: `MaxEncodedLen`) /// Storage: `DCA::RetriesOnError` (r:0 w:1) @@ -130,10 +126,10 @@ impl WeightInfo for HydraWeight { /// Proof: `DCA::RemainingAmounts` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) fn schedule() -> Weight { // Proof Size summary in bytes: - // Measured: `52577` + // Measured: `52552` // Estimated: `29326` - // Minimum execution time: 175_288_000 picoseconds. - Weight::from_parts(178_961_000, 29326) + // Minimum execution time: 174_494_000 picoseconds. + Weight::from_parts(176_197_000, 29326) .saturating_add(T::DbWeight::get().reads(17)) .saturating_add(T::DbWeight::get().writes(8)) } @@ -155,8 +151,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `2526` // Estimated: `4714` - // Minimum execution time: 82_404_000 picoseconds. - Weight::from_parts(83_099_000, 4714) + // Minimum execution time: 80_303_000 picoseconds. + Weight::from_parts(81_183_000, 4714) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(7)) } diff --git a/runtime/hydradx/src/weights/democracy.rs b/runtime/hydradx/src/weights/democracy.rs index b0d2327de..da99aec3c 100644 --- a/runtime/hydradx/src/weights/democracy.rs +++ b/runtime/hydradx/src/weights/democracy.rs @@ -1,5 +1,4 @@ // This file is part of HydraDX. -// This file is part of HydraDX. // Copyright (C) 2020-2023 Intergalactic, Limited (GIB). // SPDX-License-Identifier: Apache-2.0 @@ -19,43 +18,36 @@ //! Autogenerated weights for `pallet_democracy` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-democracy +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_democracy +// --output=./weights/democracy.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/democracy.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_democracy::weights::WeightInfo; - -/// Weights for pallet_democracy using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_democracy`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_democracy::WeightInfo for HydraWeight { /// Storage: `Democracy::PublicPropCount` (r:1 w:1) /// Proof: `Democracy::PublicPropCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Democracy::PublicProps` (r:1 w:1) @@ -68,10 +60,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `4688` // Estimated: `18187` - // Minimum execution time: 52_594_000 picoseconds. - Weight::from_parts(53_207_000, 18187) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 52_817_000 picoseconds. + Weight::from_parts(53_361_000, 18187) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `Democracy::DepositOf` (r:1 w:1) /// Proof: `Democracy::DepositOf` (`max_values`: None, `max_size`: Some(3230), added: 5705, mode: `MaxEncodedLen`) @@ -79,10 +71,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `3443` // Estimated: `6695` - // Minimum execution time: 47_180_000 picoseconds. - Weight::from_parts(47_748_000, 6695) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 47_312_000 picoseconds. + Weight::from_parts(48_028_000, 6695) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Democracy::ReferendumInfoOf` (r:100 w:1) /// Proof: `Democracy::ReferendumInfoOf` (`max_values`: None, `max_size`: Some(201), added: 2676, mode: `MaxEncodedLen`) @@ -102,10 +94,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `15343` // Estimated: `268590` - // Minimum execution time: 452_520_000 picoseconds. - Weight::from_parts(456_752_000, 268590) - .saturating_add(T::DbWeight::get().reads(107_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Minimum execution time: 457_000_000 picoseconds. + Weight::from_parts(463_662_000, 268590) + .saturating_add(T::DbWeight::get().reads(107)) + .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `Democracy::ReferendumInfoOf` (r:100 w:1) /// Proof: `Democracy::ReferendumInfoOf` (`max_values`: None, `max_size`: Some(201), added: 2676, mode: `MaxEncodedLen`) @@ -125,10 +117,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `15365` // Estimated: `268590` - // Minimum execution time: 451_312_000 picoseconds. - Weight::from_parts(457_827_000, 268590) - .saturating_add(T::DbWeight::get().reads(107_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Minimum execution time: 458_732_000 picoseconds. + Weight::from_parts(462_786_000, 268590) + .saturating_add(T::DbWeight::get().reads(107)) + .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `Democracy::ReferendumInfoOf` (r:1 w:1) /// Proof: `Democracy::ReferendumInfoOf` (`max_values`: None, `max_size`: Some(201), added: 2676, mode: `MaxEncodedLen`) @@ -140,10 +132,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `249` // Estimated: `3666` - // Minimum execution time: 35_636_000 picoseconds. - Weight::from_parts(36_070_000, 3666) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 35_202_000 picoseconds. + Weight::from_parts(35_727_000, 3666) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `Democracy::PublicProps` (r:1 w:1) /// Proof: `Democracy::PublicProps` (`max_values`: Some(1), `max_size`: Some(16702), added: 17197, mode: `MaxEncodedLen`) @@ -163,10 +155,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `6191` // Estimated: `18187` - // Minimum execution time: 132_102_000 picoseconds. - Weight::from_parts(133_131_000, 18187) - .saturating_add(T::DbWeight::get().reads(9_u64)) - .saturating_add(T::DbWeight::get().writes(8_u64)) + // Minimum execution time: 133_106_000 picoseconds. + Weight::from_parts(134_384_000, 18187) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(8)) } /// Storage: `Democracy::NextExternal` (r:1 w:1) /// Proof: `Democracy::NextExternal` (`max_values`: Some(1), `max_size`: Some(132), added: 627, mode: `MaxEncodedLen`) @@ -176,10 +168,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `3276` // Estimated: `6703` - // Minimum execution time: 16_474_000 picoseconds. - Weight::from_parts(16_722_000, 6703) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 16_191_000 picoseconds. + Weight::from_parts(16_552_000, 6703) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Democracy::NextExternal` (r:0 w:1) /// Proof: `Democracy::NextExternal` (`max_values`: Some(1), `max_size`: Some(132), added: 627, mode: `MaxEncodedLen`) @@ -187,8 +179,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_354_000 picoseconds. - Weight::from_parts(5_544_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 5_348_000 picoseconds. + Weight::from_parts(5_614_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Democracy::NextExternal` (r:0 w:1) /// Proof: `Democracy::NextExternal` (`max_values`: Some(1), `max_size`: Some(132), added: 627, mode: `MaxEncodedLen`) @@ -196,8 +189,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_302_000 picoseconds. - Weight::from_parts(5_556_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 5_475_000 picoseconds. + Weight::from_parts(5_653_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Democracy::NextExternal` (r:1 w:1) /// Proof: `Democracy::NextExternal` (`max_values`: Some(1), `max_size`: Some(132), added: 627, mode: `MaxEncodedLen`) @@ -211,10 +205,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `147` // Estimated: `3518` - // Minimum execution time: 35_393_000 picoseconds. - Weight::from_parts(36_025_000, 3518) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Minimum execution time: 35_067_000 picoseconds. + Weight::from_parts(35_615_000, 3518) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `Democracy::NextExternal` (r:1 w:1) /// Proof: `Democracy::NextExternal` (`max_values`: Some(1), `max_size`: Some(132), added: 627, mode: `MaxEncodedLen`) @@ -226,10 +220,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `3377` // Estimated: `6703` - // Minimum execution time: 37_183_000 picoseconds. - Weight::from_parts(37_728_000, 6703) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 37_167_000 picoseconds. + Weight::from_parts(37_496_000, 6703) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `Democracy::PublicProps` (r:1 w:1) /// Proof: `Democracy::PublicProps` (`max_values`: Some(1), `max_size`: Some(16702), added: 17197, mode: `MaxEncodedLen`) @@ -243,10 +237,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `6076` // Estimated: `18187` - // Minimum execution time: 107_143_000 picoseconds. - Weight::from_parts(107_867_000, 18187) - .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Minimum execution time: 106_446_000 picoseconds. + Weight::from_parts(107_332_000, 18187) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `Democracy::MetadataOf` (r:1 w:1) /// Proof: `Democracy::MetadataOf` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) @@ -256,10 +250,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `181` // Estimated: `3518` - // Minimum execution time: 27_379_000 picoseconds. - Weight::from_parts(27_886_000, 3518) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 27_026_000 picoseconds. + Weight::from_parts(27_252_000, 3518) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Democracy::LowestUnbaked` (r:1 w:1) /// Proof: `Democracy::LowestUnbaked` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -268,17 +262,17 @@ impl WeightInfo for HydraWeight { /// Storage: `Democracy::ReferendumInfoOf` (r:99 w:0) /// Proof: `Democracy::ReferendumInfoOf` (`max_values`: None, `max_size`: Some(201), added: 2676, mode: `MaxEncodedLen`) /// The range of component `r` is `[0, 99]`. - fn on_initialize_base(r: u32) -> Weight { + fn on_initialize_base(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `108 + r * (86 ±0)` + // Measured: `125 + r * (86 ±0)` // Estimated: `1489 + r * (2676 ±0)` - // Minimum execution time: 6_121_000 picoseconds. - Weight::from_parts(8_592_893, 1489) - // Standard Error: 15_703 - .saturating_add(Weight::from_parts(3_531_200, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) + // Minimum execution time: 6_449_000 picoseconds. + Weight::from_parts(10_202_160, 1489) + // Standard Error: 9_155 + .saturating_add(Weight::from_parts(3_512_494, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) - .saturating_add(T::DbWeight::get().writes(1_u64)) + .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(Weight::from_parts(0, 2676).saturating_mul(r.into())) } /// Storage: `Democracy::LowestUnbaked` (r:1 w:1) @@ -294,17 +288,17 @@ impl WeightInfo for HydraWeight { /// Storage: `Democracy::ReferendumInfoOf` (r:99 w:0) /// Proof: `Democracy::ReferendumInfoOf` (`max_values`: None, `max_size`: Some(201), added: 2676, mode: `MaxEncodedLen`) /// The range of component `r` is `[0, 99]`. - fn on_initialize_base_with_launch_period(r: u32) -> Weight { + fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `108 + r * (86 ±0)` + // Measured: `125 + r * (86 ±0)` // Estimated: `18187 + r * (2676 ±0)` - // Minimum execution time: 10_482_000 picoseconds. - Weight::from_parts(12_899_855, 18187) - // Standard Error: 16_258 - .saturating_add(Weight::from_parts(3_555_121, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(5_u64)) + // Minimum execution time: 10_851_000 picoseconds. + Weight::from_parts(14_487_601, 18187) + // Standard Error: 11_289 + .saturating_add(Weight::from_parts(3_526_832, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) - .saturating_add(T::DbWeight::get().writes(1_u64)) + .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(Weight::from_parts(0, 2676).saturating_mul(r.into())) } /// Storage: `Democracy::VotingOf` (r:3 w:3) @@ -316,17 +310,17 @@ impl WeightInfo for HydraWeight { /// Storage: `Balances::Freezes` (r:1 w:0) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) /// The range of component `r` is `[0, 99]`. - fn delegate(r: u32) -> Weight { + fn delegate(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `658 + r * (108 ±0)` + // Measured: `677 + r * (108 ±0)` // Estimated: `19800 + r * (2676 ±0)` - // Minimum execution time: 52_402_000 picoseconds. - Weight::from_parts(54_800_637, 19800) - // Standard Error: 20_146 - .saturating_add(Weight::from_parts(4_621_419, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(5_u64)) + // Minimum execution time: 51_565_000 picoseconds. + Weight::from_parts(54_150_506, 19800) + // Standard Error: 11_442 + .saturating_add(Weight::from_parts(4_583_970, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) - .saturating_add(T::DbWeight::get().writes(4_u64)) + .saturating_add(T::DbWeight::get().writes(4)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(r.into()))) .saturating_add(Weight::from_parts(0, 2676).saturating_mul(r.into())) } @@ -335,17 +329,17 @@ impl WeightInfo for HydraWeight { /// Storage: `Democracy::ReferendumInfoOf` (r:99 w:99) /// Proof: `Democracy::ReferendumInfoOf` (`max_values`: None, `max_size`: Some(201), added: 2676, mode: `MaxEncodedLen`) /// The range of component `r` is `[0, 99]`. - fn undelegate(r: u32) -> Weight { + fn undelegate(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `356 + r * (108 ±0)` + // Measured: `373 + r * (108 ±0)` // Estimated: `13530 + r * (2676 ±0)` - // Minimum execution time: 25_946_000 picoseconds. - Weight::from_parts(27_003_784, 13530) - // Standard Error: 14_228 - .saturating_add(Weight::from_parts(4_553_164, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) + // Minimum execution time: 25_418_000 picoseconds. + Weight::from_parts(25_764_904, 13530) + // Standard Error: 11_050 + .saturating_add(Weight::from_parts(4_467_732, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) - .saturating_add(T::DbWeight::get().writes(2_u64)) + .saturating_add(T::DbWeight::get().writes(2)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(r.into()))) .saturating_add(Weight::from_parts(0, 2676).saturating_mul(r.into())) } @@ -355,8 +349,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_588_000 picoseconds. - Weight::from_parts(5_693_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 5_514_000 picoseconds. + Weight::from_parts(5_649_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Democracy::VotingOf` (r:1 w:1) /// Proof: `Democracy::VotingOf` (`max_values`: None, `max_size`: Some(3795), added: 6270, mode: `MaxEncodedLen`) @@ -367,16 +362,16 @@ impl WeightInfo for HydraWeight { /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `r` is `[0, 99]`. - fn unlock_remove(r: u32) -> Weight { + fn unlock_remove(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `432` // Estimated: `7260` - // Minimum execution time: 31_199_000 picoseconds. - Weight::from_parts(38_826_891, 7260) - // Standard Error: 21_192 - .saturating_add(Weight::from_parts(155_153, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 31_065_000 picoseconds. + Weight::from_parts(43_368_306, 7260) + // Standard Error: 11_713 + .saturating_add(Weight::from_parts(105_510, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `Democracy::VotingOf` (r:1 w:1) /// Proof: `Democracy::VotingOf` (`max_values`: None, `max_size`: Some(3795), added: 6270, mode: `MaxEncodedLen`) @@ -387,16 +382,16 @@ impl WeightInfo for HydraWeight { /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `r` is `[0, 99]`. - fn unlock_set(r: u32) -> Weight { + fn unlock_set(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `432 + r * (22 ±0)` // Estimated: `7260` - // Minimum execution time: 46_808_000 picoseconds. - Weight::from_parts(47_316_553, 7260) - // Standard Error: 2_010 - .saturating_add(Weight::from_parts(32_507, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 45_967_000 picoseconds. + Weight::from_parts(46_641_334, 7260) + // Standard Error: 1_430 + .saturating_add(Weight::from_parts(52_962, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `Democracy::ReferendumInfoOf` (r:100 w:1) /// Proof: `Democracy::ReferendumInfoOf` (`max_values`: None, `max_size`: Some(201), added: 2676, mode: `MaxEncodedLen`) @@ -409,17 +404,17 @@ impl WeightInfo for HydraWeight { /// Storage: `Staking::PositionVotes` (r:1 w:1) /// Proof: `Staking::PositionVotes` (`max_values`: None, `max_size`: Some(2134), added: 4609, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 100]`. - fn remove_vote(r: u32) -> Weight { + fn remove_vote(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1081 + r * (129 ±0)` + // Measured: `1078 + r * (129 ±0)` // Estimated: `7260 + r * (2676 ±0)` - // Minimum execution time: 50_224_000 picoseconds. - Weight::from_parts(48_115_552, 7260) - // Standard Error: 12_377 - .saturating_add(Weight::from_parts(3_620_792, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(5_u64)) + // Minimum execution time: 49_607_000 picoseconds. + Weight::from_parts(47_295_651, 7260) + // Standard Error: 9_326 + .saturating_add(Weight::from_parts(3_651_350, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) - .saturating_add(T::DbWeight::get().writes(4_u64)) + .saturating_add(T::DbWeight::get().writes(4)) .saturating_add(Weight::from_parts(0, 2676).saturating_mul(r.into())) } /// Storage: `Democracy::ReferendumInfoOf` (r:100 w:1) @@ -433,17 +428,17 @@ impl WeightInfo for HydraWeight { /// Storage: `Staking::PositionVotes` (r:1 w:1) /// Proof: `Staking::PositionVotes` (`max_values`: None, `max_size`: Some(2134), added: 4609, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 100]`. - fn remove_other_vote(r: u32) -> Weight { + fn remove_other_vote(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1081 + r * (129 ±0)` + // Measured: `1078 + r * (129 ±0)` // Estimated: `7260 + r * (2676 ±0)` - // Minimum execution time: 50_234_000 picoseconds. - Weight::from_parts(48_913_493, 7260) - // Standard Error: 9_632 - .saturating_add(Weight::from_parts(3_610_105, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(5_u64)) + // Minimum execution time: 49_376_000 picoseconds. + Weight::from_parts(47_208_359, 7260) + // Standard Error: 7_655 + .saturating_add(Weight::from_parts(3_658_412, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) - .saturating_add(T::DbWeight::get().writes(4_u64)) + .saturating_add(T::DbWeight::get().writes(4)) .saturating_add(Weight::from_parts(0, 2676).saturating_mul(r.into())) } /// Storage: `Democracy::NextExternal` (r:1 w:0) @@ -456,10 +451,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `287` // Estimated: `3556` - // Minimum execution time: 23_854_000 picoseconds. - Weight::from_parts(24_292_000, 3556) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 23_578_000 picoseconds. + Weight::from_parts(24_114_000, 3556) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Democracy::NextExternal` (r:1 w:0) /// Proof: `Democracy::NextExternal` (`max_values`: Some(1), `max_size`: Some(132), added: 627, mode: `MaxEncodedLen`) @@ -469,10 +464,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `147` // Estimated: `3518` - // Minimum execution time: 21_276_000 picoseconds. - Weight::from_parts(21_525_000, 3518) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 21_024_000 picoseconds. + Weight::from_parts(21_324_000, 3518) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Democracy::PublicProps` (r:1 w:0) /// Proof: `Democracy::PublicProps` (`max_values`: Some(1), `max_size`: Some(16702), added: 17197, mode: `MaxEncodedLen`) @@ -484,10 +479,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `4842` // Estimated: `18187` - // Minimum execution time: 47_143_000 picoseconds. - Weight::from_parts(47_852_000, 18187) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 47_604_000 picoseconds. + Weight::from_parts(47_974_000, 18187) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Democracy::PublicProps` (r:1 w:0) /// Proof: `Democracy::PublicProps` (`max_values`: Some(1), `max_size`: Some(16702), added: 17197, mode: `MaxEncodedLen`) @@ -497,10 +492,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `4706` // Estimated: `18187` - // Minimum execution time: 43_821_000 picoseconds. - Weight::from_parts(44_144_000, 18187) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 44_046_000 picoseconds. + Weight::from_parts(44_746_000, 18187) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Preimage::StatusFor` (r:1 w:0) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) @@ -510,10 +505,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `211` // Estimated: `3556` - // Minimum execution time: 20_772_000 picoseconds. - Weight::from_parts(21_133_000, 3556) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 20_917_000 picoseconds. + Weight::from_parts(21_223_000, 3556) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Democracy::ReferendumInfoOf` (r:1 w:0) /// Proof: `Democracy::ReferendumInfoOf` (`max_values`: None, `max_size`: Some(201), added: 2676, mode: `MaxEncodedLen`) @@ -523,9 +518,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `159` // Estimated: `3666` - // Minimum execution time: 23_308_000 picoseconds. - Weight::from_parts(23_661_000, 3666) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 23_184_000 picoseconds. + Weight::from_parts(23_505_000, 3666) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/duster.rs b/runtime/hydradx/src/weights/duster.rs index d48869f11..d57ad0429 100644 --- a/runtime/hydradx/src/weights/duster.rs +++ b/runtime/hydradx/src/weights/duster.rs @@ -3,11 +3,6 @@ // Copyright (C) 2020-2023 Intergalactic, Limited (GIB). // SPDX-License-Identifier: Apache-2.0 -// This file is part of HydraDX. - -// Copyright (C) 2020-2023 Intergalactic, Limited (GIB). -// SPDX-License-Identifier: Apache-2.0 - // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -23,51 +18,48 @@ //! Autogenerated weights for `pallet_duster` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-duster +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_duster +// --output=./weights/duster.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/duster.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_duster::weights::WeightInfo; -/// Weights for pallet_duster using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_duster`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `Duster::AccountBlacklist` (r:1 w:0) /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:2 w:2) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `Duster::DustAccount` (r:1 w:0) /// Proof: `Duster::DustAccount` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Duster::RewardAccount` (r:1 w:0) @@ -76,31 +68,32 @@ impl WeightInfo for HydraWeight { /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn dust_account() -> Weight { // Proof Size summary in bytes: - // Measured: `2538` + // Measured: `2554` // Estimated: `6156` - // Minimum execution time: 90_102_000 picoseconds. - Weight::from_parts(90_700_000, 6156) - .saturating_add(T::DbWeight::get().reads(7_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Minimum execution time: 99_580_000 picoseconds. + Weight::from_parts(100_367_000, 6156) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `Duster::AccountBlacklist` (r:0 w:1) /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) fn add_nondustable_account() -> Weight { // Proof Size summary in bytes: - // Measured: `1008` + // Measured: `1012` // Estimated: `0` - // Minimum execution time: 21_071_000 picoseconds. - Weight::from_parts(21_591_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 20_681_000 picoseconds. + Weight::from_parts(21_171_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Duster::AccountBlacklist` (r:1 w:1) /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) fn remove_nondustable_account() -> Weight { // Proof Size summary in bytes: - // Measured: `1296` + // Measured: `1300` // Estimated: `3513` - // Minimum execution time: 26_630_000 picoseconds. - Weight::from_parts(27_026_000, 3513) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 26_184_000 picoseconds. + Weight::from_parts(26_513_000, 3513) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } } diff --git a/runtime/hydradx/src/weights/ema_oracle.rs b/runtime/hydradx/src/weights/ema_oracle.rs index 78dca3a04..621a35424 100644 --- a/runtime/hydradx/src/weights/ema_oracle.rs +++ b/runtime/hydradx/src/weights/ema_oracle.rs @@ -18,42 +18,37 @@ //! Autogenerated weights for `pallet_ema_oracle` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-ema-oracle +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet-ema-oracle +// --output=./weights/ema_oracle.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/ema_oracle.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_ema_oracle::weights::WeightInfo; -/// Weights for pallet_ema_oracle using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_ema_oracle`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `EmaOracle::Accumulator` (r:1 w:0) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) @@ -61,55 +56,56 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `208` // Estimated: `7406` - // Minimum execution time: 3_108_000 picoseconds. - Weight::from_parts(3_213_000, 7406).saturating_add(T::DbWeight::get().reads(1_u64)) + // Minimum execution time: 3_140_000 picoseconds. + Weight::from_parts(3_253_000, 7406) + .saturating_add(T::DbWeight::get().reads(1)) } /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:117 w:117) /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) /// The range of component `b` is `[1, 39]`. - fn on_finalize_multiple_tokens(b: u32) -> Weight { + fn on_finalize_multiple_tokens(b: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `270 + b * (626 ±0)` // Estimated: `7406 + b * (7956 ±0)` - // Minimum execution time: 46_197_000 picoseconds. - Weight::from_parts(6_894_077, 7406) - // Standard Error: 58_512 - .saturating_add(Weight::from_parts(36_389_579, 0).saturating_mul(b.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) + // Minimum execution time: 46_946_000 picoseconds. + Weight::from_parts(9_495_798, 7406) + // Standard Error: 18_892 + .saturating_add(Weight::from_parts(36_363_503, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(b.into()))) - .saturating_add(T::DbWeight::get().writes(1_u64)) + .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(b.into()))) .saturating_add(Weight::from_parts(0, 7956).saturating_mul(b.into())) } /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) /// The range of component `b` is `[1, 39]`. - fn on_trade_multiple_tokens(b: u32) -> Weight { + fn on_trade_multiple_tokens(b: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `270 + b * (148 ±0)` // Estimated: `7406` - // Minimum execution time: 9_225_000 picoseconds. - Weight::from_parts(9_309_132, 7406) - // Standard Error: 2_681 - .saturating_add(Weight::from_parts(395_788, 0).saturating_mul(b.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 9_605_000 picoseconds. + Weight::from_parts(9_734_841, 7406) + // Standard Error: 1_636 + .saturating_add(Weight::from_parts(368_579, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) /// The range of component `b` is `[1, 39]`. - fn on_liquidity_changed_multiple_tokens(b: u32) -> Weight { + fn on_liquidity_changed_multiple_tokens(b: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `270 + b * (148 ±0)` // Estimated: `7406` - // Minimum execution time: 9_353_000 picoseconds. - Weight::from_parts(9_378_483, 7406) - // Standard Error: 1_820 - .saturating_add(Weight::from_parts(397_535, 0).saturating_mul(b.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 9_580_000 picoseconds. + Weight::from_parts(9_817_291, 7406) + // Standard Error: 1_899 + .saturating_add(Weight::from_parts(364_892, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `EmaOracle::Oracles` (r:2 w:0) /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) @@ -117,7 +113,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `604` // Estimated: `6294` - // Minimum execution time: 18_642_000 picoseconds. - Weight::from_parts(19_015_000, 6294).saturating_add(T::DbWeight::get().reads(2_u64)) + // Minimum execution time: 18_804_000 picoseconds. + Weight::from_parts(19_169_000, 6294) + .saturating_add(T::DbWeight::get().reads(2)) } } diff --git a/runtime/hydradx/src/weights/identity.rs b/runtime/hydradx/src/weights/identity.rs index 7eab3d306..7144de19c 100644 --- a/runtime/hydradx/src/weights/identity.rs +++ b/runtime/hydradx/src/weights/identity.rs @@ -18,73 +18,66 @@ //! Autogenerated weights for `pallet_identity` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-identity +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet-identity +// --output=./weights/identity.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/identity.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +#![allow(missing_docs)] -use pallet_identity::weights::WeightInfo; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -/// Weights for pallet_identity using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_identity`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_identity::WeightInfo for HydraWeight { /// Storage: `Identity::Registrars` (r:1 w:1) /// Proof: `Identity::Registrars` (`max_values`: Some(1), `max_size`: Some(1141), added: 1636, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 19]`. - fn add_registrar(r: u32) -> Weight { + fn add_registrar(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `32 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 16_934_000 picoseconds. - Weight::from_parts(17_553_576, 2626) - // Standard Error: 6_083 - .saturating_add(Weight::from_parts(104_428, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 17_261_000 picoseconds. + Weight::from_parts(18_025_223, 2626) + // Standard Error: 3_087 + .saturating_add(Weight::from_parts(88_219, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Identity::IdentityOf` (r:1 w:1) /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. /// The range of component `x` is `[0, 100]`. - fn set_identity(r: u32, x: u32) -> Weight { + fn set_identity(r: u32, x: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `442 + r * (5 ±0)` // Estimated: `11003` - // Minimum execution time: 44_671_000 picoseconds. - Weight::from_parts(43_380_570, 11003) - // Standard Error: 3_398 - .saturating_add(Weight::from_parts(89_436, 0).saturating_mul(r.into())) - // Standard Error: 659 - .saturating_add(Weight::from_parts(714_757, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 44_163_000 picoseconds. + Weight::from_parts(42_727_355, 11003) + // Standard Error: 4_678 + .saturating_add(Weight::from_parts(103_190, 0).saturating_mul(r.into())) + // Standard Error: 897 + .saturating_add(Weight::from_parts(697_595, 0).saturating_mul(x.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Identity::IdentityOf` (r:1 w:0) /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) @@ -93,17 +86,17 @@ impl WeightInfo for HydraWeight { /// Storage: `Identity::SuperOf` (r:100 w:100) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 100]`. - fn set_subs_new(s: u32) -> Weight { + fn set_subs_new(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `101` // Estimated: `11003 + s * (2589 ±0)` - // Minimum execution time: 14_570_000 picoseconds. - Weight::from_parts(23_863_560, 11003) - // Standard Error: 25_763 - .saturating_add(Weight::from_parts(4_280_870, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) + // Minimum execution time: 14_699_000 picoseconds. + Weight::from_parts(29_345_813, 11003) + // Standard Error: 14_245 + .saturating_add(Weight::from_parts(4_057_797, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(s.into()))) - .saturating_add(T::DbWeight::get().writes(1_u64)) + .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) .saturating_add(Weight::from_parts(0, 2589).saturating_mul(s.into())) } @@ -114,16 +107,16 @@ impl WeightInfo for HydraWeight { /// Storage: `Identity::SuperOf` (r:0 w:100) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// The range of component `p` is `[0, 100]`. - fn set_subs_old(p: u32) -> Weight { + fn set_subs_old(p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `192 + p * (32 ±0)` + // Measured: `193 + p * (32 ±0)` // Estimated: `11003` - // Minimum execution time: 14_562_000 picoseconds. - Weight::from_parts(22_949_900, 11003) - // Standard Error: 23_636 - .saturating_add(Weight::from_parts(1_793_279, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 14_679_000 picoseconds. + Weight::from_parts(27_894_942, 11003) + // Standard Error: 12_742 + .saturating_add(Weight::from_parts(1_675_500, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) } /// Storage: `Identity::SubsOf` (r:1 w:1) @@ -135,20 +128,20 @@ impl WeightInfo for HydraWeight { /// The range of component `r` is `[1, 20]`. /// The range of component `s` is `[0, 100]`. /// The range of component `x` is `[0, 100]`. - fn clear_identity(r: u32, s: u32, x: u32) -> Weight { + fn clear_identity(r: u32, s: u32, x: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `467 + r * (5 ±0) + s * (32 ±0) + x * (66 ±0)` + // Measured: `468 + r * (5 ±0) + s * (32 ±0) + x * (66 ±0)` // Estimated: `11003` - // Minimum execution time: 78_708_000 picoseconds. - Weight::from_parts(39_980_565, 11003) - // Standard Error: 16_719 - .saturating_add(Weight::from_parts(151_091, 0).saturating_mul(r.into())) - // Standard Error: 3_247 - .saturating_add(Weight::from_parts(1_645_822, 0).saturating_mul(s.into())) - // Standard Error: 3_247 - .saturating_add(Weight::from_parts(372_874, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 78_695_000 picoseconds. + Weight::from_parts(41_668_144, 11003) + // Standard Error: 7_894 + .saturating_add(Weight::from_parts(85_933, 0).saturating_mul(r.into())) + // Standard Error: 1_517 + .saturating_add(Weight::from_parts(1_590_914, 0).saturating_mul(s.into())) + // Standard Error: 1_517 + .saturating_add(Weight::from_parts(375_705, 0).saturating_mul(x.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) } /// Storage: `Identity::Registrars` (r:1 w:0) @@ -157,77 +150,77 @@ impl WeightInfo for HydraWeight { /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. /// The range of component `x` is `[0, 100]`. - fn request_judgement(r: u32, x: u32) -> Weight { + fn request_judgement(r: u32, x: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `365 + r * (57 ±0) + x * (66 ±0)` // Estimated: `11003` - // Minimum execution time: 45_052_000 picoseconds. - Weight::from_parts(44_230_262, 11003) - // Standard Error: 5_797 - .saturating_add(Weight::from_parts(68_847, 0).saturating_mul(r.into())) - // Standard Error: 1_125 - .saturating_add(Weight::from_parts(723_782, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 44_784_000 picoseconds. + Weight::from_parts(43_971_070, 11003) + // Standard Error: 5_047 + .saturating_add(Weight::from_parts(80_761, 0).saturating_mul(r.into())) + // Standard Error: 968 + .saturating_add(Weight::from_parts(702_450, 0).saturating_mul(x.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Identity::IdentityOf` (r:1 w:1) /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. /// The range of component `x` is `[0, 100]`. - fn cancel_request(r: u32, x: u32) -> Weight { + fn cancel_request(r: u32, x: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `396 + x * (66 ±0)` // Estimated: `11003` - // Minimum execution time: 41_286_000 picoseconds. - Weight::from_parts(40_750_967, 11003) - // Standard Error: 6_724 - .saturating_add(Weight::from_parts(49_172, 0).saturating_mul(r.into())) - // Standard Error: 1_305 - .saturating_add(Weight::from_parts(723_915, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 41_076_000 picoseconds. + Weight::from_parts(40_739_871, 11003) + // Standard Error: 6_026 + .saturating_add(Weight::from_parts(54_796, 0).saturating_mul(r.into())) + // Standard Error: 1_156 + .saturating_add(Weight::from_parts(702_783, 0).saturating_mul(x.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Identity::Registrars` (r:1 w:1) /// Proof: `Identity::Registrars` (`max_values`: Some(1), `max_size`: Some(1141), added: 1636, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 19]`. - fn set_fee(r: u32) -> Weight { + fn set_fee(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `89 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 10_775_000 picoseconds. - Weight::from_parts(11_396_553, 2626) - // Standard Error: 6_015 - .saturating_add(Weight::from_parts(78_325, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 11_308_000 picoseconds. + Weight::from_parts(11_832_550, 2626) + // Standard Error: 2_040 + .saturating_add(Weight::from_parts(72_446, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Identity::Registrars` (r:1 w:1) /// Proof: `Identity::Registrars` (`max_values`: Some(1), `max_size`: Some(1141), added: 1636, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 19]`. - fn set_account_id(r: u32) -> Weight { + fn set_account_id(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `89 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 11_285_000 picoseconds. - Weight::from_parts(11_718_851, 2626) - // Standard Error: 2_957 - .saturating_add(Weight::from_parts(68_141, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 11_782_000 picoseconds. + Weight::from_parts(12_164_081, 2626) + // Standard Error: 1_710 + .saturating_add(Weight::from_parts(69_398, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Identity::Registrars` (r:1 w:1) /// Proof: `Identity::Registrars` (`max_values`: Some(1), `max_size`: Some(1141), added: 1636, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 19]`. - fn set_fields(r: u32) -> Weight { + fn set_fields(r: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `89 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 10_902_000 picoseconds. - Weight::from_parts(11_350_705, 2626) - // Standard Error: 4_692 - .saturating_add(Weight::from_parts(72_095, 0).saturating_mul(r.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 11_490_000 picoseconds. + Weight::from_parts(11_819_190, 2626) + // Standard Error: 1_612 + .saturating_add(Weight::from_parts(65_269, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Identity::Registrars` (r:1 w:0) /// Proof: `Identity::Registrars` (`max_values`: Some(1), `max_size`: Some(1141), added: 1636, mode: `MaxEncodedLen`) @@ -235,18 +228,18 @@ impl WeightInfo for HydraWeight { /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 19]`. /// The range of component `x` is `[0, 100]`. - fn provide_judgement(r: u32, x: u32) -> Weight { + fn provide_judgement(r: u32, x: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `443 + r * (57 ±0) + x * (66 ±0)` // Estimated: `11003` - // Minimum execution time: 32_313_000 picoseconds. - Weight::from_parts(30_931_150, 11003) - // Standard Error: 6_730 - .saturating_add(Weight::from_parts(97_823, 0).saturating_mul(r.into())) - // Standard Error: 1_225 - .saturating_add(Weight::from_parts(1_117_375, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 32_212_000 picoseconds. + Weight::from_parts(30_951_168, 11003) + // Standard Error: 5_657 + .saturating_add(Weight::from_parts(98_160, 0).saturating_mul(r.into())) + // Standard Error: 1_016 + .saturating_add(Weight::from_parts(1_087_740, 0).saturating_mul(x.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) @@ -259,18 +252,20 @@ impl WeightInfo for HydraWeight { /// The range of component `r` is `[1, 20]`. /// The range of component `s` is `[0, 100]`. /// The range of component `x` is `[0, 100]`. - fn kill_identity(_r: u32, s: u32, x: u32) -> Weight { + fn kill_identity(r: u32, s: u32, x: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `732 + r * (17 ±0) + s * (32 ±0) + x * (66 ±0)` + // Measured: `760 + r * (16 ±0) + s * (32 ±0) + x * (66 ±0)` // Estimated: `11003` - // Minimum execution time: 102_506_000 picoseconds. - Weight::from_parts(68_340_447, 11003) - // Standard Error: 2_827 - .saturating_add(Weight::from_parts(1_654_468, 0).saturating_mul(s.into())) - // Standard Error: 2_827 - .saturating_add(Weight::from_parts(360_303, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 102_051_000 picoseconds. + Weight::from_parts(67_588_586, 11003) + // Standard Error: 12_409 + .saturating_add(Weight::from_parts(167_208, 0).saturating_mul(r.into())) + // Standard Error: 2_384 + .saturating_add(Weight::from_parts(1_609_560, 0).saturating_mul(s.into())) + // Standard Error: 2_384 + .saturating_add(Weight::from_parts(344_185, 0).saturating_mul(x.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) } /// Storage: `Identity::IdentityOf` (r:1 w:0) @@ -280,32 +275,32 @@ impl WeightInfo for HydraWeight { /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 99]`. - fn add_sub(s: u32) -> Weight { + fn add_sub(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `263 + s * (39 ±0)` + // Measured: `428 + s * (36 ±0)` // Estimated: `11003` - // Minimum execution time: 40_861_000 picoseconds. - Weight::from_parts(43_416_491, 11003) - // Standard Error: 5_902 - .saturating_add(Weight::from_parts(84_100, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 40_751_000 picoseconds. + Weight::from_parts(44_490_675, 11003) + // Standard Error: 3_411 + .saturating_add(Weight::from_parts(72_803, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Identity::IdentityOf` (r:1 w:0) /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:1 w:1) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// The range of component `s` is `[1, 100]`. - fn rename_sub(s: u32) -> Weight { + fn rename_sub(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `450 + s * (5 ±0)` + // Measured: `563 + s * (3 ±0)` // Estimated: `11003` - // Minimum execution time: 18_907_000 picoseconds. - Weight::from_parts(20_162_889, 11003) - // Standard Error: 2_842 - .saturating_add(Weight::from_parts(32_962, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 19_092_000 picoseconds. + Weight::from_parts(20_893_870, 11003) + // Standard Error: 1_498 + .saturating_add(Weight::from_parts(29_141, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Identity::IdentityOf` (r:1 w:0) /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) @@ -314,16 +309,16 @@ impl WeightInfo for HydraWeight { /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) /// The range of component `s` is `[1, 100]`. - fn remove_sub(s: u32) -> Weight { + fn remove_sub(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `499 + s * (37 ±0)` + // Measured: `611 + s * (35 ±0)` // Estimated: `11003` - // Minimum execution time: 44_474_000 picoseconds. - Weight::from_parts(46_128_496, 11003) - // Standard Error: 3_813 - .saturating_add(Weight::from_parts(55_997, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 44_470_000 picoseconds. + Weight::from_parts(46_580_204, 11003) + // Standard Error: 1_811 + .saturating_add(Weight::from_parts(51_699, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Identity::SuperOf` (r:1 w:1) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) @@ -332,15 +327,15 @@ impl WeightInfo for HydraWeight { /// Storage: `System::Account` (r:1 w:0) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 99]`. - fn quit_sub(s: u32) -> Weight { + fn quit_sub(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `603 + s * (38 ±0)` + // Measured: `638 + s * (38 ±0)` // Estimated: `6723` - // Minimum execution time: 32_790_000 picoseconds. - Weight::from_parts(34_581_789, 6723) - // Standard Error: 3_665 - .saturating_add(Weight::from_parts(57_073, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 33_030_000 picoseconds. + Weight::from_parts(35_034_240, 6723) + // Standard Error: 1_832 + .saturating_add(Weight::from_parts(54_735, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/lbp.rs b/runtime/hydradx/src/weights/lbp.rs index 8d7348d11..2a4238477 100644 --- a/runtime/hydradx/src/weights/lbp.rs +++ b/runtime/hydradx/src/weights/lbp.rs @@ -18,42 +18,37 @@ //! Autogenerated weights for `pallet_lbp` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-lbp +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_lbp +// --output=./weights/lbp.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/lbp.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_lbp::weights::WeightInfo; -/// Weights for pallet_lbp using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_lbp`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `LBP::PoolData` (r:1 w:1) /// Proof: `LBP::PoolData` (`max_values`: None, `max_size`: Some(163), added: 2638, mode: `MaxEncodedLen`) @@ -61,8 +56,12 @@ impl WeightInfo for HydraWeight { /// Proof: `LBP::FeeCollectorWithAsset` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:4 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:1) @@ -71,12 +70,12 @@ impl WeightInfo for HydraWeight { /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) fn create_pool() -> Weight { // Proof Size summary in bytes: - // Measured: `992` + // Measured: `1178` // Estimated: `11322` - // Minimum execution time: 144_386_000 picoseconds. - Weight::from_parts(145_196_000, 11322) - .saturating_add(T::DbWeight::get().reads(12_u64)) - .saturating_add(T::DbWeight::get().writes(8_u64)) + // Minimum execution time: 162_938_000 picoseconds. + Weight::from_parts(164_251_000, 11322) + .saturating_add(T::DbWeight::get().reads(15)) + .saturating_add(T::DbWeight::get().writes(8)) } /// Storage: `LBP::PoolData` (r:1 w:1) /// Proof: `LBP::PoolData` (`max_values`: None, `max_size`: Some(163), added: 2638, mode: `MaxEncodedLen`) @@ -86,34 +85,42 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3628` - // Minimum execution time: 30_461_000 picoseconds. - Weight::from_parts(30_686_000, 3628) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 30_041_000 picoseconds. + Weight::from_parts(30_468_000, 3628) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `LBP::PoolData` (r:1 w:0) /// Proof: `LBP::PoolData` (`max_values`: None, `max_size`: Some(163), added: 2638, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:4 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:0) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn add_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `1180` + // Measured: `1439` // Estimated: `11322` - // Minimum execution time: 100_583_000 picoseconds. - Weight::from_parts(101_592_000, 11322) - .saturating_add(T::DbWeight::get().reads(8_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Minimum execution time: 118_411_000 picoseconds. + Weight::from_parts(119_467_000, 11322) + .saturating_add(T::DbWeight::get().reads(11)) + .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `LBP::PoolData` (r:1 w:1) /// Proof: `LBP::PoolData` (`max_values`: None, `max_size`: Some(163), added: 2638, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:4 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:1) @@ -124,12 +131,12 @@ impl WeightInfo for HydraWeight { /// Proof: `LBP::FeeCollectorWithAsset` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) fn remove_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `1368` + // Measured: `1554` // Estimated: `11322` - // Minimum execution time: 133_274_000 picoseconds. - Weight::from_parts(134_648_000, 11322) - .saturating_add(T::DbWeight::get().reads(10_u64)) - .saturating_add(T::DbWeight::get().writes(8_u64)) + // Minimum execution time: 153_550_000 picoseconds. + Weight::from_parts(154_890_000, 11322) + .saturating_add(T::DbWeight::get().reads(13)) + .saturating_add(T::DbWeight::get().writes(8)) } /// Storage: `Tokens::Accounts` (r:5 w:5) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) @@ -137,18 +144,22 @@ impl WeightInfo for HydraWeight { /// Proof: `LBP::PoolData` (`max_values`: None, `max_size`: Some(163), added: 2638, mode: `MaxEncodedLen`) /// Storage: `Tokens::Locks` (r:1 w:1) /// Proof: `Tokens::Locks` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn sell() -> Weight { // Proof Size summary in bytes: - // Measured: `1585` + // Measured: `1844` // Estimated: `13905` - // Minimum execution time: 218_344_000 picoseconds. - Weight::from_parts(220_109_000, 13905) - .saturating_add(T::DbWeight::get().reads(12_u64)) - .saturating_add(T::DbWeight::get().writes(7_u64)) + // Minimum execution time: 243_058_000 picoseconds. + Weight::from_parts(244_292_000, 13905) + .saturating_add(T::DbWeight::get().reads(16)) + .saturating_add(T::DbWeight::get().writes(7)) } /// Storage: `LBP::PoolData` (r:1 w:0) /// Proof: `LBP::PoolData` (`max_values`: None, `max_size`: Some(163), added: 2638, mode: `MaxEncodedLen`) @@ -156,18 +167,22 @@ impl WeightInfo for HydraWeight { /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `Tokens::Locks` (r:1 w:1) /// Proof: `Tokens::Locks` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn buy() -> Weight { // Proof Size summary in bytes: - // Measured: `1585` + // Measured: `1844` // Estimated: `13905` - // Minimum execution time: 219_060_000 picoseconds. - Weight::from_parts(220_516_000, 13905) - .saturating_add(T::DbWeight::get().reads(12_u64)) - .saturating_add(T::DbWeight::get().writes(7_u64)) + // Minimum execution time: 242_758_000 picoseconds. + Weight::from_parts(244_140_000, 13905) + .saturating_add(T::DbWeight::get().reads(16)) + .saturating_add(T::DbWeight::get().writes(7)) } /// Storage: `LBP::PoolData` (r:1 w:0) /// Proof: `LBP::PoolData` (`max_values`: None, `max_size`: Some(163), added: 2638, mode: `MaxEncodedLen`) @@ -175,24 +190,28 @@ impl WeightInfo for HydraWeight { /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `Tokens::Locks` (r:1 w:1) /// Proof: `Tokens::Locks` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `c` is `[1, 2]`. /// The range of component `e` is `[0, 1]`. - fn router_execution_sell(c: u32, e: u32) -> Weight { + fn router_execution_sell(c: u32, e: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `756 + e * (829 ±0)` - // Estimated: `6156 + e * (7749 ±0)` - // Minimum execution time: 65_722_000 picoseconds. - Weight::from_parts(66_193_000, 6156) - // Standard Error: 1_355_364 - .saturating_add(Weight::from_parts(3_961_882, 0).saturating_mul(c.into())) - // Standard Error: 2_927_921 - .saturating_add(Weight::from_parts(163_724_923, 0).saturating_mul(e.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().reads((9_u64).saturating_mul(e.into()))) + // Measured: `756 + e * (1088 ±0)` + // Estimated: `6156 + e * (7749 ±251_795_645_551_580_832)` + // Minimum execution time: 66_583_000 picoseconds. + Weight::from_parts(67_060_000, 6156) + // Standard Error: 587_908 + .saturating_add(Weight::from_parts(2_276_829, 0).saturating_mul(c.into())) + // Standard Error: 1_290_627 + .saturating_add(Weight::from_parts(183_046_701, 0).saturating_mul(e.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().reads((13_u64).saturating_mul(e.into()))) .saturating_add(T::DbWeight::get().writes((7_u64).saturating_mul(e.into()))) .saturating_add(Weight::from_parts(0, 7749).saturating_mul(e.into())) } @@ -202,24 +221,28 @@ impl WeightInfo for HydraWeight { /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `Tokens::Locks` (r:1 w:1) /// Proof: `Tokens::Locks` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `c` is `[1, 3]`. /// The range of component `e` is `[0, 1]`. - fn router_execution_buy(c: u32, e: u32) -> Weight { + fn router_execution_buy(c: u32, e: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `756 + e * (829 ±0)` + // Measured: `756 + e * (1088 ±0)` // Estimated: `6156 + e * (7749 ±0)` - // Minimum execution time: 116_733_000 picoseconds. - Weight::from_parts(117_433_000, 6156) - // Standard Error: 1_509_020 - .saturating_add(Weight::from_parts(5_197_432, 0).saturating_mul(c.into())) - // Standard Error: 4_928_439 - .saturating_add(Weight::from_parts(141_782_318, 0).saturating_mul(e.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().reads((9_u64).saturating_mul(e.into()))) + // Minimum execution time: 117_561_000 picoseconds. + Weight::from_parts(118_264_000, 6156) + // Standard Error: 751_682 + .saturating_add(Weight::from_parts(3_708_043, 0).saturating_mul(c.into())) + // Standard Error: 2_482_101 + .saturating_add(Weight::from_parts(155_294_743, 0).saturating_mul(e.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().reads((13_u64).saturating_mul(e.into()))) .saturating_add(T::DbWeight::get().writes((7_u64).saturating_mul(e.into()))) .saturating_add(Weight::from_parts(0, 7749).saturating_mul(e.into())) } @@ -231,7 +254,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `756` // Estimated: `6156` - // Minimum execution time: 65_795_000 picoseconds. - Weight::from_parts(66_370_000, 6156).saturating_add(T::DbWeight::get().reads(3_u64)) + // Minimum execution time: 66_616_000 picoseconds. + Weight::from_parts(67_128_000, 6156) + .saturating_add(T::DbWeight::get().reads(3)) } } diff --git a/runtime/hydradx/src/weights/omnipool.rs b/runtime/hydradx/src/weights/omnipool.rs index 777d91214..8cd6318d1 100644 --- a/runtime/hydradx/src/weights/omnipool.rs +++ b/runtime/hydradx/src/weights/omnipool.rs @@ -18,7 +18,7 @@ //! Autogenerated weights for `pallet_omnipool` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2024-01-09, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 @@ -33,31 +33,25 @@ // --wasm-execution=compiled // --heap-pages=4096 // --template=.maintain/pallet-weight-template-no-back.hbs -// --pallet=pallet-omnipool -// --output=weights-1.1.0/omnipool.rs +// --pallet=pallet_omnipool +// --output=./weights/omnipool.rs // --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_omnipool::weights::WeightInfo; - -/// Weights for pallet_omnipool using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_omnipool`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_omnipool::WeightInfo for HydraWeight { /// Storage: `Omnipool::Assets` (r:1 w:1) /// Proof: `Omnipool::Assets` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Uniques::Class` (r:1 w:1) /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(190), added: 2665, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:2 w:1) @@ -70,6 +64,8 @@ impl WeightInfo for HydraWeight { /// Proof: `Uniques::CollectionMaxSupply` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) /// Storage: `Omnipool::HubAssetImbalance` (r:1 w:1) /// Proof: `Omnipool::HubAssetImbalance` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) @@ -80,11 +76,11 @@ impl WeightInfo for HydraWeight { /// Proof: `Omnipool::Positions` (`max_values`: None, `max_size`: Some(100), added: 2575, mode: `MaxEncodedLen`) fn add_token() -> Weight { // Proof Size summary in bytes: - // Measured: `3004` + // Measured: `3028` // Estimated: `7406` - // Minimum execution time: 141_394_000 picoseconds. - Weight::from_parts(142_349_000, 7406) - .saturating_add(T::DbWeight::get().reads(12)) + // Minimum execution time: 146_309_000 picoseconds. + Weight::from_parts(147_552_000, 7406) + .saturating_add(T::DbWeight::get().reads(13)) .saturating_add(T::DbWeight::get().writes(10)) } /// Storage: `Tokens::Accounts` (r:3 w:3) @@ -103,8 +99,12 @@ impl WeightInfo for HydraWeight { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(190), added: 2665, mode: `MaxEncodedLen`) /// Storage: `Uniques::CollectionMaxSupply` (r:1 w:0) /// Proof: `Uniques::CollectionMaxSupply` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:0) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) @@ -125,11 +125,11 @@ impl WeightInfo for HydraWeight { /// Proof: `Omnipool::Positions` (`max_values`: None, `max_size`: Some(100), added: 2575, mode: `MaxEncodedLen`) fn add_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `3919` + // Measured: `4178` // Estimated: `8739` - // Minimum execution time: 220_969_000 picoseconds. - Weight::from_parts(222_574_000, 8739) - .saturating_add(T::DbWeight::get().reads(20)) + // Minimum execution time: 236_030_000 picoseconds. + Weight::from_parts(237_610_000, 8739) + .saturating_add(T::DbWeight::get().reads(23)) .saturating_add(T::DbWeight::get().writes(14)) } /// Storage: `Uniques::Asset` (r:1 w:1) @@ -144,8 +144,12 @@ impl WeightInfo for HydraWeight { /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) /// Storage: `Omnipool::HubAssetImbalance` (r:1 w:1) /// Proof: `Omnipool::HubAssetImbalance` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) @@ -172,11 +176,11 @@ impl WeightInfo for HydraWeight { /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(113), added: 2588, mode: `MaxEncodedLen`) fn remove_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `6903` + // Measured: `7089` // Estimated: `11322` - // Minimum execution time: 297_780_000 picoseconds. - Weight::from_parts(299_506_000, 11322) - .saturating_add(T::DbWeight::get().reads(23)) + // Minimum execution time: 316_738_000 picoseconds. + Weight::from_parts(319_501_000, 11322) + .saturating_add(T::DbWeight::get().reads(26)) .saturating_add(T::DbWeight::get().writes(16)) } /// Storage: `Tokens::Accounts` (r:5 w:5) @@ -187,8 +191,12 @@ impl WeightInfo for HydraWeight { /// Proof: `Omnipool::HubAssetImbalance` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) /// Storage: `DynamicFees::AssetFee` (r:2 w:0) /// Proof: `DynamicFees::AssetFee` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:2 w:2) @@ -225,11 +233,11 @@ impl WeightInfo for HydraWeight { /// Proof: `Referrals::CounterForPendingConversions` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn sell() -> Weight { // Proof Size summary in bytes: - // Measured: `7179` + // Measured: `7327` // Estimated: `13905` - // Minimum execution time: 333_598_000 picoseconds. - Weight::from_parts(336_465_000, 13905) - .saturating_add(T::DbWeight::get().reads(35)) + // Minimum execution time: 360_954_000 picoseconds. + Weight::from_parts(362_880_000, 13905) + .saturating_add(T::DbWeight::get().reads(39)) .saturating_add(T::DbWeight::get().writes(23)) } /// Storage: `Omnipool::Assets` (r:3 w:3) @@ -240,8 +248,12 @@ impl WeightInfo for HydraWeight { /// Proof: `Omnipool::HubAssetImbalance` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) /// Storage: `DynamicFees::AssetFee` (r:2 w:0) /// Proof: `DynamicFees::AssetFee` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:2 w:2) @@ -278,11 +290,11 @@ impl WeightInfo for HydraWeight { /// Proof: `Referrals::CounterForPendingConversions` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn buy() -> Weight { // Proof Size summary in bytes: - // Measured: `7179` + // Measured: `7327` // Estimated: `13905` - // Minimum execution time: 333_688_000 picoseconds. - Weight::from_parts(335_133_000, 13905) - .saturating_add(T::DbWeight::get().reads(35)) + // Minimum execution time: 364_573_000 picoseconds. + Weight::from_parts(365_989_000, 13905) + .saturating_add(T::DbWeight::get().reads(39)) .saturating_add(T::DbWeight::get().writes(23)) } /// Storage: `Omnipool::Assets` (r:1 w:1) @@ -291,8 +303,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `1305` // Estimated: `3550` - // Minimum execution time: 32_634_000 picoseconds. - Weight::from_parts(33_024_000, 3550) + // Minimum execution time: 32_736_000 picoseconds. + Weight::from_parts(33_138_000, 3550) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -300,8 +312,12 @@ impl WeightInfo for HydraWeight { /// Proof: `Omnipool::Assets` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:2 w:2) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:1) @@ -310,11 +326,11 @@ impl WeightInfo for HydraWeight { /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) fn refund_refused_asset() -> Weight { // Proof Size summary in bytes: - // Measured: `2336` + // Measured: `2510` // Estimated: `6196` - // Minimum execution time: 107_435_000 picoseconds. - Weight::from_parts(108_211_000, 6196) - .saturating_add(T::DbWeight::get().reads(8)) + // Minimum execution time: 122_163_000 picoseconds. + Weight::from_parts(123_392_000, 6196) + .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `Omnipool::Positions` (r:1 w:1) @@ -333,8 +349,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `2876` // Estimated: `3655` - // Minimum execution time: 75_289_000 picoseconds. - Weight::from_parts(76_090_000, 3655) + // Minimum execution time: 75_629_000 picoseconds. + Weight::from_parts(76_582_000, 3655) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(6)) } @@ -344,8 +360,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `1305` // Estimated: `3550` - // Minimum execution time: 32_857_000 picoseconds. - Weight::from_parts(33_349_000, 3550) + // Minimum execution time: 32_944_000 picoseconds. + Weight::from_parts(33_586_000, 3550) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -355,8 +371,12 @@ impl WeightInfo for HydraWeight { /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `Omnipool::HubAssetImbalance` (r:1 w:1) /// Proof: `Omnipool::HubAssetImbalance` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) @@ -369,11 +389,11 @@ impl WeightInfo for HydraWeight { /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) fn withdraw_protocol_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `4019` + // Measured: `4205` // Estimated: `8739` - // Minimum execution time: 161_313_000 picoseconds. - Weight::from_parts(162_354_000, 8739) - .saturating_add(T::DbWeight::get().reads(13)) + // Minimum execution time: 174_415_000 picoseconds. + Weight::from_parts(174_998_000, 8739) + .saturating_add(T::DbWeight::get().reads(15)) .saturating_add(T::DbWeight::get().writes(8)) } /// Storage: `Omnipool::Assets` (r:1 w:1) @@ -383,9 +403,13 @@ impl WeightInfo for HydraWeight { /// Storage: `Omnipool::HubAssetImbalance` (r:1 w:1) /// Proof: `Omnipool::HubAssetImbalance` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:2 w:0) @@ -394,11 +418,11 @@ impl WeightInfo for HydraWeight { /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) fn remove_token() -> Weight { // Proof Size summary in bytes: - // Measured: `3110` + // Measured: `3296` // Estimated: `11322` - // Minimum execution time: 160_104_000 picoseconds. - Weight::from_parts(161_947_000, 11322) - .saturating_add(T::DbWeight::get().reads(14)) + // Minimum execution time: 175_638_000 picoseconds. + Weight::from_parts(176_841_000, 11322) + .saturating_add(T::DbWeight::get().reads(16)) .saturating_add(T::DbWeight::get().writes(8)) } /// Storage: `Omnipool::Assets` (r:3 w:3) @@ -409,8 +433,12 @@ impl WeightInfo for HydraWeight { /// Proof: `Omnipool::HubAssetImbalance` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) /// Storage: `DynamicFees::AssetFee` (r:2 w:0) /// Proof: `DynamicFees::AssetFee` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:2 w:2) @@ -443,18 +471,16 @@ impl WeightInfo for HydraWeight { /// Proof: `Referrals::CounterForPendingConversions` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// The range of component `c` is `[1, 2]`. /// The range of component `e` is `[0, 1]`. - fn router_execution_sell(c: u32, e: u32, ) -> Weight { + fn router_execution_sell(_c: u32, e: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1974 + e * (4750 ±0)` - // Estimated: `6156 + e * (7749 ±118_379_753_737_997_488)` - // Minimum execution time: 49_393_000 picoseconds. - Weight::from_parts(47_313_937, 6156) - // Standard Error: 84_954 - .saturating_add(Weight::from_parts(1_522_262, 0).saturating_mul(c.into())) - // Standard Error: 84_954 - .saturating_add(Weight::from_parts(288_560_770, 0).saturating_mul(e.into())) + // Measured: `1974 + e * (4936 ±0)` + // Estimated: `6156 + e * (7749 ±201_913_854_157_949_888)` + // Minimum execution time: 48_921_000 picoseconds. + Weight::from_parts(51_507_911, 6156) + // Standard Error: 122_017 + .saturating_add(Weight::from_parts(316_472_235, 0).saturating_mul(e.into())) .saturating_add(T::DbWeight::get().reads(7)) - .saturating_add(T::DbWeight::get().reads((25_u64).saturating_mul(e.into()))) + .saturating_add(T::DbWeight::get().reads((29_u64).saturating_mul(e.into()))) .saturating_add(T::DbWeight::get().writes((21_u64).saturating_mul(e.into()))) .saturating_add(Weight::from_parts(0, 7749).saturating_mul(e.into())) } @@ -466,8 +492,12 @@ impl WeightInfo for HydraWeight { /// Proof: `Omnipool::HubAssetImbalance` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) /// Storage: `DynamicFees::AssetFee` (r:2 w:0) /// Proof: `DynamicFees::AssetFee` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:2 w:2) @@ -500,17 +530,15 @@ impl WeightInfo for HydraWeight { /// Proof: `Referrals::CounterForPendingConversions` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// The range of component `c` is `[1, 2]`. /// The range of component `e` is `[0, 1]`. - fn router_execution_buy(c: u32, e: u32, ) -> Weight { + fn router_execution_buy(c: u32, _e: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `6724` + // Measured: `6910` // Estimated: `13905` - // Minimum execution time: 319_950_000 picoseconds. - Weight::from_parts(308_443_101, 13905) - // Standard Error: 135_443 - .saturating_add(Weight::from_parts(14_990_074, 0).saturating_mul(c.into())) - // Standard Error: 135_443 - .saturating_add(Weight::from_parts(285_316, 0).saturating_mul(e.into())) - .saturating_add(T::DbWeight::get().reads(32)) + // Minimum execution time: 350_132_000 picoseconds. + Weight::from_parts(340_475_478, 13905) + // Standard Error: 178_513 + .saturating_add(Weight::from_parts(13_719_977, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(36)) .saturating_add(T::DbWeight::get().writes(21)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/omnipool_lm.rs b/runtime/hydradx/src/weights/omnipool_lm.rs index 534e2145a..2e257585f 100644 --- a/runtime/hydradx/src/weights/omnipool_lm.rs +++ b/runtime/hydradx/src/weights/omnipool_lm.rs @@ -18,45 +18,38 @@ //! Autogenerated weights for `pallet_omnipool_liquidity_mining` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-omnipool-liquidity-mining +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_omnipool_liquidity_mining +// --output=./weights/omnipool_lm.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/omnipool_lm.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_omnipool_liquidity_mining::weights::WeightInfo; - -/// Weights for pallet_omnipool_liquidity_mining using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_omnipool_liquidity_mining`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_omnipool_liquidity_mining::WeightInfo for HydraWeight { /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `OmnipoolWarehouseLM::FarmSequencer` (r:1 w:1) @@ -67,12 +60,12 @@ impl WeightInfo for HydraWeight { /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) fn create_global_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `462` + // Measured: `491` // Estimated: `6196` - // Minimum execution time: 104_411_000 picoseconds. - Weight::from_parts(105_372_000, 6196) - .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Minimum execution time: 104_814_000 picoseconds. + Weight::from_parts(105_633_000, 6196) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) @@ -84,10 +77,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `898` // Estimated: `6196` - // Minimum execution time: 101_766_000 picoseconds. - Weight::from_parts(102_892_000, 6196) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Minimum execution time: 100_225_000 picoseconds. + Weight::from_parts(101_025_000, 6196) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `Omnipool::Assets` (r:1 w:0) /// Proof: `Omnipool::Assets` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) @@ -96,7 +89,7 @@ impl WeightInfo for HydraWeight { /// Storage: `OmnipoolWarehouseLM::ActiveYieldFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::ActiveYieldFarm` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:2 w:0) @@ -107,12 +100,12 @@ impl WeightInfo for HydraWeight { /// Proof: `OmnipoolWarehouseLM::YieldFarm` (`max_values`: None, `max_size`: Some(198), added: 2673, mode: `MaxEncodedLen`) fn create_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `2287` + // Measured: `2271` // Estimated: `6294` - // Minimum execution time: 140_071_000 picoseconds. - Weight::from_parts(141_599_000, 6294) - .saturating_add(T::DbWeight::get().reads(9_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) + // Minimum execution time: 140_947_000 picoseconds. + Weight::from_parts(141_851_000, 6294) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `Omnipool::Assets` (r:1 w:0) /// Proof: `Omnipool::Assets` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) @@ -123,19 +116,19 @@ impl WeightInfo for HydraWeight { /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:2 w:0) /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn update_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `2457` + // Measured: `2441` // Estimated: `6294` - // Minimum execution time: 145_051_000 picoseconds. - Weight::from_parts(146_213_000, 6294) - .saturating_add(T::DbWeight::get().reads(9_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Minimum execution time: 145_933_000 picoseconds. + Weight::from_parts(147_109_000, 6294) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `OmnipoolWarehouseLM::ActiveYieldFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::ActiveYieldFarm` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) @@ -144,19 +137,19 @@ impl WeightInfo for HydraWeight { /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:2 w:0) /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn stop_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `2096` + // Measured: `2080` // Estimated: `6294` - // Minimum execution time: 139_750_000 picoseconds. - Weight::from_parts(140_646_000, 6294) - .saturating_add(T::DbWeight::get().reads(8_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Minimum execution time: 138_770_000 picoseconds. + Weight::from_parts(140_134_000, 6294) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `Omnipool::Assets` (r:1 w:0) /// Proof: `Omnipool::Assets` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) @@ -167,19 +160,19 @@ impl WeightInfo for HydraWeight { /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:2 w:0) /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn resume_yield_farm() -> Weight { // Proof Size summary in bytes: - // Measured: `2493` + // Measured: `2477` // Estimated: `6294` - // Minimum execution time: 141_404_000 picoseconds. - Weight::from_parts(142_349_000, 6294) - .saturating_add(T::DbWeight::get().reads(9_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Minimum execution time: 140_945_000 picoseconds. + Weight::from_parts(142_502_000, 6294) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `OmnipoolWarehouseLM::ActiveYieldFarm` (r:1 w:0) /// Proof: `OmnipoolWarehouseLM::ActiveYieldFarm` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) @@ -193,10 +186,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `924` // Estimated: `6196` - // Minimum execution time: 90_529_000 picoseconds. - Weight::from_parts(91_011_000, 6196) - .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Minimum execution time: 89_994_000 picoseconds. + Weight::from_parts(90_683_000, 6196) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `Uniques::Asset` (r:2 w:2) /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) @@ -209,7 +202,7 @@ impl WeightInfo for HydraWeight { /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:4 w:0) @@ -230,12 +223,12 @@ impl WeightInfo for HydraWeight { /// Proof: `OmnipoolWarehouseLM::Deposit` (`max_values`: None, `max_size`: Some(385), added: 2860, mode: `MaxEncodedLen`) fn deposit_shares() -> Weight { // Proof Size summary in bytes: - // Measured: `3989` + // Measured: `3973` // Estimated: `11598` - // Minimum execution time: 240_264_000 picoseconds. - Weight::from_parts(241_286_000, 11598) - .saturating_add(T::DbWeight::get().reads(17_u64)) - .saturating_add(T::DbWeight::get().writes(14_u64)) + // Minimum execution time: 236_325_000 picoseconds. + Weight::from_parts(239_018_000, 11598) + .saturating_add(T::DbWeight::get().reads(17)) + .saturating_add(T::DbWeight::get().writes(14)) } /// Storage: `Uniques::Asset` (r:2 w:0) /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) @@ -252,19 +245,19 @@ impl WeightInfo for HydraWeight { /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:4 w:0) /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn redeposit_shares() -> Weight { // Proof Size summary in bytes: - // Measured: `4331` + // Measured: `4315` // Estimated: `11598` - // Minimum execution time: 195_833_000 picoseconds. - Weight::from_parts(196_912_000, 11598) - .saturating_add(T::DbWeight::get().reads(15_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Minimum execution time: 197_087_000 picoseconds. + Weight::from_parts(198_393_000, 11598) + .saturating_add(T::DbWeight::get().reads(15)) + .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `Uniques::Asset` (r:1 w:0) /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) @@ -275,19 +268,19 @@ impl WeightInfo for HydraWeight { /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:3) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:2 w:0) /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn claim_rewards() -> Weight { // Proof Size summary in bytes: - // Measured: `2896` + // Measured: `2880` // Estimated: `8799` - // Minimum execution time: 195_680_000 picoseconds. - Weight::from_parts(196_827_000, 8799) - .saturating_add(T::DbWeight::get().reads(10_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) + // Minimum execution time: 195_915_000 picoseconds. + Weight::from_parts(197_475_000, 8799) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `Uniques::Asset` (r:2 w:2) /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(146), added: 2621, mode: `MaxEncodedLen`) @@ -302,7 +295,7 @@ impl WeightInfo for HydraWeight { /// Storage: `OmnipoolWarehouseLM::GlobalFarm` (r:1 w:1) /// Proof: `OmnipoolWarehouseLM::GlobalFarm` (`max_values`: None, `max_size`: Some(205), added: 2680, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:3 w:3) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:2 w:0) @@ -315,11 +308,11 @@ impl WeightInfo for HydraWeight { /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(113), added: 2588, mode: `MaxEncodedLen`) fn withdraw_shares() -> Weight { // Proof Size summary in bytes: - // Measured: `3857` + // Measured: `3841` // Estimated: `8799` - // Minimum execution time: 294_229_000 picoseconds. - Weight::from_parts(296_004_000, 8799) - .saturating_add(T::DbWeight::get().reads(15_u64)) - .saturating_add(T::DbWeight::get().writes(15_u64)) + // Minimum execution time: 294_171_000 picoseconds. + Weight::from_parts(296_256_000, 8799) + .saturating_add(T::DbWeight::get().reads(15)) + .saturating_add(T::DbWeight::get().writes(15)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/otc.rs b/runtime/hydradx/src/weights/otc.rs index d26b68380..9911cb4cd 100644 --- a/runtime/hydradx/src/weights/otc.rs +++ b/runtime/hydradx/src/weights/otc.rs @@ -18,113 +18,118 @@ //! Autogenerated weights for `pallet_otc` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-otc +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_otc +// --output=./weights/otc.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/otc.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_otc::weights::WeightInfo; -/// Weights for pallet_otc using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_otc`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `OTC::NextOrderId` (r:1 w:1) /// Proof: `OTC::NextOrderId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Reserves` (r:1 w:1) + /// Proof: `Tokens::Reserves` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:1 w:1) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `OTC::Orders` (r:0 w:1) /// Proof: `OTC::Orders` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) fn place_order() -> Weight { // Proof Size summary in bytes: - // Measured: `624` - // Estimated: `6114` - // Minimum execution time: 54_176_000 picoseconds. - Weight::from_parts(54_920_000, 6114) - .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Measured: `897` + // Estimated: `6190` + // Minimum execution time: 55_411_000 picoseconds. + Weight::from_parts(56_027_000, 6190) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `OTC::Orders` (r:1 w:1) /// Proof: `OTC::Orders` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:2 w:2) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:4 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) + /// Storage: `System::Account` (r:2 w:0) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Reserves` (r:1 w:1) + /// Proof: `Tokens::Reserves` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) fn partial_fill_order() -> Weight { // Proof Size summary in bytes: - // Measured: `1404` - // Estimated: `6196` - // Minimum execution time: 138_354_000 picoseconds. - Weight::from_parts(140_113_000, 6196) - .saturating_add(T::DbWeight::get().reads(8_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) + // Measured: `1882` + // Estimated: `11322` + // Minimum execution time: 138_653_000 picoseconds. + Weight::from_parts(139_630_000, 11322) + .saturating_add(T::DbWeight::get().reads(14)) + .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `OTC::Orders` (r:1 w:1) /// Proof: `OTC::Orders` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:2 w:2) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:4 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) + /// Storage: `AssetRegistry::Assets` (r:2 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:0) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Reserves` (r:1 w:1) + /// Proof: `Tokens::Reserves` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) fn fill_order() -> Weight { // Proof Size summary in bytes: - // Measured: `1399` - // Estimated: `6196` - // Minimum execution time: 136_927_000 picoseconds. - Weight::from_parts(137_782_000, 6196) - .saturating_add(T::DbWeight::get().reads(7_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) + // Measured: `1882` + // Estimated: `11322` + // Minimum execution time: 135_774_000 picoseconds. + Weight::from_parts(137_332_000, 11322) + .saturating_add(T::DbWeight::get().reads(14)) + .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `OTC::Orders` (r:1 w:1) /// Proof: `OTC::Orders` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) - /// Storage: `Balances::Reserves` (r:1 w:1) - /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Reserves` (r:1 w:1) + /// Proof: `Tokens::Reserves` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:1 w:1) + /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:1 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) fn cancel_order() -> Weight { // Proof Size summary in bytes: - // Measured: `525` - // Estimated: `4714` - // Minimum execution time: 44_402_000 picoseconds. - Weight::from_parts(44_773_000, 4714) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Measured: `1131` + // Estimated: `4726` + // Minimum execution time: 50_061_000 picoseconds. + Weight::from_parts(50_721_000, 4726) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) } } diff --git a/runtime/hydradx/src/weights/payment.rs b/runtime/hydradx/src/weights/payment.rs index f3b1b6eeb..6faa12376 100644 --- a/runtime/hydradx/src/weights/payment.rs +++ b/runtime/hydradx/src/weights/payment.rs @@ -18,7 +18,7 @@ //! Autogenerated weights for `pallet_transaction_multi_payment` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-27, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 @@ -33,26 +33,22 @@ // --wasm-execution=compiled // --heap-pages=4096 // --template=.maintain/pallet-weight-template-no-back.hbs -// --pallet=pallet-transaction-multi-payment -// --output=weights-1.1.0/transaction_multi_payment.rs +// --pallet=pallet_transaction_multi_payment +// --output=./weights/payment.rs // --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_transaction_multi_payment::weights::WeightInfo; -/// Weights for pallet_transaction_multi_payment using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_transaction_multi_payment`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:1) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) @@ -60,8 +56,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `1176` // Estimated: `3493` - // Minimum execution time: 24_548_000 picoseconds. - Weight::from_parts(25_118_000, 3493) + // Minimum execution time: 24_211_000 picoseconds. + Weight::from_parts(24_571_000, 3493) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -71,8 +67,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `1207` // Estimated: `3493` - // Minimum execution time: 25_178_000 picoseconds. - Weight::from_parts(25_545_000, 3493) + // Minimum execution time: 24_768_000 picoseconds. + Weight::from_parts(24_992_000, 3493) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -84,8 +80,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `1241` // Estimated: `3493` - // Minimum execution time: 30_284_000 picoseconds. - Weight::from_parts(30_744_000, 3493) + // Minimum execution time: 30_095_000 picoseconds. + Weight::from_parts(30_539_000, 3493) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -97,8 +93,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `3221` // Estimated: `27510` - // Minimum execution time: 93_281_000 picoseconds. - Weight::from_parts(94_259_000, 27510) + // Minimum execution time: 94_272_000 picoseconds. + Weight::from_parts(95_196_000, 27510) .saturating_add(T::DbWeight::get().reads(11)) } } diff --git a/runtime/hydradx/src/weights/preimage.rs b/runtime/hydradx/src/weights/preimage.rs index 8e3671a5c..60afab1b5 100644 --- a/runtime/hydradx/src/weights/preimage.rs +++ b/runtime/hydradx/src/weights/preimage.rs @@ -18,89 +18,83 @@ //! Autogenerated weights for `pallet_preimage` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-preimage +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet-preimage +// --output=./weights/preimage.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/preimage.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +#![allow(missing_docs)] -use pallet_preimage::weights::WeightInfo; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; +/// Weight functions for `pallet_preimage`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_preimage::WeightInfo for HydraWeight { /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// Storage: `Preimage::PreimageFor` (r:0 w:1) /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 4194304]`. - fn note_preimage(s: u32) -> Weight { + fn note_preimage(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `210` // Estimated: `3556` - // Minimum execution time: 41_621_000 picoseconds. - Weight::from_parts(42_113_000, 3556) - // Standard Error: 2 - .saturating_add(Weight::from_parts(1_993, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 41_276_000 picoseconds. + Weight::from_parts(41_498_000, 3556) + // Standard Error: 1 + .saturating_add(Weight::from_parts(1_985, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// Storage: `Preimage::PreimageFor` (r:0 w:1) /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 4194304]`. - fn note_requested_preimage(s: u32) -> Weight { + fn note_requested_preimage(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `173` // Estimated: `3556` - // Minimum execution time: 23_232_000 picoseconds. - Weight::from_parts(23_575_000, 3556) - // Standard Error: 3 - .saturating_add(Weight::from_parts(1_998, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 23_090_000 picoseconds. + Weight::from_parts(23_405_000, 3556) + // Standard Error: 9 + .saturating_add(Weight::from_parts(2_041, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// Storage: `Preimage::PreimageFor` (r:0 w:1) /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 4194304]`. - fn note_no_deposit_preimage(s: u32) -> Weight { + fn note_no_deposit_preimage(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `173` // Estimated: `3556` - // Minimum execution time: 22_316_000 picoseconds. - Weight::from_parts(22_663_000, 3556) - // Standard Error: 2 - .saturating_add(Weight::from_parts(1_995, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 22_229_000 picoseconds. + Weight::from_parts(8_603_845, 3556) + // Standard Error: 8 + .saturating_add(Weight::from_parts(1_999, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) @@ -110,10 +104,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `356` // Estimated: `3556` - // Minimum execution time: 52_679_000 picoseconds. - Weight::from_parts(53_474_000, 3556) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 53_648_000 picoseconds. + Weight::from_parts(55_277_000, 3556) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) @@ -123,10 +117,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `211` // Estimated: `3556` - // Minimum execution time: 31_545_000 picoseconds. - Weight::from_parts(32_646_000, 3556) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 31_781_000 picoseconds. + Weight::from_parts(32_720_000, 3556) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) @@ -134,10 +128,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `255` // Estimated: `3556` - // Minimum execution time: 28_243_000 picoseconds. - Weight::from_parts(29_512_000, 3556) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 28_938_000 picoseconds. + Weight::from_parts(29_985_000, 3556) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) @@ -145,10 +139,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `211` // Estimated: `3556` - // Minimum execution time: 17_312_000 picoseconds. - Weight::from_parts(18_097_000, 3556) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 17_683_000 picoseconds. + Weight::from_parts(18_217_000, 3556) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) @@ -156,10 +150,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3556` - // Minimum execution time: 18_766_000 picoseconds. - Weight::from_parts(19_233_000, 3556) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 18_566_000 picoseconds. + Weight::from_parts(19_082_000, 3556) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) @@ -167,10 +161,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `173` // Estimated: `3556` - // Minimum execution time: 12_350_000 picoseconds. - Weight::from_parts(12_757_000, 3556) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 12_526_000 picoseconds. + Weight::from_parts(12_808_000, 3556) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) @@ -180,10 +174,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `211` // Estimated: `3556` - // Minimum execution time: 30_134_000 picoseconds. - Weight::from_parts(31_219_000, 3556) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 29_887_000 picoseconds. + Weight::from_parts(30_842_000, 3556) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) @@ -191,10 +185,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `173` // Estimated: `3556` - // Minimum execution time: 12_288_000 picoseconds. - Weight::from_parts(12_700_000, 3556) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 12_510_000 picoseconds. + Weight::from_parts(12_886_000, 3556) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) @@ -202,9 +196,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `173` // Estimated: `3556` - // Minimum execution time: 12_628_000 picoseconds. - Weight::from_parts(12_949_000, 3556) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 12_820_000 picoseconds. + Weight::from_parts(13_056_000, 3556) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/proxy.rs b/runtime/hydradx/src/weights/proxy.rs index ecc53ef07..efa83756f 100644 --- a/runtime/hydradx/src/weights/proxy.rs +++ b/runtime/hydradx/src/weights/proxy.rs @@ -18,55 +18,48 @@ //! Autogenerated weights for `pallet_proxy` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-proxy +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet-proxy +// --output=./weights/proxy.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/proxy.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +#![allow(missing_docs)] -use pallet_proxy::weights::WeightInfo; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -/// Weights for pallet_proxy using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_proxy`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_proxy::WeightInfo for HydraWeight { /// Storage: `Proxy::Proxies` (r:1 w:0) /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) /// The range of component `p` is `[1, 31]`. - fn proxy(p: u32) -> Weight { + fn proxy(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `293 + p * (37 ±0)` // Estimated: `4706` - // Minimum execution time: 22_719_000 picoseconds. - Weight::from_parts(23_093_311, 4706) - // Standard Error: 1_907 - .saturating_add(Weight::from_parts(38_448, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) + // Minimum execution time: 23_362_000 picoseconds. + Weight::from_parts(23_716_894, 4706) + // Standard Error: 1_411 + .saturating_add(Weight::from_parts(31_936, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) } /// Storage: `Proxy::Proxies` (r:1 w:0) /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) @@ -76,18 +69,18 @@ impl WeightInfo for HydraWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `a` is `[0, 31]`. /// The range of component `p` is `[1, 31]`. - fn proxy_announced(a: u32, p: u32) -> Weight { + fn proxy_announced(a: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `620 + a * (68 ±0) + p * (37 ±0)` // Estimated: `5698` - // Minimum execution time: 51_590_000 picoseconds. - Weight::from_parts(50_716_699, 5698) - // Standard Error: 4_159 - .saturating_add(Weight::from_parts(178_083, 0).saturating_mul(a.into())) - // Standard Error: 4_325 - .saturating_add(Weight::from_parts(30_784, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 51_500_000 picoseconds. + Weight::from_parts(51_077_709, 5698) + // Standard Error: 2_902 + .saturating_add(Weight::from_parts(168_254, 0).saturating_mul(a.into())) + // Standard Error: 3_017 + .saturating_add(Weight::from_parts(29_333, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Proxy::Announcements` (r:1 w:1) /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) @@ -95,16 +88,16 @@ impl WeightInfo for HydraWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `a` is `[0, 31]`. /// The range of component `p` is `[1, 31]`. - fn remove_announcement(a: u32, _p: u32) -> Weight { + fn remove_announcement(a: u32, _p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `535 + a * (68 ±0)` // Estimated: `5698` - // Minimum execution time: 34_482_000 picoseconds. - Weight::from_parts(34_652_525, 5698) - // Standard Error: 4_201 - .saturating_add(Weight::from_parts(155_744, 0).saturating_mul(a.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 34_322_000 picoseconds. + Weight::from_parts(34_848_430, 5698) + // Standard Error: 2_484 + .saturating_add(Weight::from_parts(157_646, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Proxy::Announcements` (r:1 w:1) /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) @@ -112,16 +105,16 @@ impl WeightInfo for HydraWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `a` is `[0, 31]`. /// The range of component `p` is `[1, 31]`. - fn reject_announcement(a: u32, _p: u32) -> Weight { + fn reject_announcement(a: u32, _p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `535 + a * (68 ±0)` // Estimated: `5698` - // Minimum execution time: 34_516_000 picoseconds. - Weight::from_parts(34_407_038, 5698) - // Standard Error: 3_233 - .saturating_add(Weight::from_parts(163_369, 0).saturating_mul(a.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 34_010_000 picoseconds. + Weight::from_parts(34_723_018, 5698) + // Standard Error: 2_442 + .saturating_add(Weight::from_parts(164_732, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Proxy::Proxies` (r:1 w:0) /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) @@ -131,85 +124,87 @@ impl WeightInfo for HydraWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `a` is `[0, 31]`. /// The range of component `p` is `[1, 31]`. - fn announce(a: u32, p: u32) -> Weight { + fn announce(a: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `552 + a * (68 ±0) + p * (37 ±0)` // Estimated: `5698` - // Minimum execution time: 44_879_000 picoseconds. - Weight::from_parts(44_863_459, 5698) - // Standard Error: 2_277 - .saturating_add(Weight::from_parts(186_705, 0).saturating_mul(a.into())) - // Standard Error: 2_368 - .saturating_add(Weight::from_parts(25_596, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 46_184_000 picoseconds. + Weight::from_parts(45_983_861, 5698) + // Standard Error: 2_006 + .saturating_add(Weight::from_parts(172_287, 0).saturating_mul(a.into())) + // Standard Error: 2_086 + .saturating_add(Weight::from_parts(26_773, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Proxy::Proxies` (r:1 w:1) /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) /// The range of component `p` is `[1, 31]`. - fn add_proxy(p: u32) -> Weight { + fn add_proxy(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `293 + p * (37 ±0)` // Estimated: `4706` - // Minimum execution time: 34_980_000 picoseconds. - Weight::from_parts(35_443_005, 4706) - // Standard Error: 2_435 - .saturating_add(Weight::from_parts(30_168, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 35_158_000 picoseconds. + Weight::from_parts(35_671_577, 4706) + // Standard Error: 1_904 + .saturating_add(Weight::from_parts(43_085, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Proxy::Proxies` (r:1 w:1) /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) /// The range of component `p` is `[1, 31]`. - fn remove_proxy(_p: u32) -> Weight { + fn remove_proxy(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `293 + p * (37 ±0)` // Estimated: `4706` - // Minimum execution time: 35_573_000 picoseconds. - Weight::from_parts(36_596_298, 4706) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 35_277_000 picoseconds. + Weight::from_parts(36_469_179, 4706) + // Standard Error: 4_286 + .saturating_add(Weight::from_parts(13_586, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Proxy::Proxies` (r:1 w:1) /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) /// The range of component `p` is `[1, 31]`. - fn remove_proxies(p: u32) -> Weight { + fn remove_proxies(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `293 + p * (37 ±0)` // Estimated: `4706` - // Minimum execution time: 31_724_000 picoseconds. - Weight::from_parts(32_119_569, 4706) - // Standard Error: 2_666 - .saturating_add(Weight::from_parts(32_815, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 31_983_000 picoseconds. + Weight::from_parts(32_492_459, 4706) + // Standard Error: 1_600 + .saturating_add(Weight::from_parts(30_213, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Proxy::Proxies` (r:1 w:1) /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) /// The range of component `p` is `[1, 31]`. - fn create_pure(p: u32) -> Weight { + fn create_pure(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `305` // Estimated: `4706` - // Minimum execution time: 37_850_000 picoseconds. - Weight::from_parts(38_490_275, 4706) - // Standard Error: 2_156 - .saturating_add(Weight::from_parts(1_048, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 37_955_000 picoseconds. + Weight::from_parts(38_652_892, 4706) + // Standard Error: 2_122 + .saturating_add(Weight::from_parts(14_074, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Proxy::Proxies` (r:1 w:1) /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) /// The range of component `p` is `[0, 30]`. - fn kill_pure(p: u32) -> Weight { + fn kill_pure(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `330 + p * (37 ±0)` // Estimated: `4706` - // Minimum execution time: 32_796_000 picoseconds. - Weight::from_parts(33_380_258, 4706) - // Standard Error: 2_079 - .saturating_add(Weight::from_parts(29_420, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 32_767_000 picoseconds. + Weight::from_parts(33_326_886, 4706) + // Standard Error: 1_559 + .saturating_add(Weight::from_parts(38_563, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/referrals.rs b/runtime/hydradx/src/weights/referrals.rs index e28a17288..43620ecf6 100644 --- a/runtime/hydradx/src/weights/referrals.rs +++ b/runtime/hydradx/src/weights/referrals.rs @@ -18,7 +18,7 @@ //! Autogenerated weights for `pallet_referrals` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2024-01-09, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 @@ -33,26 +33,22 @@ // --wasm-execution=compiled // --heap-pages=4096 // --template=.maintain/pallet-weight-template-no-back.hbs -// --pallet=pallet-referrals -// --output=weights-1.1.0/referrals.rs +// --pallet=pallet_referrals +// --output=./weights/referrlas.rs // --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_referrals::weights::WeightInfo; -/// Weights for pallet_referrals using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_referrals`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `Referrals::ReferralAccounts` (r:1 w:1) /// Proof: `Referrals::ReferralAccounts` (`max_values`: None, `max_size`: Some(59), added: 2534, mode: `MaxEncodedLen`) @@ -66,8 +62,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `284` // Estimated: `6196` - // Minimum execution time: 64_118_000 picoseconds. - Weight::from_parts(64_600_000, 6196) + // Minimum execution time: 63_867_000 picoseconds. + Weight::from_parts(64_488_000, 6196) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(5)) } @@ -79,8 +75,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `194` // Estimated: `3545` - // Minimum execution time: 22_117_000 picoseconds. - Weight::from_parts(22_358_000, 3545) + // Minimum execution time: 21_841_000 picoseconds. + Weight::from_parts(22_151_000, 3545) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -96,8 +92,10 @@ impl WeightInfo for HydraWeight { /// Proof: `DynamicFees::AssetFee` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Oracles` (r:2 w:0) /// Proof: `EmaOracle::Oracles` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) /// Storage: `CircuitBreaker::AllowedTradeVolumeLimitPerAsset` (r:2 w:2) @@ -122,11 +120,11 @@ impl WeightInfo for HydraWeight { /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn convert() -> Weight { // Proof Size summary in bytes: - // Measured: `2105` + // Measured: `2088` // Estimated: `7406` - // Minimum execution time: 290_406_000 picoseconds. - Weight::from_parts(291_955_000, 7406) - .saturating_add(T::DbWeight::get().reads(24)) + // Minimum execution time: 295_663_000 picoseconds. + Weight::from_parts(297_036_000, 7406) + .saturating_add(T::DbWeight::get().reads(25)) .saturating_add(T::DbWeight::get().writes(15)) } /// Storage: `Referrals::PendingConversions` (r:1 w:0) @@ -145,8 +143,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `655` // Estimated: `6196` - // Minimum execution time: 88_340_000 picoseconds. - Weight::from_parts(89_429_000, 6196) + // Minimum execution time: 88_579_000 picoseconds. + Weight::from_parts(89_353_000, 6196) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(6)) } @@ -156,8 +154,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `42` // Estimated: `3514` - // Minimum execution time: 16_024_000 picoseconds. - Weight::from_parts(16_319_000, 3514) + // Minimum execution time: 15_398_000 picoseconds. + Weight::from_parts(15_676_000, 3514) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } diff --git a/runtime/hydradx/src/weights/registry.rs b/runtime/hydradx/src/weights/registry.rs index f52baaafe..26c0398c7 100644 --- a/runtime/hydradx/src/weights/registry.rs +++ b/runtime/hydradx/src/weights/registry.rs @@ -15,11 +15,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Autogenerated weights for pallet_asset_registry +//! Autogenerated weights for `pallet_asset_registry` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-04, STEPS: 10, REPEAT: 30, LOW RANGE: [], HIGH RANGE: [] -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx @@ -28,90 +30,101 @@ // --chain=dev // --steps=10 // --repeat=30 -// --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 // --template=.maintain/pallet-weight-template-no-back.hbs // --pallet=pallet_asset_registry -// --output=registry.rs +// --output=./weights/registry.rs // --extrinsic=* +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_asset_registry::weights::WeightInfo; -/// Weights for pallet_asset_registry using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_asset_registry`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { - // Storage: AssetRegistry Assets (r:1 w:1) - // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) - // Storage: AssetRegistry AssetIds (r:1 w:1) - // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) - // Storage: AssetRegistry LocationAssets (r:1 w:1) - // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) - // Storage: AssetRegistry AssetLocations (r:0 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) + /// Storage: `AssetRegistry::Assets` (r:1 w:1) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::AssetIds` (r:1 w:1) + /// Proof: `AssetRegistry::AssetIds` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::LocationAssets` (r:1 w:1) + /// Proof: `AssetRegistry::LocationAssets` (`max_values`: None, `max_size`: Some(622), added: 3097, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::AssetLocations` (r:0 w:1) + /// Proof: `AssetRegistry::AssetLocations` (`max_values`: None, `max_size`: Some(622), added: 3097, mode: `MaxEncodedLen`) fn register() -> Weight { - // Minimum execution time: 40_681 nanoseconds. - Weight::from_parts(41_321_000, 0) - .saturating_add(T::DbWeight::get().reads(3 as u64)) - .saturating_add(T::DbWeight::get().writes(4 as u64)) + // Proof Size summary in bytes: + // Measured: `322` + // Estimated: `4087` + // Minimum execution time: 40_579_000 picoseconds. + Weight::from_parts(41_148_000, 4087) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(4)) } - // Storage: AssetRegistry Assets (r:1 w:1) - // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) - // Storage: AssetRegistry AssetIds (r:1 w:2) - // Proof: AssetRegistry AssetIds (max_values: None, max_size: Some(53), added: 2528, mode: MaxEncodedLen) - // Storage: AssetRegistry AssetLocations (r:1 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) - // Storage: AssetRegistry LocationAssets (r:0 w:1) - // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) + /// Storage: `AssetRegistry::Assets` (r:1 w:1) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::AssetIds` (r:1 w:2) + /// Proof: `AssetRegistry::AssetIds` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::AssetLocations` (r:1 w:1) + /// Proof: `AssetRegistry::AssetLocations` (`max_values`: None, `max_size`: Some(622), added: 3097, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::LocationAssets` (r:0 w:1) + /// Proof: `AssetRegistry::LocationAssets` (`max_values`: None, `max_size`: Some(622), added: 3097, mode: `MaxEncodedLen`) fn update() -> Weight { - // Minimum execution time: 49_934 nanoseconds. - Weight::from_parts(50_392_000, 0) - .saturating_add(T::DbWeight::get().reads(3 as u64)) - .saturating_add(T::DbWeight::get().writes(5 as u64)) + // Proof Size summary in bytes: + // Measured: `551` + // Estimated: `4087` + // Minimum execution time: 48_132_000 picoseconds. + Weight::from_parts(48_483_000, 4087) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(5)) } - // Storage: System Account (r:2 w:2) - // Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - // Storage: AssetRegistry NextAssetId (r:1 w:1) - // Proof: AssetRegistry NextAssetId (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - // Storage: AssetRegistry LocationAssets (r:1 w:1) - // Proof: AssetRegistry LocationAssets (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) - // Storage: AssetRegistry AssetLocations (r:0 w:1) - // Proof: AssetRegistry AssetLocations (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) - // Storage: AssetRegistry Assets (r:0 w:1) - // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::NextAssetId` (r:1 w:1) + /// Proof: `AssetRegistry::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::LocationAssets` (r:1 w:1) + /// Proof: `AssetRegistry::LocationAssets` (`max_values`: None, `max_size`: Some(622), added: 3097, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::AssetLocations` (r:0 w:1) + /// Proof: `AssetRegistry::AssetLocations` (`max_values`: None, `max_size`: Some(622), added: 3097, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:0 w:1) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) fn register_external() -> Weight { - // Minimum execution time: 62_510 nanoseconds. - Weight::from_parts(63_275_000, 0) - .saturating_add(T::DbWeight::get().reads(4 as u64)) - .saturating_add(T::DbWeight::get().writes(6 as u64)) + // Proof Size summary in bytes: + // Measured: `477` + // Estimated: `6196` + // Minimum execution time: 80_033_000 picoseconds. + Weight::from_parts(80_684_000, 6196) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(6)) } - // Storage: AssetRegistry Assets (r:1 w:0) - // Proof: AssetRegistry Assets (max_values: None, max_size: Some(125), added: 2600, mode: MaxEncodedLen) - // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) - // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) + /// Storage: `AssetRegistry::Assets` (r:1 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:1) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) fn ban_asset() -> Weight { - // Minimum execution time: 22_677 nanoseconds. - Weight::from_parts(22_950_000, 0) - .saturating_add(T::DbWeight::get().reads(2 as u64)) - .saturating_add(T::DbWeight::get().writes(1 as u64)) + // Proof Size summary in bytes: + // Measured: `361` + // Estimated: `3590` + // Minimum execution time: 21_799_000 picoseconds. + Weight::from_parts(22_232_000, 3590) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } - // Storage: AssetRegistry BlacklistedAssets (r:1 w:1) - // Proof: AssetRegistry BlacklistedAssets (max_values: None, max_size: Some(20), added: 2495, mode: MaxEncodedLen) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:1) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) fn unban_asset() -> Weight { - // Minimum execution time: 17_460 nanoseconds. - Weight::from_parts(17_958_000, 0) - .saturating_add(T::DbWeight::get().reads(1 as u64)) - .saturating_add(T::DbWeight::get().writes(1 as u64)) + // Proof Size summary in bytes: + // Measured: `254` + // Estimated: `3485` + // Minimum execution time: 18_853_000 picoseconds. + Weight::from_parts(19_166_000, 3485) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } } diff --git a/runtime/hydradx/src/weights/route_executor.rs b/runtime/hydradx/src/weights/route_executor.rs index 8dc7fe923..b61909e67 100644 --- a/runtime/hydradx/src/weights/route_executor.rs +++ b/runtime/hydradx/src/weights/route_executor.rs @@ -18,42 +18,37 @@ //! Autogenerated weights for `pallet_route_executor` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-route-executor +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet-route-executor +// --output=./weights/route_executor.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/route_executor.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_route_executor::weights::WeightInfo; -/// Weights for pallet_route_executor using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_route_executor`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `LBP::PoolData` (r:1 w:0) /// Proof: `LBP::PoolData` (`max_values`: None, `max_size`: Some(163), added: 2638, mode: `MaxEncodedLen`) @@ -63,19 +58,23 @@ impl WeightInfo for HydraWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Tokens::Locks` (r:1 w:1) /// Proof: `Tokens::Locks` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// The range of component `c` is `[0, 1]`. - fn calculate_and_execute_sell_in_lbp(c: u32) -> Weight { + fn calculate_and_execute_sell_in_lbp(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `3016` + // Measured: `3402` // Estimated: `13905` - // Minimum execution time: 316_311_000 picoseconds. - Weight::from_parts(318_353_450, 13905) - // Standard Error: 164_994 - .saturating_add(Weight::from_parts(50_546_750, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(12_u64)) - .saturating_add(T::DbWeight::get().writes(7_u64)) + // Minimum execution time: 342_380_000 picoseconds. + Weight::from_parts(344_960_058, 13905) + // Standard Error: 141_835 + .saturating_add(Weight::from_parts(50_412_253, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(16)) + .saturating_add(T::DbWeight::get().writes(7)) } /// Storage: `LBP::PoolData` (r:1 w:0) /// Proof: `LBP::PoolData` (`max_values`: None, `max_size`: Some(163), added: 2638, mode: `MaxEncodedLen`) @@ -85,22 +84,26 @@ impl WeightInfo for HydraWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Tokens::Locks` (r:1 w:1) /// Proof: `Tokens::Locks` (`max_values`: None, `max_size`: Some(1261), added: 3736, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// The range of component `c` is `[1, 2]`. /// The range of component `b` is `[0, 1]`. - fn calculate_and_execute_buy_in_lbp(c: u32, b: u32) -> Weight { + fn calculate_and_execute_buy_in_lbp(c: u32, b: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1567 + b * (1418 ±0)` - // Estimated: `6156 + b * (7749 ±0)` - // Minimum execution time: 75_646_000 picoseconds. - Weight::from_parts(76_052_000, 6156) - // Standard Error: 1_389_058 - .saturating_add(Weight::from_parts(4_096_946, 0).saturating_mul(c.into())) - // Standard Error: 3_000_708 - .saturating_add(Weight::from_parts(250_139_938, 0).saturating_mul(b.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().reads((9_u64).saturating_mul(b.into()))) + // Measured: `1571 + b * (1836 ±0)` + // Estimated: `6156 + b * (7749 ±245_709_589_663_843_264)` + // Minimum execution time: 75_535_000 picoseconds. + Weight::from_parts(76_397_000, 6156) + // Standard Error: 600_512 + .saturating_add(Weight::from_parts(2_328_934, 0).saturating_mul(c.into())) + // Standard Error: 1_318_297 + .saturating_add(Weight::from_parts(272_259_348, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().reads((13_u64).saturating_mul(b.into()))) .saturating_add(T::DbWeight::get().writes((7_u64).saturating_mul(b.into()))) .saturating_add(Weight::from_parts(0, 7749).saturating_mul(b.into())) } @@ -108,27 +111,37 @@ impl WeightInfo for HydraWeight { /// Proof: `Router::Routes` (`max_values`: None, `max_size`: Some(90), added: 2565, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:9 w:0) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:5 w:0) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:2 w:0) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:3 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:4 w:0) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:3 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:0) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:0) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:3 w:0) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `XYK::ShareToken` (r:3 w:0) /// Proof: `XYK::ShareToken` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:4 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:0) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) fn set_route_for_xyk() -> Weight { // Proof Size summary in bytes: - // Measured: `4201` + // Measured: `4957` // Estimated: `24237` - // Minimum execution time: 1_126_027_000 picoseconds. - Weight::from_parts(1_133_155_000, 24237) - .saturating_add(T::DbWeight::get().reads(27_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 2_485_264_000 picoseconds. + Weight::from_parts(2_495_249_000, 24237) + .saturating_add(T::DbWeight::get().reads(38)) + .saturating_add(T::DbWeight::get().writes(1)) } } diff --git a/runtime/hydradx/src/weights/scheduler.rs b/runtime/hydradx/src/weights/scheduler.rs index ea11e8d37..d39faa62a 100644 --- a/runtime/hydradx/src/weights/scheduler.rs +++ b/runtime/hydradx/src/weights/scheduler.rs @@ -18,90 +18,83 @@ //! Autogenerated weights for `pallet_scheduler` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-scheduler +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_scheduler +// --output=./weights/scheduler.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/scheduler.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_scheduler::weights::WeightInfo; - -/// Weights for pallet_scheduler using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_scheduler`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_scheduler::WeightInfo for HydraWeight { /// Storage: `Scheduler::IncompleteSince` (r:1 w:1) /// Proof: `Scheduler::IncompleteSince` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn service_agendas_base() -> Weight { // Proof Size summary in bytes: // Measured: `31` // Estimated: `1489` - // Minimum execution time: 4_643_000 picoseconds. - Weight::from_parts(4_787_000, 1489) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 4_766_000 picoseconds. + Weight::from_parts(4_908_000, 1489) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Scheduler::Agenda` (r:1 w:1) /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(38963), added: 41438, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 50]`. - fn service_agenda_base(s: u32) -> Weight { + fn service_agenda_base(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `78 + s * (177 ±0)` // Estimated: `42428` - // Minimum execution time: 4_686_000 picoseconds. - Weight::from_parts(6_756_919, 42428) - // Standard Error: 11_265 - .saturating_add(Weight::from_parts(959_261, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 4_580_000 picoseconds. + Weight::from_parts(7_795_367, 42428) + // Standard Error: 6_252 + .saturating_add(Weight::from_parts(905_945, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } fn service_task_base() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_940_000 picoseconds. - Weight::from_parts(8_088_000, 0) + // Minimum execution time: 8_057_000 picoseconds. + Weight::from_parts(8_214_000, 0) } /// Storage: `Preimage::PreimageFor` (r:1 w:1) /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `Measured`) /// Storage: `Preimage::StatusFor` (r:1 w:1) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// The range of component `s` is `[128, 4194304]`. - fn service_task_fetched(s: u32) -> Weight { + fn service_task_fetched(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `246 + s * (1 ±0)` - // Estimated: `3708 + s * (1 ±0)` - // Minimum execution time: 27_177_000 picoseconds. - Weight::from_parts(16_696_892, 3708) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_259, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Estimated: `3709 + s * (1 ±0)` + // Minimum execution time: 27_147_000 picoseconds. + Weight::from_parts(27_475_000, 3709) + // Standard Error: 19 + .saturating_add(Weight::from_parts(1_397, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(s.into())) } /// Storage: `Scheduler::Lookup` (r:0 w:1) @@ -110,90 +103,91 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 10_369_000 picoseconds. - Weight::from_parts(10_613_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 10_368_000 picoseconds. + Weight::from_parts(10_520_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } fn service_task_periodic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_045_000 picoseconds. - Weight::from_parts(8_135_000, 0) + // Minimum execution time: 7_981_000 picoseconds. + Weight::from_parts(8_201_000, 0) } fn execute_dispatch_signed() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_361_000 picoseconds. - Weight::from_parts(4_491_000, 0) + // Minimum execution time: 4_335_000 picoseconds. + Weight::from_parts(4_499_000, 0) } fn execute_dispatch_unsigned() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_376_000 picoseconds. - Weight::from_parts(4_505_000, 0) + // Minimum execution time: 4_214_000 picoseconds. + Weight::from_parts(4_391_000, 0) } /// Storage: `Scheduler::Agenda` (r:1 w:1) /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(38963), added: 41438, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 49]`. - fn schedule(s: u32) -> Weight { + fn schedule(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `78 + s * (177 ±0)` // Estimated: `42428` - // Minimum execution time: 18_064_000 picoseconds. - Weight::from_parts(20_065_367, 42428) - // Standard Error: 10_260 - .saturating_add(Weight::from_parts(953_244, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 17_694_000 picoseconds. + Weight::from_parts(21_031_139, 42428) + // Standard Error: 6_108 + .saturating_add(Weight::from_parts(896_821, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Scheduler::Agenda` (r:1 w:1) /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(38963), added: 41438, mode: `MaxEncodedLen`) /// Storage: `Scheduler::Lookup` (r:0 w:1) /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) /// The range of component `s` is `[1, 50]`. - fn cancel(s: u32) -> Weight { + fn cancel(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `78 + s * (177 ±0)` // Estimated: `42428` - // Minimum execution time: 24_575_000 picoseconds. - Weight::from_parts(23_596_290, 42428) - // Standard Error: 6_439 - .saturating_add(Weight::from_parts(1_644_619, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 24_274_000 picoseconds. + Weight::from_parts(23_345_538, 42428) + // Standard Error: 1_887 + .saturating_add(Weight::from_parts(1_577_518, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Scheduler::Lookup` (r:1 w:1) /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) /// Storage: `Scheduler::Agenda` (r:1 w:1) /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(38963), added: 41438, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 49]`. - fn schedule_named(s: u32) -> Weight { + fn schedule_named(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `148 + s * (188 ±0)` + // Measured: `192 + s * (187 ±0)` // Estimated: `42428` - // Minimum execution time: 22_396_000 picoseconds. - Weight::from_parts(25_018_609, 42428) - // Standard Error: 12_955 - .saturating_add(Weight::from_parts(1_010_928, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 22_839_000 picoseconds. + Weight::from_parts(26_341_432, 42428) + // Standard Error: 6_685 + .saturating_add(Weight::from_parts(941_746, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Scheduler::Lookup` (r:1 w:1) /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) /// Storage: `Scheduler::Agenda` (r:1 w:1) /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(38963), added: 41438, mode: `MaxEncodedLen`) /// The range of component `s` is `[1, 50]`. - fn cancel_named(s: u32) -> Weight { + fn cancel_named(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `277 + s * (185 ±0)` + // Measured: `263 + s * (186 ±0)` // Estimated: `42428` - // Minimum execution time: 26_539_000 picoseconds. - Weight::from_parts(25_956_508, 42428) - // Standard Error: 4_676 - .saturating_add(Weight::from_parts(1_656_608, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 26_360_000 picoseconds. + Weight::from_parts(25_724_190, 42428) + // Standard Error: 3_550 + .saturating_add(Weight::from_parts(1_590_016, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/stableswap.rs b/runtime/hydradx/src/weights/stableswap.rs index 60d676438..d507ae37e 100644 --- a/runtime/hydradx/src/weights/stableswap.rs +++ b/runtime/hydradx/src/weights/stableswap.rs @@ -1,5 +1,4 @@ // This file is part of HydraDX. -// This file is part of HydraDX. // Copyright (C) 2020-2023 Intergalactic, Limited (GIB). // SPDX-License-Identifier: Apache-2.0 @@ -19,7 +18,7 @@ //! Autogenerated weights for `pallet_stableswap` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-18, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 @@ -34,8 +33,8 @@ // --wasm-execution=compiled // --heap-pages=4096 // --template=.maintain/pallet-weight-template-no-back.hbs -// --pallet=pallet-stableswap -// --output=weights-1.1.0/stableswap.rs +// --pallet=pallet_stableswap +// --output=./weights/stableswap.rs // --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] @@ -43,30 +42,26 @@ #![allow(unused_imports)] #![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_stableswap::weights::WeightInfo; -/// Weights for pallet_stableswap using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_stableswap`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `Stableswap::Pools` (r:1 w:1) /// Proof: `Stableswap::Pools` (`max_values`: None, `max_size`: Some(57), added: 2532, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:6 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Duster::AccountBlacklist` (r:0 w:1) /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) fn create_pool() -> Weight { // Proof Size summary in bytes: - // Measured: `717` - // Estimated: `16362` - // Minimum execution time: 52_498_000 picoseconds. - Weight::from_parts(52_992_000, 16362) + // Measured: `789` + // Estimated: `16590` + // Minimum execution time: 53_155_000 picoseconds. + Weight::from_parts(53_722_000, 16590) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -76,54 +71,60 @@ impl WeightInfo for HydraWeight { /// Proof: `Stableswap::AssetTradability` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:11 w:11) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::AssetMetadataMap` (r:5 w:0) - /// Proof: `AssetRegistry::AssetMetadataMap` (`max_values`: None, `max_size`: Some(46), added: 2521, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:6 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:6 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:6 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) fn add_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `3168` + // Measured: `3339` // Estimated: `29403` - // Minimum execution time: 1_087_109_000 picoseconds. - Weight::from_parts(1_090_256_000, 29403) - .saturating_add(T::DbWeight::get().reads(33)) + // Minimum execution time: 1_155_933_000 picoseconds. + Weight::from_parts(1_159_202_000, 29403) + .saturating_add(T::DbWeight::get().reads(35)) .saturating_add(T::DbWeight::get().writes(14)) } + /// Storage: `Stableswap::AssetTradability` (r:1 w:0) + /// Proof: `Stableswap::AssetTradability` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) /// Storage: `Stableswap::Pools` (r:1 w:0) /// Proof: `Stableswap::Pools` (`max_values`: None, `max_size`: Some(57), added: 2532, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:7 w:3) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::AssetMetadataMap` (r:5 w:0) - /// Proof: `AssetRegistry::AssetMetadataMap` (`max_values`: None, `max_size`: Some(46), added: 2521, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:6 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) fn add_liquidity_shares() -> Weight { // Proof Size summary in bytes: - // Measured: `3014` + // Measured: `3207` // Estimated: `19071` - // Minimum execution time: 739_668_000 picoseconds. - Weight::from_parts(743_517_000, 19071) - .saturating_add(T::DbWeight::get().reads(20)) + // Minimum execution time: 775_198_000 picoseconds. + Weight::from_parts(779_737_000, 19071) + .saturating_add(T::DbWeight::get().reads(23)) .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `Stableswap::AssetTradability` (r:1 w:0) @@ -132,14 +133,16 @@ impl WeightInfo for HydraWeight { /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `Stableswap::Pools` (r:1 w:0) /// Proof: `Stableswap::Pools` (`max_values`: None, `max_size`: Some(57), added: 2532, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::AssetMetadataMap` (r:5 w:0) - /// Proof: `AssetRegistry::AssetMetadataMap` (`max_values`: None, `max_size`: Some(46), added: 2521, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:6 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) @@ -148,11 +151,11 @@ impl WeightInfo for HydraWeight { /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn remove_liquidity_one_asset() -> Weight { // Proof Size summary in bytes: - // Measured: `3017` + // Measured: `3231` // Estimated: `19071` - // Minimum execution time: 777_557_000 picoseconds. - Weight::from_parts(781_094_000, 19071) - .saturating_add(T::DbWeight::get().reads(21)) + // Minimum execution time: 807_519_000 picoseconds. + Weight::from_parts(811_614_000, 19071) + .saturating_add(T::DbWeight::get().reads(22)) .saturating_add(T::DbWeight::get().writes(7)) } /// Storage: `Stableswap::AssetTradability` (r:1 w:0) @@ -161,12 +164,14 @@ impl WeightInfo for HydraWeight { /// Proof: `Stableswap::Pools` (`max_values`: None, `max_size`: Some(57), added: 2532, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:7 w:3) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::AssetMetadataMap` (r:5 w:0) - /// Proof: `AssetRegistry::AssetMetadataMap` (`max_values`: None, `max_size`: Some(46), added: 2521, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:6 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:1 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) @@ -177,11 +182,11 @@ impl WeightInfo for HydraWeight { /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) fn withdraw_asset_amount() -> Weight { // Proof Size summary in bytes: - // Measured: `3017` + // Measured: `3231` // Estimated: `19071` - // Minimum execution time: 1_041_027_000 picoseconds. - Weight::from_parts(1_050_193_000, 19071) - .saturating_add(T::DbWeight::get().reads(22)) + // Minimum execution time: 1_061_520_000 picoseconds. + Weight::from_parts(1_068_689_000, 19071) + .saturating_add(T::DbWeight::get().reads(23)) .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `Stableswap::AssetTradability` (r:2 w:0) @@ -190,10 +195,12 @@ impl WeightInfo for HydraWeight { /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `Stableswap::Pools` (r:1 w:0) /// Proof: `Stableswap::Pools` (`max_values`: None, `max_size`: Some(57), added: 2532, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::AssetMetadataMap` (r:5 w:0) - /// Proof: `AssetRegistry::AssetMetadataMap` (`max_values`: None, `max_size`: Some(46), added: 2521, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:5 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) @@ -206,11 +213,11 @@ impl WeightInfo for HydraWeight { /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn sell() -> Weight { // Proof Size summary in bytes: - // Measured: `3043` + // Measured: `3269` // Estimated: `19071` - // Minimum execution time: 730_301_000 picoseconds. - Weight::from_parts(735_887_000, 19071) - .saturating_add(T::DbWeight::get().reads(22)) + // Minimum execution time: 767_301_000 picoseconds. + Weight::from_parts(771_963_000, 19071) + .saturating_add(T::DbWeight::get().reads(24)) .saturating_add(T::DbWeight::get().writes(7)) } /// Storage: `Stableswap::AssetTradability` (r:2 w:0) @@ -219,10 +226,12 @@ impl WeightInfo for HydraWeight { /// Proof: `Stableswap::Pools` (`max_values`: None, `max_size`: Some(57), added: 2532, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:7 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::AssetMetadataMap` (r:5 w:0) - /// Proof: `AssetRegistry::AssetMetadataMap` (`max_values`: None, `max_size`: Some(46), added: 2521, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:5 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) @@ -235,11 +244,11 @@ impl WeightInfo for HydraWeight { /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) fn buy() -> Weight { // Proof Size summary in bytes: - // Measured: `3013` + // Measured: `3239` // Estimated: `19071` - // Minimum execution time: 710_874_000 picoseconds. - Weight::from_parts(714_006_000, 19071) - .saturating_add(T::DbWeight::get().reads(23)) + // Minimum execution time: 745_716_000 picoseconds. + Weight::from_parts(748_811_000, 19071) + .saturating_add(T::DbWeight::get().reads(25)) .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `Stableswap::Pools` (r:1 w:0) @@ -250,8 +259,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `291` // Estimated: `3522` - // Minimum execution time: 25_547_000 picoseconds. - Weight::from_parts(25_951_000, 3522) + // Minimum execution time: 25_044_000 picoseconds. + Weight::from_parts(25_584_000, 3522) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -261,8 +270,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `291` // Estimated: `3522` - // Minimum execution time: 23_026_000 picoseconds. - Weight::from_parts(23_457_000, 3522) + // Minimum execution time: 22_703_000 picoseconds. + Weight::from_parts(23_093_000, 3522) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -272,8 +281,8 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `291` // Estimated: `3522` - // Minimum execution time: 24_839_000 picoseconds. - Weight::from_parts(25_332_000, 3522) + // Minimum execution time: 24_632_000 picoseconds. + Weight::from_parts(24_919_000, 3522) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -281,12 +290,14 @@ impl WeightInfo for HydraWeight { /// Proof: `Stableswap::Pools` (`max_values`: None, `max_size`: Some(57), added: 2532, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:7 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::AssetMetadataMap` (r:5 w:0) - /// Proof: `AssetRegistry::AssetMetadataMap` (`max_values`: None, `max_size`: Some(46), added: 2521, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:5 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Stableswap::AssetTradability` (r:2 w:0) /// Proof: `Stableswap::AssetTradability` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) @@ -301,14 +312,14 @@ impl WeightInfo for HydraWeight { /// The range of component `e` is `[0, 1]`. fn router_execution_sell(_c: u32, e: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1276 + e * (1767 ±0)` - // Estimated: `13905 + e * (5797 ±124_823_812_913_251_024)` - // Minimum execution time: 305_934_000 picoseconds. - Weight::from_parts(312_030_194, 13905) - // Standard Error: 324_777 - .saturating_add(Weight::from_parts(704_923_524, 0).saturating_mul(e.into())) + // Measured: `1555 + e * (1714 ±0)` + // Estimated: `13990 + e * (5797 ±245_709_589_663_843_264)` + // Minimum execution time: 314_654_000 picoseconds. + Weight::from_parts(321_208_138, 13990) + // Standard Error: 305_814 + .saturating_add(Weight::from_parts(731_985_555, 0).saturating_mul(e.into())) .saturating_add(T::DbWeight::get().reads(11)) - .saturating_add(T::DbWeight::get().reads((11_u64).saturating_mul(e.into()))) + .saturating_add(T::DbWeight::get().reads((13_u64).saturating_mul(e.into()))) .saturating_add(T::DbWeight::get().writes((7_u64).saturating_mul(e.into()))) .saturating_add(Weight::from_parts(0, 5797).saturating_mul(e.into())) } @@ -316,12 +327,14 @@ impl WeightInfo for HydraWeight { /// Proof: `Stableswap::Pools` (`max_values`: None, `max_size`: Some(57), added: 2532, mode: `MaxEncodedLen`) /// Storage: `Tokens::Accounts` (r:7 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::AssetMetadataMap` (r:5 w:0) - /// Proof: `AssetRegistry::AssetMetadataMap` (`max_values`: None, `max_size`: Some(46), added: 2521, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:5 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Stableswap::AssetTradability` (r:2 w:0) /// Proof: `Stableswap::AssetTradability` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) @@ -336,16 +349,16 @@ impl WeightInfo for HydraWeight { /// The range of component `e` is `[0, 1]`. fn router_execution_buy(c: u32, e: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1275 + e * (1738 ±0)` - // Estimated: `13905 + e * (5797 ±201_913_854_157_949_888)` - // Minimum execution time: 304_954_000 picoseconds. - Weight::from_parts(306_226_000, 13905) - // Standard Error: 3_224_854 - .saturating_add(Weight::from_parts(12_176_535, 0).saturating_mul(c.into())) - // Standard Error: 7_079_475 - .saturating_add(Weight::from_parts(445_329_428, 0).saturating_mul(e.into())) + // Measured: `1554 + e * (1685 ±0)` + // Estimated: `13990 + e * (5797 ±201_913_854_157_949_888)` + // Minimum execution time: 312_997_000 picoseconds. + Weight::from_parts(314_359_000, 13990) + // Standard Error: 3_248_945 + .saturating_add(Weight::from_parts(12_345_948, 0).saturating_mul(c.into())) + // Standard Error: 7_132_362 + .saturating_add(Weight::from_parts(468_057_036, 0).saturating_mul(e.into())) .saturating_add(T::DbWeight::get().reads(11)) - .saturating_add(T::DbWeight::get().reads((12_u64).saturating_mul(e.into()))) + .saturating_add(T::DbWeight::get().reads((14_u64).saturating_mul(e.into()))) .saturating_add(T::DbWeight::get().writes((6_u64).saturating_mul(e.into()))) .saturating_add(Weight::from_parts(0, 5797).saturating_mul(e.into())) } diff --git a/runtime/hydradx/src/weights/staking.rs b/runtime/hydradx/src/weights/staking.rs index 35b209837..818119012 100644 --- a/runtime/hydradx/src/weights/staking.rs +++ b/runtime/hydradx/src/weights/staking.rs @@ -18,43 +18,36 @@ //! Autogenerated weights for `pallet_staking` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-staking +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_staking +// --output=./weights/staking.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/staking.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_staking::weights::WeightInfo; - -/// Weights for pallet_staking using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_staking`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_staking::WeightInfo for HydraWeight { /// Storage: `Staking::Staking` (r:1 w:1) /// Proof: `Staking::Staking` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:0) @@ -67,10 +60,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `513` // Estimated: `3655` - // Minimum execution time: 46_433_000 picoseconds. - Weight::from_parts(47_121_000, 3655) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 45_589_000 picoseconds. + Weight::from_parts(46_388_000, 3655) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `Staking::Staking` (r:1 w:1) /// Proof: `Staking::Staking` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) @@ -96,10 +89,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `1240` // Estimated: `6196` - // Minimum execution time: 113_477_000 picoseconds. - Weight::from_parts(114_557_000, 6196) - .saturating_add(T::DbWeight::get().reads(10_u64)) - .saturating_add(T::DbWeight::get().writes(8_u64)) + // Minimum execution time: 112_917_000 picoseconds. + Weight::from_parts(113_568_000, 6196) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(8)) } /// Storage: `Staking::Staking` (r:1 w:1) /// Proof: `Staking::Staking` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) @@ -121,10 +114,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `3379` // Estimated: `268590` - // Minimum execution time: 297_204_000 picoseconds. - Weight::from_parts(300_714_000, 268590) - .saturating_add(T::DbWeight::get().reads(108_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) + // Minimum execution time: 293_910_000 picoseconds. + Weight::from_parts(296_894_000, 268590) + .saturating_add(T::DbWeight::get().reads(108)) + .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `Staking::Staking` (r:1 w:1) /// Proof: `Staking::Staking` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) @@ -146,10 +139,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `3379` // Estimated: `268590` - // Minimum execution time: 291_136_000 picoseconds. - Weight::from_parts(294_313_000, 268590) - .saturating_add(T::DbWeight::get().reads(108_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) + // Minimum execution time: 286_701_000 picoseconds. + Weight::from_parts(288_861_000, 268590) + .saturating_add(T::DbWeight::get().reads(108)) + .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `Staking::Staking` (r:1 w:1) /// Proof: `Staking::Staking` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) @@ -177,9 +170,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `3598` // Estimated: `268590` - // Minimum execution time: 330_733_000 picoseconds. - Weight::from_parts(334_301_000, 268590) - .saturating_add(T::DbWeight::get().reads(109_u64)) - .saturating_add(T::DbWeight::get().writes(10_u64)) + // Minimum execution time: 321_948_000 picoseconds. + Weight::from_parts(324_370_000, 268590) + .saturating_add(T::DbWeight::get().reads(109)) + .saturating_add(T::DbWeight::get().writes(10)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/system.rs b/runtime/hydradx/src/weights/system.rs index 238cd887f..57270ed7c 100644 --- a/runtime/hydradx/src/weights/system.rs +++ b/runtime/hydradx/src/weights/system.rs @@ -18,62 +18,55 @@ //! Autogenerated weights for `frame_system` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=frame-system +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=frame-system +// --output=./weights/system.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/system.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +#![allow(missing_docs)] -use frame_system::weights::WeightInfo; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -/// Weights for frame_system using the hydraDX node and recommended hardware. +/// Weight functions for `frame_system`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl frame_system::WeightInfo for HydraWeight { /// The range of component `b` is `[0, 3932160]`. - fn remark(b: u32) -> Weight { + fn remark(b: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_478_000 picoseconds. - Weight::from_parts(3_592_000, 0) + // Minimum execution time: 3_612_000 picoseconds. + Weight::from_parts(3_700_000, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(411, 0).saturating_mul(b.into())) + .saturating_add(Weight::from_parts(406, 0).saturating_mul(b.into())) } /// The range of component `b` is `[0, 3932160]`. - fn remark_with_event(b: u32) -> Weight { + fn remark_with_event(b: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 11_351_000 picoseconds. - Weight::from_parts(11_460_000, 0) + // Minimum execution time: 11_260_000 picoseconds. + Weight::from_parts(11_496_000, 0) // Standard Error: 1 - .saturating_add(Weight::from_parts(1_443, 0).saturating_mul(b.into())) + .saturating_add(Weight::from_parts(1_444, 0).saturating_mul(b.into())) } /// Storage: `System::Digest` (r:1 w:1) /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) @@ -83,10 +76,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `1485` - // Minimum execution time: 6_633_000 picoseconds. - Weight::from_parts(6_863_000, 1485) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 6_621_000 picoseconds. + Weight::from_parts(6_809_000, 1485) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `ParachainSystem::ValidationData` (r:1 w:0) /// Proof: `ParachainSystem::ValidationData` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) @@ -104,50 +97,50 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `198` // Estimated: `1683` - // Minimum execution time: 119_638_616_000 picoseconds. - Weight::from_parts(121_649_253_000, 1683) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 117_242_692_000 picoseconds. + Weight::from_parts(118_784_037_000, 1683) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `i` is `[0, 1000]`. - fn set_storage(i: u32) -> Weight { + fn set_storage(i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_817_000 picoseconds. - Weight::from_parts(3_879_000, 0) - // Standard Error: 8_053 - .saturating_add(Weight::from_parts(944_155, 0).saturating_mul(i.into())) + // Minimum execution time: 3_808_000 picoseconds. + Weight::from_parts(3_867_000, 0) + // Standard Error: 3_843 + .saturating_add(Weight::from_parts(894_266, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `i` is `[0, 1000]`. - fn kill_storage(i: u32) -> Weight { + fn kill_storage(i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_690_000 picoseconds. - Weight::from_parts(3_824_000, 0) - // Standard Error: 2_460 - .saturating_add(Weight::from_parts(642_858, 0).saturating_mul(i.into())) + // Minimum execution time: 3_791_000 picoseconds. + Weight::from_parts(3_854_000, 0) + // Standard Error: 1_362 + .saturating_add(Weight::from_parts(614_354, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `p` is `[0, 1000]`. - fn kill_prefix(p: u32) -> Weight { + fn kill_prefix(p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `194 + p * (69 ±0)` - // Estimated: `148 + p * (70 ±0)` - // Minimum execution time: 7_319_000 picoseconds. - Weight::from_parts(7_381_000, 148) - // Standard Error: 2_908 - .saturating_add(Weight::from_parts(1_100_356, 0).saturating_mul(p.into())) + // Measured: `119 + p * (69 ±0)` + // Estimated: `130 + p * (70 ±0)` + // Minimum execution time: 7_002_000 picoseconds. + Weight::from_parts(7_100_000, 130) + // Standard Error: 1_619 + .saturating_add(Weight::from_parts(1_101_962, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) .saturating_add(Weight::from_parts(0, 70).saturating_mul(p.into())) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/technical_committee.rs b/runtime/hydradx/src/weights/technical_committee.rs index 78bba68bf..f8e7d2eb2 100644 --- a/runtime/hydradx/src/weights/technical_committee.rs +++ b/runtime/hydradx/src/weights/technical_committee.rs @@ -18,42 +18,37 @@ //! Autogenerated weights for `tech` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=tech +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=tech +// --output=./weights/technical_committee.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/technical_committee.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_collective::WeightInfo; -/// Weights for tech using the hydraDX node and recommended hardware. +/// Weight functions for `tech`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `TechnicalCommittee::Members` (r:1 w:1) /// Proof: `TechnicalCommittee::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) @@ -66,40 +61,38 @@ impl WeightInfo for HydraWeight { /// The range of component `m` is `[0, 10]`. /// The range of component `n` is `[0, 10]`. /// The range of component `p` is `[0, 20]`. - fn set_members(m: u32, _n: u32, p: u32) -> Weight { + fn set_members(m: u32, _n: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `0 + m * (666 ±0) + p * (310 ±0)` - // Estimated: `15440 + m * (409 ±16) + p * (2331 ±8)` - // Minimum execution time: 13_516_000 picoseconds. - Weight::from_parts(13_611_000, 15440) - // Standard Error: 346_205 - .saturating_add(Weight::from_parts(3_915_806, 0).saturating_mul(m.into())) - // Standard Error: 174_852 - .saturating_add(Weight::from_parts(3_762_675, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(m.into()))) + // Measured: `0 + m * (672 ±0) + p * (310 ±0)` + // Estimated: `7085 + m * (396 ±7) + p * (2539 ±3)` + // Minimum execution time: 13_876_000 picoseconds. + Weight::from_parts(14_129_000, 7085) + // Standard Error: 155_547 + .saturating_add(Weight::from_parts(2_657_114, 0).saturating_mul(m.into())) + // Standard Error: 78_133 + .saturating_add(Weight::from_parts(4_151_945, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) - .saturating_add(T::DbWeight::get().writes(2_u64)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(m.into()))) + .saturating_add(T::DbWeight::get().writes(2)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) - .saturating_add(Weight::from_parts(0, 409).saturating_mul(m.into())) - .saturating_add(Weight::from_parts(0, 2331).saturating_mul(p.into())) + .saturating_add(Weight::from_parts(0, 396).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 2539).saturating_mul(p.into())) } /// Storage: `TechnicalCommittee::Members` (r:1 w:0) /// Proof: `TechnicalCommittee::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// The range of component `b` is `[2, 1024]`. /// The range of component `m` is `[1, 10]`. - fn execute(b: u32, m: u32) -> Weight { + fn execute(b: u32, m: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `70 + m * (32 ±0)` - // Estimated: `1554 + m * (32 ±0)` - // Minimum execution time: 21_681_000 picoseconds. - Weight::from_parts(21_863_772, 1554) - // Standard Error: 55 - .saturating_add(Weight::from_parts(1_268, 0).saturating_mul(b.into())) - // Standard Error: 6_176 - .saturating_add(Weight::from_parts(21_902, 0).saturating_mul(m.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) + // Estimated: `1555 + m * (32 ±0)` + // Minimum execution time: 22_086_000 picoseconds. + Weight::from_parts(22_142_927, 1555) + // Standard Error: 27 + .saturating_add(Weight::from_parts(1_188, 0).saturating_mul(b.into())) + // Standard Error: 3_174 + .saturating_add(Weight::from_parts(24_985, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) } /// Storage: `TechnicalCommittee::Members` (r:1 w:0) @@ -108,17 +101,17 @@ impl WeightInfo for HydraWeight { /// Proof: `TechnicalCommittee::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `b` is `[2, 1024]`. /// The range of component `m` is `[1, 10]`. - fn propose_execute(b: u32, m: u32) -> Weight { + fn propose_execute(b: u32, m: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `70 + m * (32 ±0)` - // Estimated: `3534 + m * (32 ±0)` - // Minimum execution time: 25_160_000 picoseconds. - Weight::from_parts(25_278_856, 3534) - // Standard Error: 55 - .saturating_add(Weight::from_parts(1_402, 0).saturating_mul(b.into())) - // Standard Error: 6_187 - .saturating_add(Weight::from_parts(55_858, 0).saturating_mul(m.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) + // Estimated: `3535 + m * (32 ±0)` + // Minimum execution time: 25_870_000 picoseconds. + Weight::from_parts(25_809_413, 3535) + // Standard Error: 26 + .saturating_add(Weight::from_parts(1_349, 0).saturating_mul(b.into())) + // Standard Error: 3_065 + .saturating_add(Weight::from_parts(39_651, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) } /// Storage: `TechnicalCommittee::Members` (r:1 w:0) @@ -134,38 +127,38 @@ impl WeightInfo for HydraWeight { /// The range of component `b` is `[2, 1024]`. /// The range of component `m` is `[2, 10]`. /// The range of component `p` is `[1, 20]`. - fn propose_proposed(b: u32, m: u32, p: u32) -> Weight { + fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `0 + m * (32 ±0) + p * (58 ±0)` - // Estimated: `3460 + m * (36 ±1) + p * (56 ±0)` - // Minimum execution time: 32_705_000 picoseconds. - Weight::from_parts(30_842_242, 3460) - // Standard Error: 168 - .saturating_add(Weight::from_parts(2_782, 0).saturating_mul(b.into())) - // Standard Error: 21_583 - .saturating_add(Weight::from_parts(45_202, 0).saturating_mul(m.into())) - // Standard Error: 8_890 - .saturating_add(Weight::from_parts(408_142, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) - .saturating_add(Weight::from_parts(0, 36).saturating_mul(m.into())) - .saturating_add(Weight::from_parts(0, 56).saturating_mul(p.into())) + // Measured: `156 + m * (32 ±0) + p * (50 ±0)` + // Estimated: `3574 + m * (32 ±0) + p * (53 ±0)` + // Minimum execution time: 33_389_000 picoseconds. + Weight::from_parts(33_070_270, 3574) + // Standard Error: 101 + .saturating_add(Weight::from_parts(2_087, 0).saturating_mul(b.into())) + // Standard Error: 12_061 + .saturating_add(Weight::from_parts(57_103, 0).saturating_mul(m.into())) + // Standard Error: 5_380 + .saturating_add(Weight::from_parts(365_489, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 53).saturating_mul(p.into())) } /// Storage: `TechnicalCommittee::Members` (r:1 w:0) /// Proof: `TechnicalCommittee::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `TechnicalCommittee::Voting` (r:1 w:1) /// Proof: `TechnicalCommittee::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `m` is `[5, 10]`. - fn vote(m: u32) -> Weight { + fn vote(m: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `538 + m * (64 ±0)` // Estimated: `4003 + m * (64 ±0)` - // Minimum execution time: 26_154_000 picoseconds. - Weight::from_parts(26_371_710, 4003) - // Standard Error: 9_771 - .saturating_add(Weight::from_parts(58_004, 0).saturating_mul(m.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 26_815_000 picoseconds. + Weight::from_parts(27_021_617, 4003) + // Standard Error: 4_949 + .saturating_add(Weight::from_parts(61_849, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) } /// Storage: `TechnicalCommittee::Voting` (r:1 w:1) @@ -178,17 +171,19 @@ impl WeightInfo for HydraWeight { /// Proof: `TechnicalCommittee::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `m` is `[4, 10]`. /// The range of component `p` is `[1, 20]`. - fn close_early_disapproved(m: u32, p: u32) -> Weight { + fn close_early_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `231 + m * (64 ±0) + p * (48 ±0)` - // Estimated: `3651 + m * (66 ±1) + p * (50 ±0)` - // Minimum execution time: 34_121_000 picoseconds. - Weight::from_parts(35_042_411, 3651) - // Standard Error: 5_417 - .saturating_add(Weight::from_parts(321_198, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) - .saturating_add(Weight::from_parts(0, 66).saturating_mul(m.into())) + // Measured: `208 + m * (64 ±0) + p * (49 ±0)` + // Estimated: `3640 + m * (69 ±0) + p * (50 ±0)` + // Minimum execution time: 35_042_000 picoseconds. + Weight::from_parts(36_087_417, 3640) + // Standard Error: 12_149 + .saturating_add(Weight::from_parts(3_876, 0).saturating_mul(m.into())) + // Standard Error: 3_989 + .saturating_add(Weight::from_parts(297_818, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 69).saturating_mul(m.into())) .saturating_add(Weight::from_parts(0, 50).saturating_mul(p.into())) } /// Storage: `TechnicalCommittee::Voting` (r:1 w:1) @@ -202,23 +197,23 @@ impl WeightInfo for HydraWeight { /// The range of component `b` is `[2, 1024]`. /// The range of component `m` is `[4, 10]`. /// The range of component `p` is `[1, 20]`. - fn close_early_approved(b: u32, m: u32, p: u32) -> Weight { + fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `178 + b * (1 ±0) + m * (64 ±0) + p * (71 ±0)` - // Estimated: `3620 + b * (1 ±0) + m * (71 ±3) + p * (69 ±0)` - // Minimum execution time: 49_393_000 picoseconds. - Weight::from_parts(49_577_674, 3620) - // Standard Error: 179 - .saturating_add(Weight::from_parts(1_043, 0).saturating_mul(b.into())) - // Standard Error: 29_444 - .saturating_add(Weight::from_parts(20_887, 0).saturating_mul(m.into())) - // Standard Error: 9_451 - .saturating_add(Weight::from_parts(371_478, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Measured: `290 + b * (1 ±0) + m * (64 ±0) + p * (65 ±0)` + // Estimated: `3656 + b * (1 ±0) + m * (69 ±1) + p * (66 ±0)` + // Minimum execution time: 50_836_000 picoseconds. + Weight::from_parts(50_461_445, 3656) + // Standard Error: 117 + .saturating_add(Weight::from_parts(1_279, 0).saturating_mul(b.into())) + // Standard Error: 18_953 + .saturating_add(Weight::from_parts(100_270, 0).saturating_mul(m.into())) + // Standard Error: 6_210 + .saturating_add(Weight::from_parts(330_642, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(b.into())) - .saturating_add(Weight::from_parts(0, 71).saturating_mul(m.into())) - .saturating_add(Weight::from_parts(0, 69).saturating_mul(p.into())) + .saturating_add(Weight::from_parts(0, 69).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 66).saturating_mul(p.into())) } /// Storage: `TechnicalCommittee::Voting` (r:1 w:1) /// Proof: `TechnicalCommittee::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -232,19 +227,19 @@ impl WeightInfo for HydraWeight { /// Proof: `TechnicalCommittee::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `m` is `[4, 10]`. /// The range of component `p` is `[1, 20]`. - fn close_disapproved(m: u32, p: u32) -> Weight { + fn close_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `251 + m * (64 ±0) + p * (48 ±0)` - // Estimated: `3671 + m * (66 ±1) + p * (50 ±0)` - // Minimum execution time: 37_061_000 picoseconds. - Weight::from_parts(37_585_589, 3671) - // Standard Error: 18_492 - .saturating_add(Weight::from_parts(16_560, 0).saturating_mul(m.into())) - // Standard Error: 5_928 - .saturating_add(Weight::from_parts(325_412, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) - .saturating_add(Weight::from_parts(0, 66).saturating_mul(m.into())) + // Measured: `228 + m * (64 ±0) + p * (49 ±0)` + // Estimated: `3660 + m * (69 ±0) + p * (50 ±0)` + // Minimum execution time: 38_419_000 picoseconds. + Weight::from_parts(39_480_671, 3660) + // Standard Error: 14_633 + .saturating_add(Weight::from_parts(23_963, 0).saturating_mul(m.into())) + // Standard Error: 4_805 + .saturating_add(Weight::from_parts(275_614, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 69).saturating_mul(m.into())) .saturating_add(Weight::from_parts(0, 50).saturating_mul(p.into())) } /// Storage: `TechnicalCommittee::Voting` (r:1 w:1) @@ -260,23 +255,23 @@ impl WeightInfo for HydraWeight { /// The range of component `b` is `[2, 1024]`. /// The range of component `m` is `[4, 10]`. /// The range of component `p` is `[1, 20]`. - fn close_approved(b: u32, m: u32, p: u32) -> Weight { + fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `198 + b * (1 ±0) + m * (64 ±0) + p * (71 ±0)` - // Estimated: `3640 + b * (1 ±0) + m * (71 ±3) + p * (69 ±0)` - // Minimum execution time: 52_845_000 picoseconds. - Weight::from_parts(52_535_618, 3640) - // Standard Error: 191 - .saturating_add(Weight::from_parts(1_017, 0).saturating_mul(b.into())) - // Standard Error: 31_471 - .saturating_add(Weight::from_parts(81_957, 0).saturating_mul(m.into())) - // Standard Error: 10_102 - .saturating_add(Weight::from_parts(356_674, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Measured: `310 + b * (1 ±0) + m * (64 ±0) + p * (65 ±0)` + // Estimated: `3676 + b * (1 ±0) + m * (69 ±1) + p * (66 ±0)` + // Minimum execution time: 53_648_000 picoseconds. + Weight::from_parts(54_698_175, 3676) + // Standard Error: 135 + .saturating_add(Weight::from_parts(1_012, 0).saturating_mul(b.into())) + // Standard Error: 21_972 + .saturating_add(Weight::from_parts(50_246, 0).saturating_mul(m.into())) + // Standard Error: 7_199 + .saturating_add(Weight::from_parts(311_701, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(b.into())) - .saturating_add(Weight::from_parts(0, 71).saturating_mul(m.into())) - .saturating_add(Weight::from_parts(0, 69).saturating_mul(p.into())) + .saturating_add(Weight::from_parts(0, 69).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 66).saturating_mul(p.into())) } /// Storage: `TechnicalCommittee::Proposals` (r:1 w:1) /// Proof: `TechnicalCommittee::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) @@ -285,16 +280,16 @@ impl WeightInfo for HydraWeight { /// Storage: `TechnicalCommittee::ProposalOf` (r:0 w:1) /// Proof: `TechnicalCommittee::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `p` is `[1, 20]`. - fn disapprove_proposal(p: u32) -> Weight { + fn disapprove_proposal(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `226 + p * (32 ±0)` - // Estimated: `1710 + p * (32 ±0)` - // Minimum execution time: 22_267_000 picoseconds. - Weight::from_parts(22_677_377, 1710) - // Standard Error: 4_842 - .saturating_add(Weight::from_parts(232_066, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Estimated: `1711 + p * (32 ±0)` + // Minimum execution time: 22_647_000 picoseconds. + Weight::from_parts(23_173_979, 1711) + // Standard Error: 3_421 + .saturating_add(Weight::from_parts(222_829, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(3)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(p.into())) } } diff --git a/runtime/hydradx/src/weights/timestamp.rs b/runtime/hydradx/src/weights/timestamp.rs index c6da1f0a6..07f6fac65 100644 --- a/runtime/hydradx/src/weights/timestamp.rs +++ b/runtime/hydradx/src/weights/timestamp.rs @@ -18,59 +18,52 @@ //! Autogenerated weights for `pallet_timestamp` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-timestamp +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_timestamp +// --output=./weights/timestamp.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/timestamp.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_timestamp::weights::WeightInfo; - -/// Weights for pallet_timestamp using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_timestamp`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_timestamp::WeightInfo for HydraWeight { /// Storage: `Timestamp::Now` (r:1 w:1) /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) fn set() -> Weight { // Proof Size summary in bytes: // Measured: `42` // Estimated: `1493` - // Minimum execution time: 9_605_000 picoseconds. - Weight::from_parts(9_858_000, 1493) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 9_400_000 picoseconds. + Weight::from_parts(9_641_000, 1493) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } fn on_finalize() -> Weight { // Proof Size summary in bytes: // Measured: `94` // Estimated: `0` - // Minimum execution time: 4_868_000 picoseconds. - Weight::from_parts(4_992_000, 0) + // Minimum execution time: 4_863_000 picoseconds. + Weight::from_parts(5_000_000, 0) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/tokens.rs b/runtime/hydradx/src/weights/tokens.rs index 47a4ab420..51a44f5c7 100644 --- a/runtime/hydradx/src/weights/tokens.rs +++ b/runtime/hydradx/src/weights/tokens.rs @@ -18,123 +18,164 @@ //! Autogenerated weights for `orml_tokens` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=orml-tokens +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=orml_tokens +// --output=./weights/tokens.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/tokens.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +#![allow(missing_docs)] -use orml_tokens::WeightInfo; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -/// Weights for orml_tokens using the hydraDX node and recommended hardware. +/// Weight functions for `orml_tokens`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { - /// Storage: `Tokens::Accounts` (r:2 w:2) +impl orml_tokens::WeightInfo for HydraWeight { + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:4 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:1) + /// Storage: `AssetRegistry::Assets` (r:2 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:3 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:3) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:2 w:0) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `2335` - // Estimated: `6156` - // Minimum execution time: 91_456_000 picoseconds. - Weight::from_parts(92_161_000, 6156) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Measured: `3102` + // Estimated: `11322` + // Minimum execution time: 282_258_000 picoseconds. + Weight::from_parts(285_181_000, 11322) + .saturating_add(T::DbWeight::get().reads(21)) + .saturating_add(T::DbWeight::get().writes(9)) } - /// Storage: `Tokens::Accounts` (r:2 w:2) + /// Storage: `Tokens::Accounts` (r:4 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) + /// Storage: `System::Account` (r:3 w:3) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:1) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:2 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:3 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:2 w:0) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn transfer_all() -> Weight { // Proof Size summary in bytes: - // Measured: `2335` - // Estimated: `6156` - // Minimum execution time: 95_160_000 picoseconds. - Weight::from_parts(95_870_000, 6156) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Measured: `3154` + // Estimated: `11322` + // Minimum execution time: 286_100_000 picoseconds. + Weight::from_parts(287_775_000, 11322) + .saturating_add(T::DbWeight::get().reads(21)) + .saturating_add(T::DbWeight::get().writes(9)) } - /// Storage: `Tokens::Accounts` (r:2 w:2) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:4 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) + /// Storage: `AssetRegistry::Assets` (r:2 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:3 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:2 w:0) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn transfer_keep_alive() -> Weight { // Proof Size summary in bytes: - // Measured: `2195` - // Estimated: `6156` - // Minimum execution time: 75_713_000 picoseconds. - Weight::from_parts(76_553_000, 6156) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Measured: `3152` + // Estimated: `11322` + // Minimum execution time: 198_176_000 picoseconds. + Weight::from_parts(199_598_000, 11322) + .saturating_add(T::DbWeight::get().reads(21)) + .saturating_add(T::DbWeight::get().writes(8)) } - /// Storage: `Tokens::Accounts` (r:2 w:2) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:2 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `Tokens::Accounts` (r:4 w:4) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) + /// Storage: `AssetRegistry::Assets` (r:2 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:3 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:3) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:2 w:0) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn force_transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `2333` - // Estimated: `6196` - // Minimum execution time: 79_242_000 picoseconds. - Weight::from_parts(79_954_000, 6196) - .saturating_add(T::DbWeight::get().reads(7_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Measured: `3154` + // Estimated: `11322` + // Minimum execution time: 282_695_000 picoseconds. + Weight::from_parts(284_482_000, 11322) + .saturating_add(T::DbWeight::get().reads(21)) + .saturating_add(T::DbWeight::get().writes(9)) } /// Storage: `Tokens::Accounts` (r:1 w:1) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::Assets` (r:1 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) @@ -145,11 +186,11 @@ impl WeightInfo for HydraWeight { /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) fn set_balance() -> Weight { // Proof Size summary in bytes: - // Measured: `2127` + // Measured: `2143` // Estimated: `3593` - // Minimum execution time: 68_117_000 picoseconds. - Weight::from_parts(68_690_000, 3593) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 67_017_000 picoseconds. + Weight::from_parts(67_929_000, 3593) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(3)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/transaction_pause.rs b/runtime/hydradx/src/weights/transaction_pause.rs index a8c7f1e5d..37995911f 100644 --- a/runtime/hydradx/src/weights/transaction_pause.rs +++ b/runtime/hydradx/src/weights/transaction_pause.rs @@ -18,63 +18,56 @@ //! Autogenerated weights for `pallet_transaction_pause` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-transaction-pause +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_transaction_pause +// --output=./weights/transaction_pause.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/transaction_pause.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_transaction_pause::weights::WeightInfo; - -/// Weights for pallet_transaction_pause using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_transaction_pause`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_transaction_pause::WeightInfo for HydraWeight { /// Storage: `TransactionPause::PausedTransactions` (r:1 w:1) /// Proof: `TransactionPause::PausedTransactions` (`max_values`: None, `max_size`: Some(90), added: 2565, mode: `MaxEncodedLen`) fn pause_transaction() -> Weight { // Proof Size summary in bytes: - // Measured: `109` + // Measured: `147` // Estimated: `3555` - // Minimum execution time: 15_060_000 picoseconds. - Weight::from_parts(15_317_000, 3555) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 16_343_000 picoseconds. + Weight::from_parts(16_726_000, 3555) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `TransactionPause::PausedTransactions` (r:1 w:1) /// Proof: `TransactionPause::PausedTransactions` (`max_values`: None, `max_size`: Some(90), added: 2565, mode: `MaxEncodedLen`) fn unpause_transaction() -> Weight { // Proof Size summary in bytes: - // Measured: `160` + // Measured: `198` // Estimated: `3555` - // Minimum execution time: 17_304_000 picoseconds. - Weight::from_parts(17_780_000, 3555) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 17_899_000 picoseconds. + Weight::from_parts(18_371_000, 3555) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/treasury.rs b/runtime/hydradx/src/weights/treasury.rs index 52dca557b..0e1a664bd 100644 --- a/runtime/hydradx/src/weights/treasury.rs +++ b/runtime/hydradx/src/weights/treasury.rs @@ -18,49 +18,42 @@ //! Autogenerated weights for `pallet_treasury` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-treasury +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_treasury +// --output=./weights/treasury.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/treasury.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_treasury::weights::WeightInfo; - -/// Weights for pallet_treasury using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_treasury`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_treasury::WeightInfo for HydraWeight { fn spend() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 422_000 picoseconds. - Weight::from_parts(449_000, 0) + // Minimum execution time: 377_000 picoseconds. + Weight::from_parts(415_000, 0) } /// Storage: `Treasury::ProposalCount` (r:1 w:1) /// Proof: `Treasury::ProposalCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -70,10 +63,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `210` // Estimated: `1489` - // Minimum execution time: 39_374_000 picoseconds. - Weight::from_parts(39_839_000, 1489) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 37_853_000 picoseconds. + Weight::from_parts(38_512_000, 1489) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Treasury::Proposals` (r:1 w:1) /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) @@ -83,26 +76,26 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `471` // Estimated: `6196` - // Minimum execution time: 58_400_000 picoseconds. - Weight::from_parts(58_832_000, 6196) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 56_828_000 picoseconds. + Weight::from_parts(57_266_000, 6196) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `Treasury::Proposals` (r:1 w:0) /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `Treasury::Approvals` (r:1 w:1) /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) /// The range of component `p` is `[0, 99]`. - fn approve_proposal(p: u32) -> Weight { + fn approve_proposal(p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `417 + p * (11 ±0)` + // Measured: `571 + p * (7 ±0)` // Estimated: `3573` - // Minimum execution time: 14_121_000 picoseconds. - Weight::from_parts(15_974_273, 3573) - // Standard Error: 4_650 - .saturating_add(Weight::from_parts(58_332, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 14_617_000 picoseconds. + Weight::from_parts(17_552_607, 3573) + // Standard Error: 2_701 + .saturating_add(Weight::from_parts(41_981, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Treasury::Approvals` (r:1 w:1) /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) @@ -110,10 +103,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `194` // Estimated: `1887` - // Minimum execution time: 9_887_000 picoseconds. - Weight::from_parts(10_028_000, 1887) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 9_955_000 picoseconds. + Weight::from_parts(10_322_000, 1887) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `System::Account` (r:201 w:201) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -126,18 +119,18 @@ impl WeightInfo for HydraWeight { /// Storage: `Treasury::Proposals` (r:100 w:100) /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// The range of component `p` is `[0, 100]`. - fn on_initialize_proposals(p: u32) -> Weight { + fn on_initialize_proposals(p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `459 + p * (251 ±0)` + // Measured: `316 + p * (253 ±0)` // Estimated: `3593 + p * (5206 ±0)` - // Minimum execution time: 39_458_000 picoseconds. - Weight::from_parts(53_941_800, 3593) - // Standard Error: 121_853 - .saturating_add(Weight::from_parts(51_771_233, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) + // Minimum execution time: 38_716_000 picoseconds. + Weight::from_parts(47_514_413, 3593) + // Standard Error: 29_010 + .saturating_add(Weight::from_parts(50_516_662, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(p.into()))) - .saturating_add(T::DbWeight::get().writes(3_u64)) + .saturating_add(T::DbWeight::get().writes(4)) .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(p.into()))) .saturating_add(Weight::from_parts(0, 5206).saturating_mul(p.into())) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/utility.rs b/runtime/hydradx/src/weights/utility.rs index 4839f642f..b986763e2 100644 --- a/runtime/hydradx/src/weights/utility.rs +++ b/runtime/hydradx/src/weights/utility.rs @@ -18,85 +18,78 @@ //! Autogenerated weights for `pallet_utility` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-utility +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_utility +// --output=./weights/utility.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/utility.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use pallet_utility::weights::WeightInfo; - -/// Weights for pallet_utility using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_utility`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_utility::WeightInfo for HydraWeight { /// The range of component `c` is `[0, 1000]`. - fn batch(c: u32) -> Weight { + fn batch(c: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 10_344_000 picoseconds. - Weight::from_parts(18_082_840, 0) - // Standard Error: 4_915 - .saturating_add(Weight::from_parts(6_792_341, 0).saturating_mul(c.into())) + // Minimum execution time: 10_239_000 picoseconds. + Weight::from_parts(9_506_750, 0) + // Standard Error: 4_964 + .saturating_add(Weight::from_parts(6_554_896, 0).saturating_mul(c.into())) } fn as_derivative() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_899_000 picoseconds. - Weight::from_parts(8_182_000, 0) + // Minimum execution time: 7_602_000 picoseconds. + Weight::from_parts(7_828_000, 0) } /// The range of component `c` is `[0, 1000]`. - fn batch_all(c: u32) -> Weight { + fn batch_all(c: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 10_308_000 picoseconds. - Weight::from_parts(14_711_160, 0) - // Standard Error: 4_844 - .saturating_add(Weight::from_parts(7_186_588, 0).saturating_mul(c.into())) + // Minimum execution time: 10_351_000 picoseconds. + Weight::from_parts(19_343_913, 0) + // Standard Error: 5_903 + .saturating_add(Weight::from_parts(6_958_305, 0).saturating_mul(c.into())) } fn dispatch_as() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 13_395_000 picoseconds. - Weight::from_parts(13_566_000, 0) + // Minimum execution time: 13_448_000 picoseconds. + Weight::from_parts(13_627_000, 0) } /// The range of component `c` is `[0, 1000]`. - fn force_batch(c: u32) -> Weight { + fn force_batch(c: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 10_686_000 picoseconds. - Weight::from_parts(7_857_460, 0) - // Standard Error: 4_105 - .saturating_add(Weight::from_parts(6_820_383, 0).saturating_mul(c.into())) + // Minimum execution time: 10_282_000 picoseconds. + Weight::from_parts(21_770_041, 0) + // Standard Error: 6_324 + .saturating_add(Weight::from_parts(6_570_955, 0).saturating_mul(c.into())) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/vesting.rs b/runtime/hydradx/src/weights/vesting.rs index f35946a95..c8c72e4dd 100644 --- a/runtime/hydradx/src/weights/vesting.rs +++ b/runtime/hydradx/src/weights/vesting.rs @@ -18,43 +18,36 @@ //! Autogenerated weights for `orml_vesting` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=orml-vesting +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=orml_vesting +// --output=./weights/vesting.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/vesting.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -use orml_vesting::WeightInfo; - -/// Weights for orml_vesting using the hydraDX node and recommended hardware. +/// Weight functions for `orml_vesting`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl orml_vesting::WeightInfo for HydraWeight { /// Storage: `Vesting::VestingSchedules` (r:1 w:1) /// Proof: `Vesting::VestingSchedules` (`max_values`: None, `max_size`: Some(2850), added: 5325, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) @@ -65,12 +58,12 @@ impl WeightInfo for HydraWeight { /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) fn vested_transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `1914` + // Measured: `1918` // Estimated: `6315` - // Minimum execution time: 119_563_000 picoseconds. - Weight::from_parts(120_581_000, 6315) - .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Minimum execution time: 118_969_000 picoseconds. + Weight::from_parts(120_010_000, 6315) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `Vesting::VestingSchedules` (r:1 w:1) /// Proof: `Vesting::VestingSchedules` (`max_values`: None, `max_size`: Some(2850), added: 5325, mode: `MaxEncodedLen`) @@ -79,16 +72,16 @@ impl WeightInfo for HydraWeight { /// Storage: `Balances::Freezes` (r:1 w:0) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) /// The range of component `i` is `[1, 100]`. - fn claim(i: u32) -> Weight { + fn claim(i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `2032 + i * (18 ±0)` + // Measured: `2037 + i * (18 ±0)` // Estimated: `6315` - // Minimum execution time: 68_015_000 picoseconds. - Weight::from_parts(68_850_181, 6315) - // Standard Error: 1_475 - .saturating_add(Weight::from_parts(86_367, 0).saturating_mul(i.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 66_914_000 picoseconds. + Weight::from_parts(68_653_438, 6315) + // Standard Error: 1_016 + .saturating_add(Weight::from_parts(84_943, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -99,15 +92,15 @@ impl WeightInfo for HydraWeight { /// Storage: `Vesting::VestingSchedules` (r:0 w:1) /// Proof: `Vesting::VestingSchedules` (`max_values`: None, `max_size`: Some(2850), added: 5325, mode: `MaxEncodedLen`) /// The range of component `i` is `[1, 100]`. - fn update_vesting_schedules(i: u32) -> Weight { + fn update_vesting_schedules(i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1615` + // Measured: `1619` // Estimated: `4764` - // Minimum execution time: 59_122_000 picoseconds. - Weight::from_parts(59_638_156, 4764) - // Standard Error: 730 - .saturating_add(Weight::from_parts(78_296, 0).saturating_mul(i.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 58_382_000 picoseconds. + Weight::from_parts(59_008_204, 4764) + // Standard Error: 546 + .saturating_add(Weight::from_parts(82_456, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/xcm.rs b/runtime/hydradx/src/weights/xcm.rs index 796617c51..183f43b07 100644 --- a/runtime/hydradx/src/weights/xcm.rs +++ b/runtime/hydradx/src/weights/xcm.rs @@ -18,43 +18,36 @@ //! Autogenerated weights for `pallet_xcm` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-xcm +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet-xcm +// --output=./weights/xcm.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/xcm.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] - -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +#![allow(missing_docs)] -use pallet_xcm::WeightInfo; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; -/// Weights for pallet_xcm using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_xcm`. pub struct HydraWeight(PhantomData); - -impl WeightInfo for HydraWeight { +impl pallet_xcm::WeightInfo for HydraWeight { /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) @@ -69,10 +62,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 38_308_000 picoseconds. - Weight::from_parts(39_025_000, 3610) - .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 38_630_000 picoseconds. + Weight::from_parts(39_297_000, 3610) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `Benchmark::Override` (r:0 w:0) /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -89,8 +82,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `69` // Estimated: `1489` - // Minimum execution time: 30_501_000 picoseconds. - Weight::from_parts(31_561_000, 1489).saturating_add(T::DbWeight::get().reads(1_u64)) + // Minimum execution time: 30_159_000 picoseconds. + Weight::from_parts(30_412_000, 1489) + .saturating_add(T::DbWeight::get().reads(1)) } /// Storage: `Benchmark::Override` (r:0 w:0) /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -107,8 +101,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 14_258_000 picoseconds. - Weight::from_parts(14_635_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 13_988_000 picoseconds. + Weight::from_parts(14_343_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `PolkadotXcm::SafeXcmVersion` (r:0 w:1) /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) @@ -116,8 +111,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_144_000 picoseconds. - Weight::from_parts(5_275_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 5_051_000 picoseconds. + Weight::from_parts(5_221_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -139,10 +135,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 45_191_000 picoseconds. - Weight::from_parts(45_866_000, 3610) - .saturating_add(T::DbWeight::get().reads(7_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Minimum execution time: 45_381_000 picoseconds. + Weight::from_parts(45_916_000, 3610) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -162,10 +158,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `328` // Estimated: `3793` - // Minimum execution time: 45_127_000 picoseconds. - Weight::from_parts(45_519_000, 3793) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Minimum execution time: 44_926_000 picoseconds. + Weight::from_parts(45_579_000, 3793) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `PolkadotXcm::XcmExecutionSuspended` (r:0 w:1) /// Proof: `PolkadotXcm::XcmExecutionSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) @@ -173,8 +169,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_213_000 picoseconds. - Weight::from_parts(5_354_000, 0).saturating_add(T::DbWeight::get().writes(1_u64)) + // Minimum execution time: 4_986_000 picoseconds. + Weight::from_parts(5_153_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `PolkadotXcm::SupportedVersion` (r:4 w:2) /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -182,10 +179,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `167` // Estimated: `11057` - // Minimum execution time: 24_438_000 picoseconds. - Weight::from_parts(24_889_000, 11057) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 23_374_000 picoseconds. + Weight::from_parts(24_225_000, 11057) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `PolkadotXcm::VersionNotifiers` (r:4 w:2) /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -193,10 +190,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `171` // Estimated: `11061` - // Minimum execution time: 24_317_000 picoseconds. - Weight::from_parts(24_952_000, 11061) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 23_394_000 picoseconds. + Weight::from_parts(24_116_000, 11061) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:5 w:0) /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -204,8 +201,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `178` // Estimated: `13543` - // Minimum execution time: 25_401_000 picoseconds. - Weight::from_parts(25_725_000, 13543).saturating_add(T::DbWeight::get().reads(5_u64)) + // Minimum execution time: 24_948_000 picoseconds. + Weight::from_parts(25_329_000, 13543) + .saturating_add(T::DbWeight::get().reads(5)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:2 w:1) /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -223,10 +221,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `212` // Estimated: `6152` - // Minimum execution time: 41_914_000 picoseconds. - Weight::from_parts(42_385_000, 6152) - .saturating_add(T::DbWeight::get().reads(7_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 40_668_000 picoseconds. + Weight::from_parts(41_385_000, 6152) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:3 w:0) /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -234,8 +232,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `172` // Estimated: `8587` - // Minimum execution time: 13_727_000 picoseconds. - Weight::from_parts(13_964_000, 8587).saturating_add(T::DbWeight::get().reads(3_u64)) + // Minimum execution time: 13_397_000 picoseconds. + Weight::from_parts(13_608_000, 8587) + .saturating_add(T::DbWeight::get().reads(3)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -243,10 +242,10 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `178` // Estimated: `11068` - // Minimum execution time: 24_882_000 picoseconds. - Weight::from_parts(25_611_000, 11068) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 24_281_000 picoseconds. + Weight::from_parts(24_768_000, 11068) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -264,9 +263,9 @@ impl WeightInfo for HydraWeight { // Proof Size summary in bytes: // Measured: `254` // Estimated: `11144` - // Minimum execution time: 51_859_000 picoseconds. - Weight::from_parts(52_412_000, 11144) - .saturating_add(T::DbWeight::get().reads(9_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + // Minimum execution time: 50_481_000 picoseconds. + Weight::from_parts(51_043_000, 11144) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(4)) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/xcmp_queue.rs b/runtime/hydradx/src/weights/xcmp_queue.rs index c6197d1d7..1f3673e35 100644 --- a/runtime/hydradx/src/weights/xcmp_queue.rs +++ b/runtime/hydradx/src/weights/xcmp_queue.rs @@ -18,7 +18,7 @@ //! Autogenerated weights for `cumulus_pallet_xcmp_queue` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-14, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 @@ -30,13 +30,12 @@ // --chain=dev // --steps=10 // --repeat=30 -// --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 // --template=.maintain/pallet-weight-template-no-back.hbs // --pallet=cumulus-pallet-xcmp-queue -// --output=weights-1.1.0/xcmp-queue.rs -// --extrinsic= +// --output=./weights/xcmp_queue.rs +// --extrinsic=* #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -55,8 +54,8 @@ impl cumulus_pallet_xcmp_queue::WeightInfo for HydraWei // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 8_061_000 picoseconds. - Weight::from_parts(8_243_000, 1627) + // Minimum execution time: 7_816_000 picoseconds. + Weight::from_parts(8_016_000, 1627) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -66,8 +65,8 @@ impl cumulus_pallet_xcmp_queue::WeightInfo for HydraWei // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 8_255_000 picoseconds. - Weight::from_parts(8_413_000, 1627) + // Minimum execution time: 7_869_000 picoseconds. + Weight::from_parts(8_072_000, 1627) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -92,10 +91,10 @@ impl cumulus_pallet_xcmp_queue::WeightInfo for HydraWei // Proof Size summary in bytes: // Measured: `6275 + b * (324357 ±0)` // Estimated: `9740 + b * (373857 ±0)` - // Minimum execution time: 32_529_153_000 picoseconds. - Weight::from_parts(160_904_784, 9740) - // Standard Error: 8_949_581 - .saturating_add(Weight::from_parts(32_575_018_568, 0).saturating_mul(b.into())) + // Minimum execution time: 33_398_415_000 picoseconds. + Weight::from_parts(57_262_807, 9740) + // Standard Error: 7_265_843 + .saturating_add(Weight::from_parts(33_588_589_234, 0).saturating_mul(b.into())) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().reads((21_u64).saturating_mul(b.into()))) .saturating_add(T::DbWeight::get().writes(3)) @@ -109,10 +108,10 @@ impl cumulus_pallet_xcmp_queue::WeightInfo for HydraWei // Proof Size summary in bytes: // Measured: `252 + m * (16216 ±0)` // Estimated: `3716 + m * (16216 ±0)` - // Minimum execution time: 1_269_514_000 picoseconds. - Weight::from_parts(254_832_812, 3716) - // Standard Error: 451_448 - .saturating_add(Weight::from_parts(1_075_219_465, 0).saturating_mul(m.into())) + // Minimum execution time: 1_285_382_000 picoseconds. + Weight::from_parts(242_447_351, 3716) + // Standard Error: 426_683 + .saturating_add(Weight::from_parts(1_106_936_264, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(Weight::from_parts(0, 16216).saturating_mul(m.into())) @@ -124,10 +123,10 @@ impl cumulus_pallet_xcmp_queue::WeightInfo for HydraWei // Proof Size summary in bytes: // Measured: `252 + m * (16216 ±0)` // Estimated: `3716 + m * (16216 ±0)` - // Minimum execution time: 1_331_675_000 picoseconds. - Weight::from_parts(131_637_639, 3716) - // Standard Error: 513_067 - .saturating_add(Weight::from_parts(1_197_225_867, 0).saturating_mul(m.into())) + // Minimum execution time: 1_351_709_000 picoseconds. + Weight::from_parts(116_677_544, 3716) + // Standard Error: 375_367 + .saturating_add(Weight::from_parts(1_225_618_925, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(Weight::from_parts(0, 16216).saturating_mul(m.into())) @@ -141,12 +140,12 @@ impl cumulus_pallet_xcmp_queue::WeightInfo for HydraWei // Proof Size summary in bytes: // Measured: `0 + m * (16216 ±0)` // Estimated: `9724 + m * (15020 ±55)` - // Minimum execution time: 106_584_000 picoseconds. - Weight::from_parts(125_484_886, 9724) - // Standard Error: 199_725 - .saturating_add(Weight::from_parts(6_590_187, 0).saturating_mul(m.into())) + // Minimum execution time: 107_020_000 picoseconds. + Weight::from_parts(128_836_899, 9724) + // Standard Error: 222_629 + .saturating_add(Weight::from_parts(6_772_210, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) .saturating_add(Weight::from_parts(0, 15020).saturating_mul(m.into())) } -} +} \ No newline at end of file diff --git a/runtime/hydradx/src/weights/xyk.rs b/runtime/hydradx/src/weights/xyk.rs index 62ee3d5c9..7a8c24f45 100644 --- a/runtime/hydradx/src/weights/xyk.rs +++ b/runtime/hydradx/src/weights/xyk.rs @@ -18,216 +18,305 @@ //! Autogenerated weights for `pallet_xyk` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `5`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-02-15, STEPS: `10`, REPEAT: `30`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `bench-bot`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: 1024 // Executed Command: // target/release/hydradx // benchmark // pallet -// --pallet=pallet-xyk +// --chain=dev +// --steps=10 +// --repeat=30 // --wasm-execution=compiled // --heap-pages=4096 -// --chain=dev +// --template=.maintain/pallet-weight-template-no-back.hbs +// --pallet=pallet_xyk +// --output=./weights/xyk.rs // --extrinsic=* -// --steps=5 -// --repeat=20 -// --output -// ./weights-1.1.0/xyk.rs -// --template -// .maintain/pallet-weight-template-no-back.hbs +#![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] #![allow(unused_imports)] -#![allow(clippy::unnecessary_cast)] +#![allow(missing_docs)] -use frame_support::{ - traits::Get, - weights::{constants::RocksDbWeight, Weight}, -}; -use sp_std::marker::PhantomData; +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; use pallet_xyk::weights::WeightInfo; -/// Weights for pallet_xyk using the hydraDX node and recommended hardware. +/// Weight functions for `pallet_xyk`. pub struct HydraWeight(PhantomData); - impl WeightInfo for HydraWeight { /// Storage: `LBP::PoolData` (r:1 w:0) /// Proof: `LBP::PoolData` (`max_values`: None, `max_size`: Some(163), added: 2638, mode: `MaxEncodedLen`) /// Storage: `XYK::ShareToken` (r:1 w:1) /// Proof: `XYK::ShareToken` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:5 w:5) + /// Storage: `Tokens::Accounts` (r:7 w:7) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::AssetIds` (r:1 w:1) /// Proof: `AssetRegistry::AssetIds` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) /// Storage: `AssetRegistry::NextAssetId` (r:1 w:1) /// Proof: `AssetRegistry::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:1) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:2 w:1) + /// Storage: `Duster::AccountBlacklist` (r:1 w:1) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:4 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:3 w:1) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:3 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:1 w:0) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:3) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencies` (r:3 w:0) /// Proof: `MultiTransactionPayment::AcceptedCurrencies` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) - /// Storage: `Duster::AccountBlacklist` (r:0 w:1) - /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) /// Storage: `XYK::TotalLiquidity` (r:0 w:1) /// Proof: `XYK::TotalLiquidity` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`) /// Storage: `XYK::PoolAssets` (r:0 w:1) /// Proof: `XYK::PoolAssets` (`max_values`: None, `max_size`: Some(56), added: 2531, mode: `MaxEncodedLen`) fn create_pool() -> Weight { // Proof Size summary in bytes: - // Measured: `1140` - // Estimated: `13905` - // Minimum execution time: 202_507_000 picoseconds. - Weight::from_parts(203_717_000, 13905) - .saturating_add(T::DbWeight::get().reads(17_u64)) - .saturating_add(T::DbWeight::get().writes(16_u64)) + // Measured: `3522` + // Estimated: `19071` + // Minimum execution time: 588_643_000 picoseconds. + Weight::from_parts(592_313_000, 19071) + .saturating_add(T::DbWeight::get().reads(33)) + .saturating_add(T::DbWeight::get().writes(20)) } /// Storage: `XYK::ShareToken` (r:1 w:0) /// Proof: `XYK::ShareToken` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:5 w:5) + /// Storage: `Tokens::Accounts` (r:7 w:7) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) /// Storage: `XYK::TotalLiquidity` (r:1 w:1) /// Proof: `XYK::TotalLiquidity` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:3 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) + /// Storage: `Duster::AccountBlacklist` (r:1 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:4 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:4 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `Tokens::TotalIssuance` (r:1 w:1) - /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `Tokens::TotalIssuance` (r:1 w:1) + /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) fn add_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `1803` - // Estimated: `13905` - // Minimum execution time: 176_176_000 picoseconds. - Weight::from_parts(177_422_000, 13905) - .saturating_add(T::DbWeight::get().reads(14_u64)) - .saturating_add(T::DbWeight::get().writes(9_u64)) + // Measured: `4159` + // Estimated: `19071` + // Minimum execution time: 353_004_000 picoseconds. + Weight::from_parts(354_898_000, 19071) + .saturating_add(T::DbWeight::get().reads(27)) + .saturating_add(T::DbWeight::get().writes(14)) } - /// Storage: `XYK::ShareToken` (r:1 w:0) + /// Storage: `XYK::ShareToken` (r:1 w:1) /// Proof: `XYK::ShareToken` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) /// Storage: `XYK::TotalLiquidity` (r:1 w:1) /// Proof: `XYK::TotalLiquidity` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:5 w:5) + /// Storage: `Tokens::Accounts` (r:7 w:7) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:3 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:0) + /// Storage: `Duster::AccountBlacklist` (r:2 w:1) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:3 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:4 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:2 w:0) + /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:3) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `Tokens::TotalIssuance` (r:1 w:1) /// Proof: `Tokens::TotalIssuance` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) + /// Storage: `XYK::PoolAssets` (r:0 w:1) + /// Proof: `XYK::PoolAssets` (`max_values`: None, `max_size`: Some(56), added: 2531, mode: `MaxEncodedLen`) fn remove_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `1749` - // Estimated: `13905` - // Minimum execution time: 168_176_000 picoseconds. - Weight::from_parts(169_296_000, 13905) - .saturating_add(T::DbWeight::get().reads(13_u64)) - .saturating_add(T::DbWeight::get().writes(8_u64)) + // Measured: `4208` + // Estimated: `19071` + // Minimum execution time: 523_229_000 picoseconds. + Weight::from_parts(525_459_000, 19071) + .saturating_add(T::DbWeight::get().reads(29)) + .saturating_add(T::DbWeight::get().writes(18)) } /// Storage: `XYK::ShareToken` (r:1 w:0) /// Proof: `XYK::ShareToken` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:4 w:4) + /// Storage: `Tokens::Accounts` (r:6 w:6) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:0) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:3 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:3 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) fn sell() -> Weight { // Proof Size summary in bytes: - // Measured: `1492` - // Estimated: `11322` - // Minimum execution time: 127_203_000 picoseconds. - Weight::from_parts(127_918_000, 11322) - .saturating_add(T::DbWeight::get().reads(10_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Measured: `4057` + // Estimated: `16488` + // Minimum execution time: 306_824_000 picoseconds. + Weight::from_parts(308_832_000, 16488) + .saturating_add(T::DbWeight::get().reads(24)) + .saturating_add(T::DbWeight::get().writes(11)) } /// Storage: `XYK::ShareToken` (r:1 w:0) /// Proof: `XYK::ShareToken` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:4 w:4) + /// Storage: `Tokens::Accounts` (r:6 w:6) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:0) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:3 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:3 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) fn buy() -> Weight { // Proof Size summary in bytes: - // Measured: `1492` - // Estimated: `11322` - // Minimum execution time: 126_846_000 picoseconds. - Weight::from_parts(127_737_000, 11322) - .saturating_add(T::DbWeight::get().reads(10_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) + // Measured: `4057` + // Estimated: `16488` + // Minimum execution time: 305_679_000 picoseconds. + Weight::from_parts(306_896_000, 16488) + .saturating_add(T::DbWeight::get().reads(24)) + .saturating_add(T::DbWeight::get().writes(11)) } /// Storage: `XYK::ShareToken` (r:1 w:0) /// Proof: `XYK::ShareToken` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:4 w:4) + /// Storage: `Tokens::Accounts` (r:6 w:6) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:0) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:3 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:3 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) /// The range of component `c` is `[1, 2]`. /// The range of component `e` is `[0, 1]`. - fn router_execution_sell(c: u32, e: u32) -> Weight { + fn router_execution_sell(c: u32, e: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `583 + e * (909 ±0)` - // Estimated: `6156 + e * (5166 ±0)` - // Minimum execution time: 22_072_000 picoseconds. - Weight::from_parts(5_201_125, 6156) - // Standard Error: 56_711 - .saturating_add(Weight::from_parts(8_630_075, 0).saturating_mul(c.into())) - // Standard Error: 56_711 - .saturating_add(Weight::from_parts(113_479_825, 0).saturating_mul(e.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().reads((7_u64).saturating_mul(e.into()))) - .saturating_add(T::DbWeight::get().writes((5_u64).saturating_mul(e.into()))) - .saturating_add(Weight::from_parts(0, 5166).saturating_mul(e.into())) + // Measured: `1187 + e * (2870 ±0)` + // Estimated: `6156 + e * (10332 ±52_268_479_977_062_104)` + // Minimum execution time: 25_878_000 picoseconds. + Weight::from_parts(9_649_436, 6156) + // Standard Error: 80_766 + .saturating_add(Weight::from_parts(8_443_704, 0).saturating_mul(c.into())) + // Standard Error: 80_766 + .saturating_add(Weight::from_parts(289_624_454, 0).saturating_mul(e.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().reads((21_u64).saturating_mul(e.into()))) + .saturating_add(T::DbWeight::get().writes((11_u64).saturating_mul(e.into()))) + .saturating_add(Weight::from_parts(0, 10332).saturating_mul(e.into())) } /// Storage: `XYK::ShareToken` (r:1 w:0) /// Proof: `XYK::ShareToken` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `Tokens::Accounts` (r:4 w:4) + /// Storage: `Tokens::Accounts` (r:6 w:6) /// Proof: `Tokens::Accounts` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `AssetRegistry::Assets` (r:2 w:0) - /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(87), added: 2562, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:0) + /// Storage: `Duster::AccountBlacklist` (r:2 w:0) + /// Proof: `Duster::AccountBlacklist` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::BannedAssets` (r:3 w:0) + /// Proof: `AssetRegistry::BannedAssets` (`max_values`: None, `max_size`: Some(20), added: 2495, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::Assets` (r:3 w:0) + /// Proof: `AssetRegistry::Assets` (`max_values`: None, `max_size`: Some(125), added: 2600, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AccountCurrencyMap` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AccountCurrencyMap` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MultiTransactionPayment::AcceptedCurrencyPrice` (r:1 w:0) + /// Proof: `MultiTransactionPayment::AcceptedCurrencyPrice` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:3 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:1 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:1 w:0) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AssetRegistry::ExistentialDepositCounter` (r:1 w:1) + /// Proof: `AssetRegistry::ExistentialDepositCounter` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `EmaOracle::Accumulator` (r:1 w:1) /// Proof: `EmaOracle::Accumulator` (`max_values`: Some(1), `max_size`: Some(5921), added: 6416, mode: `MaxEncodedLen`) /// The range of component `c` is `[1, 3]`. /// The range of component `e` is `[0, 1]`. - fn router_execution_buy(c: u32, e: u32) -> Weight { + fn router_execution_buy(c: u32, e: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `583 + e * (909 ±0)` - // Estimated: `6156 + e * (5166 ±0)` - // Minimum execution time: 30_065_000 picoseconds. - Weight::from_parts(6_816_200, 6156) - // Standard Error: 42_652 - .saturating_add(Weight::from_parts(7_927_825, 0).saturating_mul(c.into())) - // Standard Error: 69_651 - .saturating_add(Weight::from_parts(112_378_650, 0).saturating_mul(e.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().reads((7_u64).saturating_mul(e.into()))) - .saturating_add(T::DbWeight::get().writes((5_u64).saturating_mul(e.into()))) - .saturating_add(Weight::from_parts(0, 5166).saturating_mul(e.into())) + // Measured: `1187 + e * (2870 ±0)` + // Estimated: `6156 + e * (10332 ±0)` + // Minimum execution time: 33_714_000 picoseconds. + Weight::from_parts(11_014_445, 6156) + // Standard Error: 41_799 + .saturating_add(Weight::from_parts(7_776_697, 0).saturating_mul(c.into())) + // Standard Error: 70_916 + .saturating_add(Weight::from_parts(287_790_853, 0).saturating_mul(e.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().reads((21_u64).saturating_mul(e.into()))) + .saturating_add(T::DbWeight::get().writes((11_u64).saturating_mul(e.into()))) + .saturating_add(Weight::from_parts(0, 10332).saturating_mul(e.into())) } } From 5c4112299511e44c3f66367ea66ef6ba9feeea0b Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Thu, 15 Feb 2024 16:24:03 +0100 Subject: [PATCH 91/93] fixed cda integration test --- integration-tests/src/dca.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/src/dca.rs b/integration-tests/src/dca.rs index 61c3f514a..7a34902fa 100644 --- a/integration-tests/src/dca.rs +++ b/integration-tests/src/dca.rs @@ -2250,7 +2250,7 @@ mod xyk { set_relaychain_block_number(10); let dca_budget = 1100 * UNITS; - let amount_to_buy = 100 * UNITS; + let amount_to_buy = 150 * UNITS; let schedule1 = schedule_fake_with_buy_order(PoolType::XYK, HDX, DAI, amount_to_buy, dca_budget); create_schedule(ALICE, schedule1); From 77614bd1e2644162cc96ac62adac65129a81a310 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 20 Feb 2024 12:03:14 +0100 Subject: [PATCH 92/93] asset-registry: removed storage fees for external asset registration and added weight multiplier for external asset registration --- pallets/asset-registry/src/benchmarking.rs | 1 - pallets/asset-registry/src/lib.rs | 53 ++++++-------------- pallets/asset-registry/src/tests/mock.rs | 9 +--- pallets/asset-registry/src/tests/register.rs | 48 +++++++----------- pallets/xyk/src/tests/mock.rs | 4 +- runtime/hydradx/src/assets.rs | 6 +-- 6 files changed, 38 insertions(+), 83 deletions(-) diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index 75abedb2f..08f2f4c5a 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -88,7 +88,6 @@ benchmarks! { register_external { let caller: T::AccountId = account("caller", 0, 1); - T::Currency::mint_into(T::StorageFeesAssetId::get(), &caller, 101_000 * UNIT)?; let expected_asset_id = Pallet::::next_asset_id().unwrap(); let location: T::AssetNativeLocation = Default::default(); diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index ac99a01e7..c91188006 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -20,13 +20,10 @@ use frame_support::pallet_prelude::*; use frame_support::require_transactional; use frame_support::sp_runtime::traits::CheckedAdd; -use frame_support::traits::tokens::{ - fungibles::{Inspect as FungiblesInspect, Mutate as FungiblesMutate}, - Preservation, -}; +use frame_support::traits::tokens::fungibles::{Inspect as FungiblesInspect, Mutate as FungiblesMutate}; use frame_system::pallet_prelude::*; use scale_info::TypeInfo; -use sp_arithmetic::traits::{BaseArithmetic, Zero}; +use sp_arithmetic::traits::BaseArithmetic; use sp_runtime::DispatchError; use sp_std::convert::TryInto; use sp_std::vec::Vec; @@ -100,18 +97,6 @@ pub mod pallet { #[pallet::constant] type SequentialIdStartAt: Get; - /// Id of the asset that is used to pay storage fees. - #[pallet::constant] - type StorageFeesAssetId: Get; - - /// Storage fees for external asset creation. - #[pallet::constant] - type StorageFees: Get; - - /// Beneficiary account of storage fees for external asset creation. - #[pallet::constant] - type StorageFeesBeneficiary: Get; - /// The maximum length of a name or symbol stored on-chain. #[pallet::constant] type StringLimit: Get + Debug + PartialEq; @@ -120,6 +105,10 @@ pub mod pallet { #[pallet::constant] type MinStringLimit: Get + Debug + PartialEq; + /// Weight multiplier for `register_external` extrinsic + #[pallet::constant] + type RegExternalWeightMultiplier: Get; + /// Weight information for the extrinsics type WeightInfo: WeightInfo; } @@ -129,7 +118,14 @@ pub mod pallet { pub struct Pallet(_); #[pallet::hooks] - impl Hooks> for Pallet {} + impl Hooks> for Pallet { + fn integrity_test() { + assert!( + T::RegExternalWeightMultiplier::get().ge(&1_u64), + "`T::RegExternalWeightMultiplier` must be greater than zero." + ); + } + } #[pallet::error] pub enum Error { @@ -488,26 +484,9 @@ pub mod pallet { //NOTE: call indices 2 and 3 were used by removed extrinsics. #[pallet::call_index(4)] - #[pallet::weight(::WeightInfo::register_external())] + #[pallet::weight(::WeightInfo::register_external().saturating_mul(::RegExternalWeightMultiplier::get()))] pub fn register_external(origin: OriginFor, location: T::AssetNativeLocation) -> DispatchResult { - let who = ensure_signed(origin)?; - - if !T::StorageFees::get().is_zero() { - ensure!( - T::Currency::can_withdraw(T::StorageFeesAssetId::get(), &who, T::StorageFees::get()) - .into_result(false) - .is_ok(), - Error::::InsufficientBalance - ); - - T::Currency::transfer( - T::StorageFeesAssetId::get(), - &who, - &T::StorageFeesBeneficiary::get(), - T::StorageFees::get(), - Preservation::Expendable, - )?; - } + let _ = ensure_signed(origin)?; Self::do_register_asset( None, diff --git a/pallets/asset-registry/src/tests/mock.rs b/pallets/asset-registry/src/tests/mock.rs index e2df307bb..dad279dde 100644 --- a/pallets/asset-registry/src/tests/mock.rs +++ b/pallets/asset-registry/src/tests/mock.rs @@ -95,11 +95,6 @@ use scale_info::TypeInfo; #[derive(Debug, Default, Encode, Decode, Clone, PartialEq, Eq, TypeInfo, MaxEncodedLen)] pub struct AssetLocation(pub MultiLocation); -parameter_types! { - pub const StoreFees: Balance = 10 * UNIT; - pub const FeesBeneficiarry: u64 = TREASURY; -} - impl pallet_asset_registry::Config for Test { type RuntimeEvent = RuntimeEvent; type Currency = Tokens; @@ -110,9 +105,7 @@ impl pallet_asset_registry::Config for Test { type StringLimit = RegistryStringLimit; type MinStringLimit = RegistryMinStringLimit; type SequentialIdStartAt = SequentialIdStart; - type StorageFeesAssetId = NativeAssetId; - type StorageFees = StoreFees; - type StorageFeesBeneficiary = FeesBeneficiarry; + type RegExternalWeightMultiplier = frame_support::traits::ConstU64<1>; type WeightInfo = (); } diff --git a/pallets/asset-registry/src/tests/register.rs b/pallets/asset-registry/src/tests/register.rs index 573d9a321..f07710f9d 100644 --- a/pallets/asset-registry/src/tests/register.rs +++ b/pallets/asset-registry/src/tests/register.rs @@ -549,12 +549,6 @@ fn register_external_asset_should_work_when_location_is_provided() { } .into() )); - - assert_eq!( - Tokens::balance(NativeAssetId::get(), &ALICE), - alice_balance - StoreFees::get() - ); - assert_eq!(Tokens::balance(NativeAssetId::get(), &TREASURY), StoreFees::get()); }); } @@ -598,30 +592,6 @@ fn register_external_asset_should_not_work_when_location_is_already_used() { }); } -#[test] -fn register_external_asset_should_not_work_when_user_cant_pay_storage_fees() { - ExtBuilder::default().build().execute_with(|| { - let key = Junction::from(BoundedVec::try_from(528.encode()).unwrap()); - let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); - - let alice_balance = 10_000 * UNIT; - Tokens::set_balance( - RuntimeOrigin::root(), - ALICE, - NativeAssetId::get(), - StoreFees::get() - 1, - alice_balance, - ) - .unwrap(); - - //Act - assert_noop!( - Registry::register_external(RuntimeOrigin::signed(ALICE), asset_location), - Error::::InsufficientBalance - ); - }); -} - #[test] fn register_should_not_work_when_symbol_is_not_valid() { ExtBuilder::default().build().execute_with(|| { @@ -836,3 +806,21 @@ fn register_should_not_work_when_symbol_is_too_short() { ); }); } + +#[test] +fn register_externa_should_not_work_when_origin_is_none() { + ExtBuilder::default().build().execute_with(|| { + let key = Junction::from(BoundedVec::try_from(528.encode()).unwrap()); + let asset_location = AssetLocation(MultiLocation::new(0, X2(Parachain(200), key))); + + let alice_balance = 10_000 * UNIT; + Tokens::mint_into(NativeAssetId::get(), &ALICE, alice_balance).unwrap(); + assert_eq!(Tokens::balance(NativeAssetId::get(), &TREASURY), 0); + + //Act + assert_noop!( + Registry::register_external(RuntimeOrigin::none(), asset_location.clone()), + BadOrigin + ); + }); +} diff --git a/pallets/xyk/src/tests/mock.rs b/pallets/xyk/src/tests/mock.rs index b6d2844cb..b8dffd442 100644 --- a/pallets/xyk/src/tests/mock.rs +++ b/pallets/xyk/src/tests/mock.rs @@ -115,9 +115,7 @@ impl pallet_asset_registry::Config for Test { type StringLimit = RegistryStringLimit; type MinStringLimit = MinRegistryStringLimit; type SequentialIdStartAt = SequentialIdOffset; - type StorageFeesAssetId = NativeAssetId; - type StorageFees = StoreFees; - type StorageFeesBeneficiary = FeesBeneficiarry; + type RegExternalWeightMultiplier = frame_support::traits::ConstU64<1>; type WeightInfo = (); } diff --git a/runtime/hydradx/src/assets.rs b/runtime/hydradx/src/assets.rs index 4e8899288..54070264d 100644 --- a/runtime/hydradx/src/assets.rs +++ b/runtime/hydradx/src/assets.rs @@ -363,7 +363,7 @@ parameter_types! { #[derive(PartialEq, Debug)] pub const MinRegistryStrLimit: u32 = 3; pub const SequentialIdOffset: u32 = 1_000_000; - pub const StoreFees: Balance = 100 * UNITS; //TODO: + pub const RegExternalWeightMultiplier: u64 = 10; } impl pallet_asset_registry::Config for Runtime { @@ -376,9 +376,7 @@ impl pallet_asset_registry::Config for Runtime { type StringLimit = RegistryStrLimit; type MinStringLimit = MinRegistryStrLimit; type SequentialIdStartAt = SequentialIdOffset; - type StorageFeesAssetId = NativeAssetId; - type StorageFees = StoreFees; - type StorageFeesBeneficiary = TreasuryAccount; + type RegExternalWeightMultiplier = RegExternalWeightMultiplier; type WeightInfo = weights::registry::HydraWeight; } From 6515140ecdf3ea28f12466d87c03b9f47f87afd6 Mon Sep 17 00:00:00 2001 From: martinfridrich Date: Tue, 20 Feb 2024 17:46:09 +0100 Subject: [PATCH 93/93] bump versions --- Cargo.lock | 6 +++--- pallets/route-executor/Cargo.toml | 2 +- runtime/adapters/Cargo.toml | 2 +- runtime/hydradx/Cargo.toml | 2 +- runtime/hydradx/src/lib.rs | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2fc4c2ea7..2f26412c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4571,7 +4571,7 @@ dependencies = [ [[package]] name = "hydradx-adapters" -version = "1.1.0" +version = "1.1.1" dependencies = [ "cumulus-pallet-parachain-system", "cumulus-primitives-core", @@ -4619,7 +4619,7 @@ dependencies = [ [[package]] name = "hydradx-runtime" -version = "209.0.0" +version = "210.0.0" dependencies = [ "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", @@ -8288,7 +8288,7 @@ dependencies = [ [[package]] name = "pallet-route-executor" -version = "2.0.0" +version = "2.0.1" dependencies = [ "frame-benchmarking", "frame-support", diff --git a/pallets/route-executor/Cargo.toml b/pallets/route-executor/Cargo.toml index 4ffa6cdd8..ca5b39e02 100644 --- a/pallets/route-executor/Cargo.toml +++ b/pallets/route-executor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = 'pallet-route-executor' -version = '2.0.0' +version = '2.0.1' description = 'A pallet to execute a route containing a sequence of trades' authors = ['GalacticCouncil'] edition = '2021' diff --git a/runtime/adapters/Cargo.toml b/runtime/adapters/Cargo.toml index 7c3582797..33c5ad71a 100644 --- a/runtime/adapters/Cargo.toml +++ b/runtime/adapters/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-adapters" -version = "1.1.0" +version = "1.1.1" description = "Structs and other generic types for building runtimes." authors = ["GalacticCouncil"] edition = "2021" diff --git a/runtime/hydradx/Cargo.toml b/runtime/hydradx/Cargo.toml index 303876695..9e6e872d6 100644 --- a/runtime/hydradx/Cargo.toml +++ b/runtime/hydradx/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hydradx-runtime" -version = "209.0.0" +version = "210.0.0" authors = ["GalacticCouncil"] edition = "2021" license = "Apache 2.0" diff --git a/runtime/hydradx/src/lib.rs b/runtime/hydradx/src/lib.rs index 38fc6322f..f06cd9325 100644 --- a/runtime/hydradx/src/lib.rs +++ b/runtime/hydradx/src/lib.rs @@ -107,7 +107,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("hydradx"), impl_name: create_runtime_str!("hydradx"), authoring_version: 1, - spec_version: 209, + spec_version: 210, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1,