From c081548ef504abf3fd7b5329b138547fa62d5c32 Mon Sep 17 00:00:00 2001 From: SunTiebing <87381708+SunTiebing@users.noreply.github.com> Date: Sun, 29 Sep 2024 16:14:00 +0800 Subject: [PATCH] Optimize asset registry (#1445) * optimize asset-registry & remove unused call * backup asset-registry pallet --- pallets/asset-registry/src/benchmarking.rs | 140 +-- pallets/asset-registry/src/lib.rs | 355 +----- pallets/asset-registry/src/migrations/mod.rs | 19 + pallets/asset-registry/src/migrations/v0.rs | 131 +++ pallets/asset-registry/src/migrations/v1.rs | 118 ++ pallets/asset-registry/src/tests.rs | 208 +--- pallets/asset-registry/src/weights.rs | 56 - pallets/deprecated/asset-registry/Cargo.toml | 51 + .../asset-registry/src/benchmarking.rs | 309 +++++ pallets/deprecated/asset-registry/src/lib.rs | 1013 +++++++++++++++++ .../asset-registry/src/migration.rs | 0 pallets/deprecated/asset-registry/src/mock.rs | 109 ++ .../deprecated/asset-registry/src/tests.rs | 519 +++++++++ .../deprecated/asset-registry/src/weights.rs | 190 ++++ pallets/slpx/src/benchmarking.rs | 4 +- primitives/src/traits.rs | 60 - .../src/weights/bifrost_asset_registry.rs | 52 - .../src/weights/bifrost_asset_registry.rs | 52 - 18 files changed, 2496 insertions(+), 890 deletions(-) create mode 100644 pallets/asset-registry/src/migrations/mod.rs create mode 100644 pallets/asset-registry/src/migrations/v0.rs create mode 100644 pallets/asset-registry/src/migrations/v1.rs create mode 100644 pallets/deprecated/asset-registry/Cargo.toml create mode 100644 pallets/deprecated/asset-registry/src/benchmarking.rs create mode 100644 pallets/deprecated/asset-registry/src/lib.rs rename pallets/{ => deprecated}/asset-registry/src/migration.rs (100%) create mode 100644 pallets/deprecated/asset-registry/src/mock.rs create mode 100644 pallets/deprecated/asset-registry/src/tests.rs create mode 100644 pallets/deprecated/asset-registry/src/weights.rs diff --git a/pallets/asset-registry/src/benchmarking.rs b/pallets/asset-registry/src/benchmarking.rs index bb7b63b13..5c5555516 100644 --- a/pallets/asset-registry/src/benchmarking.rs +++ b/pallets/asset-registry/src/benchmarking.rs @@ -20,82 +20,12 @@ use super::*; use crate::Pallet as AssetRegistry; -use bifrost_primitives::{CurrencyId, TokenSymbol}; +use bifrost_primitives::CurrencyId; use frame_benchmarking::{benchmarks, v1::BenchmarkError}; use frame_support::{assert_ok, traits::UnfilteredDispatchable}; use sp_runtime::traits::UniqueSaturatedFrom; benchmarks! { - register_native_asset { - let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let versioned_location = VersionedLocation::V4(Location::from([Parachain(1000)])); - - let call = Call::::register_native_asset { - currency_id: Token(TokenSymbol::DOT), - location: Box::new(versioned_location.clone()), - metadata: Box::new(AssetMetadata { - name: b"Token Name".to_vec(), - symbol: b"TN".to_vec(), - decimals: 12, - minimal_balance: BalanceOf::::unique_saturated_from(1u128), - }) - }; - }: {call.dispatch_bypass_filter(origin)?} - verify { - assert_eq!( - AssetMetadatas::::get(AssetIds::NativeAssetId(Token( - TokenSymbol::DOT - ))), - Some(AssetMetadata { - name: b"Token Name".to_vec(), - symbol: b"TN".to_vec(), - decimals: 12, - minimal_balance: BalanceOf::::unique_saturated_from(1u128), - }) - ); - } - - update_native_asset { - let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let versioned_location = VersionedLocation::V4(Location::from([Parachain(1000)])); - - assert_ok!(AssetRegistry::::register_native_asset( - origin.clone(), - Token(TokenSymbol::DOT), - Box::new(versioned_location.clone()), - Box::new(AssetMetadata { - name: b"Token Name".to_vec(), - symbol: b"TN".to_vec(), - decimals: 12, - minimal_balance: BalanceOf::::unique_saturated_from(1u128), - }) - )); - - let call = Call::::update_native_asset { - currency_id: Token(TokenSymbol::DOT), - location: Box::new(versioned_location.clone()), - metadata: Box::new(AssetMetadata { - name: b"Token Name".to_vec(), - symbol: b"TN".to_vec(), - decimals: 13, - minimal_balance: BalanceOf::::unique_saturated_from(2u128), - }) - }; - }: {call.dispatch_bypass_filter(origin)?} - verify { - assert_eq!( - AssetMetadatas::::get(AssetIds::NativeAssetId(Token( - TokenSymbol::DOT - ))), - Some(AssetMetadata { - name: b"Token Name".to_vec(), - symbol: b"TN".to_vec(), - decimals: 13, - minimal_balance: BalanceOf::::unique_saturated_from(2u128), - }) - ); - } - register_token_metadata { let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; let metadata = AssetMetadata { @@ -143,70 +73,6 @@ benchmarks! { ) } - register_vstoken_metadata { - let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let metadata = AssetMetadata { - name: b"KSM Native Token".to_vec(), - symbol: b"KSM".to_vec(), - decimals: 12, - minimal_balance: BalanceOf::::unique_saturated_from(0u128), - }; - let v_metadata = AssetMetadata { - name: b"Voucher Slot KSM".to_vec(), - symbol: b"vsKSM".to_vec(), - decimals: 12, - minimal_balance: BalanceOf::::unique_saturated_from(0u128), - }; - assert_ok!(AssetRegistry::::register_token_metadata( - origin.clone(), - Box::new(metadata.clone()) - )); - - let call = Call::::register_vstoken_metadata { - token_id: 0 - }; - }: {call.dispatch_bypass_filter(origin)?} - verify { - assert_eq!( - CurrencyMetadatas::::get(CurrencyId::VSToken2(0)), - Some(v_metadata.clone()) - ) - } - - register_vsbond_metadata { - let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let metadata = AssetMetadata { - name: b"KSM Native Token".to_vec(), - symbol: b"KSM".to_vec(), - decimals: 12, - minimal_balance: BalanceOf::::unique_saturated_from(0u128), - }; - let name = "vsBOND-KSM-2001-10-20".as_bytes().to_vec(); - let v_metadata = AssetMetadata { - name: name.clone(), - symbol: name, - decimals: 12, - minimal_balance: BalanceOf::::unique_saturated_from(0u128), - }; - assert_ok!(AssetRegistry::::register_token_metadata( - origin.clone(), - Box::new(metadata.clone()) - )); - - let call = Call::::register_vsbond_metadata { - token_id: 0, - para_id:2001, - first_slot:10, - last_slot:20 - }; - }: {call.dispatch_bypass_filter(origin)?} - verify { - assert_eq!( - CurrencyMetadatas::::get(CurrencyId::VSBond2(0, 2001, 10, 20)), - Some(v_metadata.clone()) - ) - } - register_location { let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; let metadata = AssetMetadata { @@ -217,7 +83,7 @@ benchmarks! { }; let versioned_location = VersionedLocation::V4(Location::new(1, [Parachain(2001)])); - let location: xcm::v3::Location = versioned_location.clone().try_into().unwrap(); + let location: xcm::v4::Location = versioned_location.clone().try_into().unwrap(); assert_ok!(AssetRegistry::::register_token_metadata( origin.clone(), @@ -232,7 +98,7 @@ benchmarks! { }: {call.dispatch_bypass_filter(origin)?} verify { assert_eq!( - LocationToCurrencyIds::::get(location), + LocationToCurrencyIds::::get(location.clone()), Some(Token2(0)) ); assert_eq!( diff --git a/pallets/asset-registry/src/lib.rs b/pallets/asset-registry/src/lib.rs index c35d14481..edf1ca0e4 100644 --- a/pallets/asset-registry/src/lib.rs +++ b/pallets/asset-registry/src/lib.rs @@ -51,7 +51,7 @@ use xcm::{ use xcm_builder::TakeRevenue; use xcm_executor::{traits::WeightTrader, AssetsInHolding}; -pub mod migration; +pub mod migrations; mod mock; mod tests; pub mod weights; @@ -66,6 +66,14 @@ pub use weights::WeightInfo; pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +#[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)] +pub struct AssetMetadata { + pub name: Vec, + pub symbol: Vec, + pub decimals: u8, + pub minimal_balance: Balance, +} + #[frame_support::pallet] pub mod pallet { use super::*; @@ -85,14 +93,6 @@ pub mod pallet { type WeightInfo: WeightInfo; } - #[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)] - pub struct AssetMetadata { - pub name: Vec, - pub symbol: Vec, - pub decimals: u8, - pub minimal_balance: Balance, - } - #[pallet::error] pub enum Error { /// The given location could not be used (e.g. because it cannot be expressed in the @@ -142,14 +142,14 @@ pub mod pallet { /// CurrencyIdToLocations: map CurrencyId => Option #[pallet::storage] pub type CurrencyIdToLocations = - StorageMap<_, Twox64Concat, CurrencyId, xcm::v3::Location, OptionQuery>; + StorageMap<_, Twox64Concat, CurrencyId, Location, OptionQuery>; /// The storages for CurrencyIds. /// /// LocationToCurrencyIds: map Location => Option #[pallet::storage] pub type LocationToCurrencyIds = - StorageMap<_, Twox64Concat, xcm::v3::Location, CurrencyId, OptionQuery>; + StorageMap<_, Twox64Concat, Location, CurrencyId, OptionQuery>; #[pallet::storage] pub type CurrencyIdToWeights = @@ -213,30 +213,6 @@ pub mod pallet { Pallet::::do_register_metadata(*currency_id, &metadata).expect("Token register"); } - for (currency, para_id, first_slot, last_slot) in self.vsbond.iter() { - match currency { - Token(symbol) | Native(symbol) => { - AssetIdMaps::::register_vsbond_metadata( - *symbol, - *para_id, - *first_slot, - *last_slot, - ) - .expect("VSBond register"); - }, - Token2(token_id) => { - AssetIdMaps::::register_vsbond2_metadata( - *token_id, - *para_id, - *first_slot, - *last_slot, - ) - .expect("VToken register"); - }, - _ => (), - } - } - for ¤cy in self.vcurrency.iter() { match currency { CurrencyId::VToken(symbol) => { @@ -247,68 +223,21 @@ pub mod pallet { AssetIdMaps::::register_vtoken2_metadata(token_id) .expect("VToken register"); }, - CurrencyId::VSToken(symbol) => { - AssetIdMaps::::register_vstoken_metadata(symbol) - .expect("VSToken register"); - }, - CurrencyId::VSToken2(token_id) => { - AssetIdMaps::::register_vstoken2_metadata(token_id) - .expect("VSToken register"); - }, _ => (), } } } } + const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + #[pallet::pallet] #[pallet::without_storage_info] + #[pallet::storage_version(STORAGE_VERSION)] pub struct Pallet(_); #[pallet::call] impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight(T::WeightInfo::register_native_asset())] - pub fn register_native_asset( - origin: OriginFor, - currency_id: CurrencyId, - location: Box, - metadata: Box>>, - ) -> DispatchResult { - T::RegisterOrigin::ensure_origin(origin)?; - - let location: Location = - (*location).try_into().map_err(|()| Error::::BadLocation)?; - Self::do_register_native_asset(currency_id, &location, &metadata)?; - - Self::deposit_event(Event::::AssetRegistered { - asset_id: AssetIds::NativeAssetId(currency_id), - metadata: *metadata, - }); - Ok(()) - } - - #[pallet::call_index(1)] - #[pallet::weight(T::WeightInfo::update_native_asset())] - pub fn update_native_asset( - origin: OriginFor, - currency_id: CurrencyId, - location: Box, - metadata: Box>>, - ) -> DispatchResult { - T::RegisterOrigin::ensure_origin(origin)?; - - let location: Location = - (*location).try_into().map_err(|()| Error::::BadLocation)?; - Self::do_update_native_asset(currency_id, &location, &metadata)?; - - Self::deposit_event(Event::::AssetUpdated { - asset_id: AssetIds::NativeAssetId(currency_id), - metadata: *metadata, - }); - Ok(()) - } - #[pallet::call_index(2)] #[pallet::weight(T::WeightInfo::register_token_metadata())] pub fn register_token_metadata( @@ -339,55 +268,6 @@ pub mod pallet { } } - #[pallet::call_index(4)] - #[pallet::weight(T::WeightInfo::register_vstoken_metadata())] - pub fn register_vstoken_metadata( - origin: OriginFor, - token_id: TokenId, - ) -> DispatchResult { - T::RegisterOrigin::ensure_origin(origin)?; - - if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token2(token_id)) - { - let vstoken_metadata = Self::convert_to_vstoken_metadata(token_metadata); - Self::do_register_metadata(CurrencyId::VSToken2(token_id), &vstoken_metadata)?; - - return Ok(()); - } else { - return Err(Error::::CurrencyIdNotExists)?; - } - } - - #[pallet::call_index(5)] - #[pallet::weight(T::WeightInfo::register_vsbond_metadata())] - pub fn register_vsbond_metadata( - origin: OriginFor, - token_id: TokenId, - para_id: ParaId, - first_slot: LeasePeriod, - last_slot: LeasePeriod, - ) -> DispatchResult { - T::RegisterOrigin::ensure_origin(origin)?; - - if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token2(token_id)) - { - let vsbond_metadata = Self::convert_to_vsbond_metadata( - token_metadata, - para_id, - first_slot, - last_slot, - ); - Self::do_register_metadata( - CurrencyId::VSBond2(token_id, para_id, first_slot, last_slot), - &vsbond_metadata, - )?; - - return Ok(()); - } else { - return Err(Error::::CurrencyIdNotExists)?; - } - } - #[pallet::call_index(6)] #[pallet::weight(T::WeightInfo::register_location())] pub fn register_location( @@ -419,16 +299,16 @@ pub mod pallet { let location: Location = (*location).try_into().map_err(|()| Error::::BadLocation)?; - let v3_location = xcm::v3::Location::try_from(location.clone()) - .map_err(|()| Error::::BadLocation)?; + let v4_location = + Location::try_from(location.clone()).map_err(|_| Error::::BadLocation)?; ensure!( CurrencyMetadatas::::get(currency_id).is_some(), Error::::CurrencyIdNotExists ); - LocationToCurrencyIds::::insert(v3_location, currency_id); - CurrencyIdToLocations::::insert(currency_id, v3_location); + LocationToCurrencyIds::::insert(v4_location.clone(), currency_id); + CurrencyIdToLocations::::insert(currency_id, v4_location); CurrencyIdToWeights::::insert(currency_id, weight); Pallet::::deposit_event(Event::::LocationSet { currency_id, location, weight }); @@ -484,31 +364,6 @@ impl Pallet { }) } - pub fn do_register_native_asset( - currency_id: CurrencyId, - location: &Location, - metadata: &AssetMetadata>, - ) -> DispatchResult { - let v3_location = - xcm::v3::Location::try_from(location.clone()).map_err(|()| Error::::BadLocation)?; - - ensure!(LocationToCurrencyIds::::get(v3_location).is_none(), Error::::AssetIdExisted); - ensure!( - CurrencyIdToLocations::::get(currency_id).is_none(), - Error::::LocationExisted - ); - ensure!( - AssetMetadatas::::get(AssetIds::NativeAssetId(currency_id)).is_none(), - Error::::AssetIdExisted - ); - - LocationToCurrencyIds::::insert(v3_location, currency_id); - CurrencyIdToLocations::::insert(currency_id, v3_location); - AssetMetadatas::::insert(AssetIds::NativeAssetId(currency_id), metadata); - - Ok(()) - } - pub fn convert_to_vtoken_metadata( token_metadata: AssetMetadata>, ) -> AssetMetadata> { @@ -519,34 +374,6 @@ impl Pallet { AssetMetadata { name, symbol, ..token_metadata } } - pub fn convert_to_vstoken_metadata( - token_metadata: AssetMetadata>, - ) -> AssetMetadata> { - let mut name = "Voucher Slot ".as_bytes().to_vec(); - name.extend_from_slice(&token_metadata.symbol); - let mut symbol = "vs".as_bytes().to_vec(); - symbol.extend_from_slice(&token_metadata.symbol); - AssetMetadata { name, symbol, ..token_metadata } - } - - pub fn convert_to_vsbond_metadata( - token_metadata: AssetMetadata>, - para_id: ParaId, - first_slot: LeasePeriod, - last_slot: LeasePeriod, - ) -> AssetMetadata> { - let name = scale_info::prelude::format!( - "vsBOND-{}-{}-{}-{}", - core::str::from_utf8(&token_metadata.symbol).unwrap_or(""), - para_id, - first_slot, - last_slot - ) - .as_bytes() - .to_vec(); - AssetMetadata { name: name.clone(), symbol: name, ..token_metadata } - } - pub fn do_register_metadata( currency_id: CurrencyId, metadata: &AssetMetadata>, @@ -564,15 +391,15 @@ impl Pallet { } pub fn do_register_location(currency_id: CurrencyId, location: &Location) -> DispatchResult { - let v3_location = - xcm::v3::Location::try_from(location.clone()).map_err(|()| Error::::BadLocation)?; + let v4_location = + Location::try_from(location.clone()).map_err(|_| Error::::BadLocation)?; ensure!( CurrencyMetadatas::::get(currency_id).is_some(), Error::::CurrencyIdNotExists ); ensure!( - LocationToCurrencyIds::::get(v3_location).is_none(), + LocationToCurrencyIds::::get(v4_location.clone()).is_none(), Error::::CurrencyIdExisted ); ensure!( @@ -580,8 +407,8 @@ impl Pallet { Error::::LocationExisted ); - LocationToCurrencyIds::::insert(v3_location, currency_id); - CurrencyIdToLocations::::insert(currency_id, v3_location); + LocationToCurrencyIds::::insert(v4_location.clone(), currency_id); + CurrencyIdToLocations::::insert(currency_id, v4_location); Ok(()) } @@ -596,34 +423,6 @@ impl Pallet { Ok(()) } - - fn do_update_native_asset( - currency_id: CurrencyId, - location: &Location, - metadata: &AssetMetadata>, - ) -> DispatchResult { - let v3_location = - xcm::v3::Location::try_from(location.clone()).map_err(|()| Error::::BadLocation)?; - - ensure!( - LocationToCurrencyIds::::get(v3_location).is_some(), - Error::::AssetIdNotExists - ); - ensure!( - CurrencyIdToLocations::::get(currency_id).is_some(), - Error::::LocationExisted - ); - ensure!( - AssetMetadatas::::get(AssetIds::NativeAssetId(currency_id)).is_some(), - Error::::AssetIdNotExists - ); - - LocationToCurrencyIds::::insert(v3_location, currency_id); - CurrencyIdToLocations::::insert(currency_id, v3_location); - AssetMetadatas::::insert(AssetIds::NativeAssetId(currency_id), metadata); - - Ok(()) - } } pub struct AssetIdMaps(sp_std::marker::PhantomData); @@ -648,8 +447,8 @@ impl CurrencyIdMapping Option { - let v3_location = xcm::v3::Location::try_from(multi_location).ok()?; - LocationToCurrencyIds::::get(v3_location) + let v4_location = Location::try_from(multi_location).ok()?; + LocationToCurrencyIds::::get(v4_location) } } @@ -752,55 +551,6 @@ impl CurrencyIdRegister for AssetIdMaps { } } - fn register_vstoken_metadata(token_symbol: TokenSymbol) -> sp_runtime::DispatchResult { - if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token(token_symbol)) { - let vstoken_metadata = Pallet::::convert_to_vstoken_metadata(token_metadata); - Pallet::::do_register_metadata( - CurrencyId::VSToken(token_symbol), - &vstoken_metadata, - )?; - - return Ok(()); - } else { - return Err(Error::::CurrencyIdNotExists.into()); - } - } - - fn register_vsbond_metadata( - token_symbol: TokenSymbol, - para_id: ParaId, - first_slot: LeasePeriod, - last_slot: LeasePeriod, - ) -> sp_runtime::DispatchResult { - let option_token_metadata = - if CurrencyMetadatas::::contains_key(CurrencyId::Token(token_symbol)) { - CurrencyMetadatas::::get(CurrencyId::Token(token_symbol)) - } else if token_symbol == TokenSymbol::BNC && - CurrencyMetadatas::::contains_key(CurrencyId::Native(token_symbol)) - { - CurrencyMetadatas::::get(CurrencyId::Native(token_symbol)) - } else { - None - }; - - if let Some(token_metadata) = option_token_metadata { - let vsbond_metadata = Pallet::::convert_to_vsbond_metadata( - token_metadata, - para_id, - first_slot, - last_slot, - ); - Pallet::::do_register_metadata( - CurrencyId::VSBond(token_symbol, para_id, first_slot, last_slot), - &vsbond_metadata, - )?; - - return Ok(()); - } else { - return Err(Error::::CurrencyIdNotExists.into()); - } - } - fn check_token2_registered(token_id: TokenId) -> bool { CurrencyMetadatas::::get(CurrencyId::Token2(token_id)).is_some() } @@ -809,20 +559,6 @@ impl CurrencyIdRegister for AssetIdMaps { CurrencyMetadatas::::get(CurrencyId::VToken2(token_id)).is_some() } - fn check_vstoken2_registered(token_id: TokenId) -> bool { - CurrencyMetadatas::::get(CurrencyId::VSToken2(token_id)).is_some() - } - - fn check_vsbond2_registered( - token_id: TokenId, - para_id: ParaId, - first_slot: LeasePeriod, - last_slot: LeasePeriod, - ) -> bool { - CurrencyMetadatas::::get(CurrencyId::VSBond2(token_id, para_id, first_slot, last_slot)) - .is_some() - } - fn register_vtoken2_metadata(token_id: TokenId) -> DispatchResult { if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token2(token_id)) { let vtoken_metadata = Pallet::::convert_to_vtoken_metadata(token_metadata); @@ -834,41 +570,6 @@ impl CurrencyIdRegister for AssetIdMaps { } } - fn register_vstoken2_metadata(token_id: TokenId) -> DispatchResult { - if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token2(token_id)) { - let vstoken_metadata = Pallet::::convert_to_vstoken_metadata(token_metadata); - Pallet::::do_register_metadata(CurrencyId::VSToken2(token_id), &vstoken_metadata)?; - - return Ok(()); - } else { - return Err(Error::::CurrencyIdNotExists.into()); - } - } - - fn register_vsbond2_metadata( - token_id: TokenId, - para_id: ParaId, - first_slot: LeasePeriod, - last_slot: LeasePeriod, - ) -> DispatchResult { - if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token2(token_id)) { - let vsbond_metadata = Pallet::::convert_to_vsbond_metadata( - token_metadata, - para_id, - first_slot, - last_slot, - ); - Pallet::::do_register_metadata( - CurrencyId::VSBond2(token_id, para_id, first_slot, last_slot), - &vsbond_metadata, - )?; - - return Ok(()); - } else { - return Err(Error::::CurrencyIdNotExists.into()); - } - } - fn register_blp_metadata(pool_id: PoolId, decimals: u8) -> DispatchResult { let name = scale_info::prelude::format!("Bifrost Stable Pool Token {}", pool_id) .as_bytes() @@ -931,10 +632,10 @@ where let AssetId(ref location) = asset_id.clone(); log::debug!(target: "asset-registry::weight", "buy_weight location: {:?}", location); - let v3_location = - xcm::v3::Location::try_from(location.clone()).map_err(|_| XcmError::InvalidLocation)?; + let v4_location = + Location::try_from(location.clone()).map_err(|_| XcmError::InvalidLocation)?; - if let Some(currency_id) = LocationToCurrencyIds::::get(v3_location) { + if let Some(currency_id) = LocationToCurrencyIds::::get(v4_location) { if let Some(currency_metadatas) = CurrencyMetadatas::::get(currency_id) { // The integration tests can ensure the ed is non-zero. let ed_ratio = FixedU128::saturating_from_rational( diff --git a/pallets/asset-registry/src/migrations/mod.rs b/pallets/asset-registry/src/migrations/mod.rs new file mode 100644 index 000000000..306e9e560 --- /dev/null +++ b/pallets/asset-registry/src/migrations/mod.rs @@ -0,0 +1,19 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +pub mod v0; +pub mod v1; diff --git a/pallets/asset-registry/src/migrations/v0.rs b/pallets/asset-registry/src/migrations/v0.rs new file mode 100644 index 000000000..e194e5eef --- /dev/null +++ b/pallets/asset-registry/src/migrations/v0.rs @@ -0,0 +1,131 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +use crate::*; +use bifrost_primitives::{CurrencyId, BNC}; +use frame_support::traits::{Get, OnRuntimeUpgrade}; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; +use xcm::opaque::v3::Junctions::X1; + +const LOG_TARGET: &str = "asset-registry::migration"; + +pub fn update_blp_metadata(pool_count: u32) -> Weight { + for pool_id in 0..pool_count { + if let Some(old_metadata) = CurrencyMetadatas::::get(CurrencyId::BLP(pool_id)) { + let name = scale_info::prelude::format!("Bifrost Stable Pool Token {}", pool_id) + .as_bytes() + .to_vec(); + let symbol = scale_info::prelude::format!("BLP{}", pool_id).as_bytes().to_vec(); + CurrencyMetadatas::::insert( + CurrencyId::BLP(pool_id), + &AssetMetadata { name, symbol, ..old_metadata }, + ) + } + } + + T::DbWeight::get().reads(pool_count.into()) + T::DbWeight::get().writes(pool_count.into()) +} + +const BNC_LOCATION: xcm::v3::Location = xcm::v3::Location { + parents: 0, + interior: X1(xcm::v3::Junction::GeneralKey { + length: 2, + data: [ + 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, + ], + }), +}; + +pub struct InsertBNCMetadata(PhantomData); +impl OnRuntimeUpgrade for InsertBNCMetadata { + fn on_runtime_upgrade() -> Weight { + log::info!(target: LOG_TARGET, "Start to insert BNC Metadata..."); + CurrencyMetadatas::::insert( + BNC, + &AssetMetadata { + name: b"Bifrost Native Token".to_vec(), + symbol: b"BNC".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(10_000_000_000u128), + }, + ); + + match Location::try_from(BNC_LOCATION) { + Ok(location) => { + CurrencyIdToLocations::::insert(BNC, location.clone()); + LocationToCurrencyIds::::insert(location, BNC); + + Weight::from(T::DbWeight::get().reads_writes(3 as u64 + 1, 3 as u64 + 1)) + }, + Err(_) => { + log::error!(target: LOG_TARGET, "Conversion failed from BNC_LOCATION to v4_bnc_location."); + Weight::from(T::DbWeight::get().reads_writes(1 as u64 + 1, 1 as u64 + 1)) + }, + } + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, TryRuntimeError> { + let bnc_location = Location::try_from(BNC_LOCATION).unwrap(); + assert!(LocationToCurrencyIds::::get(bnc_location).is_none()); + + Ok(sp_std::vec![]) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_cnt: Vec) -> Result<(), TryRuntimeError> { + let metadata = CurrencyMetadatas::::get(BNC); + assert_eq!( + metadata, + Some(AssetMetadata { + name: b"Bifrost Native Token".to_vec(), + symbol: b"BNC".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(10_000_000_000u128), + }) + ); + log::info!( + target: LOG_TARGET, + "InsertBNCMetadata post-migrate storage: {:?}", + metadata + ); + + let bnc_location = Location::try_from(BNC_LOCATION).unwrap(); + + let location = CurrencyIdToLocations::::get(BNC); + assert_eq!(location, Some(bnc_location.clone())); + + log::info!( + target: LOG_TARGET, + "InsertBNCMetadata post-migrate storage: {:?}", + location + ); + + let currency = LocationToCurrencyIds::::get(bnc_location); + assert_eq!(currency, Some(BNC)); + log::info!( + target: LOG_TARGET, + "InsertBNCMetadata post-migrate storage: {:?}", + currency + ); + + Ok(()) + } +} diff --git a/pallets/asset-registry/src/migrations/v1.rs b/pallets/asset-registry/src/migrations/v1.rs new file mode 100644 index 000000000..99a7481a2 --- /dev/null +++ b/pallets/asset-registry/src/migrations/v1.rs @@ -0,0 +1,118 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +use crate::*; +use frame_support::traits::OnRuntimeUpgrade; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; + +const LOG_TARGET: &str = "asset-registry::migration"; + +pub struct MigrateToV1(sp_std::marker::PhantomData); +impl OnRuntimeUpgrade for MigrateToV1 { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + // Check the storage version + let onchain_version = Pallet::::on_chain_storage_version(); + // Transform storage values + // We transform the storage values from the old into the new format. + if onchain_version < 1 { + let mut count = 0; + + log::info!(target: LOG_TARGET, "Start to migrate RegisterWhiteList storage..."); + CurrencyIdToLocations::::translate::( + |k: CurrencyId, value: xcm::v3::Location| { + log::info!(target: LOG_TARGET, "CurrencyIdToLocations Migrated to xcm::v4::Location for {:?}...", k); + let v4_location = xcm::v4::Location::try_from(value).unwrap(); + + count += 1; + Some(v4_location) + }, + ); + + log::info!(target: LOG_TARGET, "Start to migrate LocationToCurrencyIds storage..."); + let migrated_items: Vec<_> = LocationToCurrencyIds::::drain() + .map(|(v3_location, value)| { + log::info!(target: LOG_TARGET, "LocationToCurrencyIds Migrated to xcm::v4::Location for {:?}...", value); + let v4_location = xcm::v4::Location::try_from(v3_location).unwrap(); + + count += 1; + (v4_location, value) + }) + .collect(); + for (v4_location, value) in migrated_items { + LocationToCurrencyIds::::insert(v4_location, value); + } + + // Update the storage version + StorageVersion::new(1).put::>(); + + // Return the consumed weight + Weight::from(T::DbWeight::get().reads_writes(count as u64 + 1, count as u64 + 1)) + } else { + // We don't do anything here. + Weight::zero() + } + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, TryRuntimeError> { + let currency_id_to_locations_count = CurrencyIdToLocations::::iter().count(); + log::info!(target: LOG_TARGET, "CurrencyIdToLocations pre-migrate storage count: {:?}", currency_id_to_locations_count); + + let location_to_currency_ids_count = LocationToCurrencyIds::::iter().count(); + log::info!(target: LOG_TARGET, "LocationToCurrencyIds pre-migrate storage count: {:?}", location_to_currency_ids_count); + + let combined_data = + (currency_id_to_locations_count as u64, location_to_currency_ids_count as u64); + + Ok(combined_data.encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(cnt: Vec) -> Result<(), TryRuntimeError> { + let (old_currency_id_to_locations_count, old_location_to_currency_ids_count): (u64, u64) = + Decode::decode(&mut cnt.as_slice()).expect( + "the state parameter should be something that was generated by pre_upgrade", + ); + + let new_currency_id_to_locations_count = CurrencyIdToLocations::::iter().count(); + log::info!( + target: LOG_TARGET, + "CurrencyIdToLocations post-migrate storage count: {:?}", + new_currency_id_to_locations_count + ); + + let new_location_to_currency_ids_count = LocationToCurrencyIds::::iter().count(); + log::info!( + target: LOG_TARGET, + "LocationToCurrencyIds post-migrate storage count: {:?}", + new_location_to_currency_ids_count + ); + + ensure!( + new_currency_id_to_locations_count as u64 == old_currency_id_to_locations_count, + "Post-migration CurrencyIdToLocations count does not match pre-migration count" + ); + ensure!( + new_location_to_currency_ids_count as u64 == old_location_to_currency_ids_count, + "Post-migration LocationToCurrencyIds count does not match pre-migration count" + ); + + Ok(()) + } +} diff --git a/pallets/asset-registry/src/tests.rs b/pallets/asset-registry/src/tests.rs index 470a22438..f16a42416 100644 --- a/pallets/asset-registry/src/tests.rs +++ b/pallets/asset-registry/src/tests.rs @@ -21,7 +21,6 @@ #![cfg(test)] use super::*; -use bifrost_primitives::TokenSymbol; use frame_support::{assert_noop, assert_ok}; use mock::{ AssetRegistry, CouncilAccount, ExtBuilder, Runtime, RuntimeEvent, RuntimeOrigin, System, @@ -36,125 +35,6 @@ fn versioned_multi_location_convert_work() { }); } -#[test] -fn register_native_asset_works() { - ExtBuilder::default().build().execute_with(|| { - let versioned_location = VersionedLocation::V4(Location::from([Parachain(1000)])); - - assert_ok!(AssetRegistry::register_native_asset( - RuntimeOrigin::signed(CouncilAccount::get()), - Token(TokenSymbol::DOT), - Box::new(versioned_location.clone()), - Box::new(AssetMetadata { - name: b"Token Name".to_vec(), - symbol: b"TN".to_vec(), - decimals: 12, - minimal_balance: 1, - }) - )); - System::assert_last_event(RuntimeEvent::AssetRegistry(Event::AssetRegistered { - asset_id: AssetIds::NativeAssetId(Token(TokenSymbol::DOT)), - metadata: AssetMetadata { - name: b"Token Name".to_vec(), - symbol: b"TN".to_vec(), - decimals: 12, - minimal_balance: 1, - }, - })); - - assert_eq!( - AssetMetadatas::::get(AssetIds::NativeAssetId(Token(TokenSymbol::DOT))), - Some(AssetMetadata { - name: b"Token Name".to_vec(), - symbol: b"TN".to_vec(), - decimals: 12, - minimal_balance: 1, - }) - ); - // Can't duplicate - assert_noop!( - AssetRegistry::register_native_asset( - RuntimeOrigin::signed(CouncilAccount::get()), - Token(TokenSymbol::DOT), - Box::new(versioned_location), - Box::new(AssetMetadata { - name: b"Token Name".to_vec(), - symbol: b"TN".to_vec(), - decimals: 12, - minimal_balance: 1, - }) - ), - Error::::AssetIdExisted - ); - }); -} - -#[test] -fn update_native_asset_works() { - let versioned_location = VersionedLocation::V4(Location::from([Parachain(1000)])); - - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - AssetRegistry::update_native_asset( - RuntimeOrigin::signed(CouncilAccount::get()), - Token(TokenSymbol::DOT), - Box::new(versioned_location.clone()), - Box::new(AssetMetadata { - name: b"New Token Name".to_vec(), - symbol: b"NTN".to_vec(), - decimals: 13, - minimal_balance: 2, - }) - ), - Error::::AssetIdNotExists - ); - - assert_ok!(AssetRegistry::register_native_asset( - RuntimeOrigin::signed(CouncilAccount::get()), - Token(TokenSymbol::DOT), - Box::new(versioned_location.clone()), - Box::new(AssetMetadata { - name: b"Token Name".to_vec(), - symbol: b"TN".to_vec(), - decimals: 12, - minimal_balance: 1, - }) - )); - - assert_ok!(AssetRegistry::update_native_asset( - RuntimeOrigin::signed(CouncilAccount::get()), - Token(TokenSymbol::DOT), - Box::new(versioned_location.clone()), - Box::new(AssetMetadata { - name: b"New Token Name".to_vec(), - symbol: b"NTN".to_vec(), - decimals: 13, - minimal_balance: 2, - }) - )); - - System::assert_last_event(RuntimeEvent::AssetRegistry(Event::AssetUpdated { - asset_id: AssetIds::NativeAssetId(Token(TokenSymbol::DOT)), - metadata: AssetMetadata { - name: b"New Token Name".to_vec(), - symbol: b"NTN".to_vec(), - decimals: 13, - minimal_balance: 2, - }, - })); - - assert_eq!( - AssetMetadatas::::get(AssetIds::NativeAssetId(Token(TokenSymbol::DOT))), - Some(AssetMetadata { - name: b"New Token Name".to_vec(), - symbol: b"NTN".to_vec(), - decimals: 13, - minimal_balance: 2, - }) - ); - }); -} - #[test] fn register_token_metadata_should_work() { ExtBuilder::default().build().execute_with(|| { @@ -214,86 +94,6 @@ fn register_vtoken_metadata_should_work() { }) } -#[test] -fn register_vstoken_metadata_should_work() { - ExtBuilder::default().build().execute_with(|| { - let metadata = AssetMetadata { - name: b"KSM Native Token".to_vec(), - symbol: b"KSM".to_vec(), - decimals: 12, - minimal_balance: 0, - }; - let v_metadata = AssetMetadata { - name: b"Voucher Slot KSM".to_vec(), - symbol: b"vsKSM".to_vec(), - decimals: 12, - minimal_balance: 0, - }; - assert_noop!( - AssetRegistry::register_vtoken_metadata( - RuntimeOrigin::signed(CouncilAccount::get()), - 1 - ), - Error::::CurrencyIdNotExists - ); - - assert_ok!(AssetRegistry::register_token_metadata( - RuntimeOrigin::signed(CouncilAccount::get()), - Box::new(metadata.clone()) - )); - - assert_ok!(AssetRegistry::register_vstoken_metadata( - RuntimeOrigin::signed(CouncilAccount::get()), - 0 - )); - - assert_eq!( - CurrencyMetadatas::::get(CurrencyId::VSToken2(0)), - Some(v_metadata.clone()) - ) - }) -} - -#[test] -fn register_vsbond_metadata_should_work() { - ExtBuilder::default().build().execute_with(|| { - let metadata = AssetMetadata { - name: b"KSM Native Token".to_vec(), - symbol: b"KSM".to_vec(), - decimals: 12, - minimal_balance: 0, - }; - let name = "vsBOND-KSM-2001-10-20".as_bytes().to_vec(); - let v_metadata = - AssetMetadata { name: name.clone(), symbol: name, decimals: 12, minimal_balance: 0 }; - assert_noop!( - AssetRegistry::register_vtoken_metadata( - RuntimeOrigin::signed(CouncilAccount::get()), - 1 - ), - Error::::CurrencyIdNotExists - ); - - assert_ok!(AssetRegistry::register_token_metadata( - RuntimeOrigin::signed(CouncilAccount::get()), - Box::new(metadata.clone()) - )); - - assert_ok!(AssetRegistry::register_vsbond_metadata( - RuntimeOrigin::signed(CouncilAccount::get()), - 0, - 2001, - 10, - 20 - )); - - assert_eq!( - CurrencyMetadatas::::get(CurrencyId::VSBond2(0, 2001, 10, 20)), - Some(v_metadata.clone()) - ) - }) -} - #[test] fn register_multilocation_should_work() { ExtBuilder::default().build().execute_with(|| { @@ -305,7 +105,7 @@ fn register_multilocation_should_work() { }; let versioned_location = VersionedLocation::V4(Location::new(1, [Parachain(2001)])); - let location: xcm::v3::Location = versioned_location.clone().try_into().unwrap(); + let location: Location = versioned_location.clone().try_into().unwrap(); assert_noop!( AssetRegistry::register_location( @@ -339,7 +139,7 @@ fn register_multilocation_should_work() { Error::::CurrencyIdExisted ); - assert_eq!(LocationToCurrencyIds::::get(location), Some(Token2(0))); + assert_eq!(LocationToCurrencyIds::::get(location.clone()), Some(Token2(0))); assert_eq!(CurrencyIdToLocations::::get(Token2(0)), Some(location)); assert_eq!( CurrencyIdToWeights::::get(Token2(0)), @@ -358,7 +158,7 @@ fn force_set_multilocation_should_work() { minimal_balance: 0, }; let versioned_location = VersionedLocation::V4(Location::new(1, [Parachain(2001)])); - let location: xcm::v3::Location = versioned_location.clone().try_into().unwrap(); + let location: Location = versioned_location.clone().try_into().unwrap(); assert_noop!( AssetRegistry::force_set_location( @@ -389,7 +189,7 @@ fn force_set_multilocation_should_work() { Weight::from_parts(2000_000_000, 0) )); - assert_eq!(LocationToCurrencyIds::::get(location), Some(Token2(0))); + assert_eq!(LocationToCurrencyIds::::get(location.clone()), Some(Token2(0))); assert_eq!(CurrencyIdToLocations::::get(Token2(0)), Some(location)); assert_eq!( CurrencyIdToWeights::::get(Token2(0)), diff --git a/pallets/asset-registry/src/weights.rs b/pallets/asset-registry/src/weights.rs index 162c6fad6..b16619e2e 100644 --- a/pallets/asset-registry/src/weights.rs +++ b/pallets/asset-registry/src/weights.rs @@ -53,12 +53,8 @@ use sp_std::marker::PhantomData; /// Weight functions needed for bifrost_asset_registry. pub trait WeightInfo { - fn register_native_asset() -> Weight; - fn update_native_asset() -> Weight; fn register_token_metadata() -> Weight; fn register_vtoken_metadata() -> Weight; - fn register_vstoken_metadata() -> Weight; - fn register_vsbond_metadata() -> Weight; fn register_location() -> Weight; fn force_set_location() -> Weight; fn update_currency_metadata() -> Weight; @@ -66,36 +62,6 @@ pub trait WeightInfo { // For backwards compatibility and tests impl WeightInfo for () { - /// Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) - /// Proof Skipped: AssetRegistry LocationToCurrencyIds (max_values: None, max_size: None, mode: Measured) - /// Storage: AssetRegistry CurrencyIdToLocations (r:1 w:1) - /// Proof Skipped: AssetRegistry CurrencyIdToLocations (max_values: None, max_size: None, mode: Measured) - /// Storage: AssetRegistry AssetMetadatas (r:1 w:1) - /// Proof Skipped: AssetRegistry AssetMetadatas (max_values: None, max_size: None, mode: Measured) - fn register_native_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `118` - // Estimated: `3583` - // Minimum execution time: 52_056_000 picoseconds. - Weight::from_parts(53_012_000, 3583) - .saturating_add(RocksDbWeight::get().reads(3_u64)) - .saturating_add(RocksDbWeight::get().writes(3_u64)) - } - /// Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) - /// Proof Skipped: AssetRegistry LocationToCurrencyIds (max_values: None, max_size: None, mode: Measured) - /// Storage: AssetRegistry CurrencyIdToLocations (r:1 w:1) - /// Proof Skipped: AssetRegistry CurrencyIdToLocations (max_values: None, max_size: None, mode: Measured) - /// Storage: AssetRegistry AssetMetadatas (r:1 w:1) - /// Proof Skipped: AssetRegistry AssetMetadatas (max_values: None, max_size: None, mode: Measured) - fn update_native_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `250` - // Estimated: `3715` - // Minimum execution time: 59_891_000 picoseconds. - Weight::from_parts(60_869_000, 3715) - .saturating_add(RocksDbWeight::get().reads(3_u64)) - .saturating_add(RocksDbWeight::get().writes(3_u64)) - } /// Storage: AssetRegistry NextTokenId (r:1 w:1) /// Proof Skipped: AssetRegistry NextTokenId (max_values: Some(1), max_size: None, mode: Measured) /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:1) @@ -120,28 +86,6 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: AssetRegistry CurrencyMetadatas (r:2 w:1) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - fn register_vstoken_metadata() -> Weight { - // Proof Size summary in bytes: - // Measured: `705` - // Estimated: `6645` - // Minimum execution time: 52_491_000 picoseconds. - Weight::from_parts(53_682_000, 6645) - .saturating_add(RocksDbWeight::get().reads(2_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - /// Storage: AssetRegistry CurrencyMetadatas (r:2 w:1) - /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - fn register_vsbond_metadata() -> Weight { - // Proof Size summary in bytes: - // Measured: `763` - // Estimated: `6703` - // Minimum execution time: 55_589_000 picoseconds. - Weight::from_parts(56_804_000, 6703) - .saturating_add(RocksDbWeight::get().reads(2_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) /// Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) diff --git a/pallets/deprecated/asset-registry/Cargo.toml b/pallets/deprecated/asset-registry/Cargo.toml new file mode 100644 index 000000000..c6e22cd68 --- /dev/null +++ b/pallets/deprecated/asset-registry/Cargo.toml @@ -0,0 +1,51 @@ +[package] +name = "bifrost-asset-registry" +version = "0.8.0" +authors = ["Edwin Wang "] +edition = "2021" + +[dependencies] +log = { workspace = true } +serde = { workspace = true } +scale-info = { workspace = true, features = ["derive"] } +parity-scale-codec = { workspace = true, features = ["derive"] } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-benchmarking = { workspace = true, optional = true } +bifrost-primitives = { workspace = true } + +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } + +[dev-dependencies] +sp-io = { workspace = true } +pallet-balances = { workspace = true } + +[features] +default = ["std"] +std = [ + "serde/std", + "log/std", + "parity-scale-codec/std", + "scale-info/std", + "sp-runtime/std", + "sp-std/std", + "frame-support/std", + "frame-system/std", + "frame-benchmarking?/std", + "bifrost-primitives/std", + "xcm/std", + "xcm-builder/std", + "xcm-executor/std", +] +try-runtime = ["frame-support/try-runtime"] + +runtime-benchmarks = [ + "frame-benchmarking", + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", +] diff --git a/pallets/deprecated/asset-registry/src/benchmarking.rs b/pallets/deprecated/asset-registry/src/benchmarking.rs new file mode 100644 index 000000000..bb7b63b13 --- /dev/null +++ b/pallets/deprecated/asset-registry/src/benchmarking.rs @@ -0,0 +1,309 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +#![cfg(feature = "runtime-benchmarks")] + +use super::*; +use crate::Pallet as AssetRegistry; +use bifrost_primitives::{CurrencyId, TokenSymbol}; +use frame_benchmarking::{benchmarks, v1::BenchmarkError}; +use frame_support::{assert_ok, traits::UnfilteredDispatchable}; +use sp_runtime::traits::UniqueSaturatedFrom; + +benchmarks! { + register_native_asset { + let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let versioned_location = VersionedLocation::V4(Location::from([Parachain(1000)])); + + let call = Call::::register_native_asset { + currency_id: Token(TokenSymbol::DOT), + location: Box::new(versioned_location.clone()), + metadata: Box::new(AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(1u128), + }) + }; + }: {call.dispatch_bypass_filter(origin)?} + verify { + assert_eq!( + AssetMetadatas::::get(AssetIds::NativeAssetId(Token( + TokenSymbol::DOT + ))), + Some(AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(1u128), + }) + ); + } + + update_native_asset { + let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let versioned_location = VersionedLocation::V4(Location::from([Parachain(1000)])); + + assert_ok!(AssetRegistry::::register_native_asset( + origin.clone(), + Token(TokenSymbol::DOT), + Box::new(versioned_location.clone()), + Box::new(AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(1u128), + }) + )); + + let call = Call::::update_native_asset { + currency_id: Token(TokenSymbol::DOT), + location: Box::new(versioned_location.clone()), + metadata: Box::new(AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 13, + minimal_balance: BalanceOf::::unique_saturated_from(2u128), + }) + }; + }: {call.dispatch_bypass_filter(origin)?} + verify { + assert_eq!( + AssetMetadatas::::get(AssetIds::NativeAssetId(Token( + TokenSymbol::DOT + ))), + Some(AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 13, + minimal_balance: BalanceOf::::unique_saturated_from(2u128), + }) + ); + } + + register_token_metadata { + let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let metadata = AssetMetadata { + name: b"Bifrost Native Coin".to_vec(), + symbol: b"BNC".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(0u128), + }; + + let call = Call::::register_token_metadata { + metadata: Box::new(metadata.clone()) + }; + }: {call.dispatch_bypass_filter(origin)?} + verify { + assert_eq!(CurrencyMetadatas::::get(Token2(0)), Some(metadata.clone())) + } + + register_vtoken_metadata { + let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let metadata = AssetMetadata { + name: b"Bifrost Native Coin".to_vec(), + symbol: b"BNC".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(0u128), + }; + let v_metadata = AssetMetadata { + name: b"Voucher BNC".to_vec(), + symbol: b"vBNC".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(0u128), + }; + assert_ok!(AssetRegistry::::register_token_metadata( + origin.clone(), + Box::new(metadata.clone()) + )); + + let call = Call::::register_vtoken_metadata { + token_id: 0 + }; + }: {call.dispatch_bypass_filter(origin)?} + verify { + assert_eq!( + CurrencyMetadatas::::get(CurrencyId::VToken2(0)), + Some(v_metadata.clone()) + ) + } + + register_vstoken_metadata { + let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let metadata = AssetMetadata { + name: b"KSM Native Token".to_vec(), + symbol: b"KSM".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(0u128), + }; + let v_metadata = AssetMetadata { + name: b"Voucher Slot KSM".to_vec(), + symbol: b"vsKSM".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(0u128), + }; + assert_ok!(AssetRegistry::::register_token_metadata( + origin.clone(), + Box::new(metadata.clone()) + )); + + let call = Call::::register_vstoken_metadata { + token_id: 0 + }; + }: {call.dispatch_bypass_filter(origin)?} + verify { + assert_eq!( + CurrencyMetadatas::::get(CurrencyId::VSToken2(0)), + Some(v_metadata.clone()) + ) + } + + register_vsbond_metadata { + let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let metadata = AssetMetadata { + name: b"KSM Native Token".to_vec(), + symbol: b"KSM".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(0u128), + }; + let name = "vsBOND-KSM-2001-10-20".as_bytes().to_vec(); + let v_metadata = AssetMetadata { + name: name.clone(), + symbol: name, + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(0u128), + }; + assert_ok!(AssetRegistry::::register_token_metadata( + origin.clone(), + Box::new(metadata.clone()) + )); + + let call = Call::::register_vsbond_metadata { + token_id: 0, + para_id:2001, + first_slot:10, + last_slot:20 + }; + }: {call.dispatch_bypass_filter(origin)?} + verify { + assert_eq!( + CurrencyMetadatas::::get(CurrencyId::VSBond2(0, 2001, 10, 20)), + Some(v_metadata.clone()) + ) + } + + register_location { + let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let metadata = AssetMetadata { + name: b"Bifrost Native Coin".to_vec(), + symbol: b"BNC".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(0u128), + }; + let versioned_location = VersionedLocation::V4(Location::new(1, [Parachain(2001)])); + + let location: xcm::v3::Location = versioned_location.clone().try_into().unwrap(); + + assert_ok!(AssetRegistry::::register_token_metadata( + origin.clone(), + Box::new(metadata.clone()) + )); + + let call = Call::::register_location { + currency_id: Token2(0), + location:Box::new(versioned_location.clone()), + weight:Weight::from_parts(2000_000_000, u64::MAX), + }; + }: {call.dispatch_bypass_filter(origin)?} + verify { + assert_eq!( + LocationToCurrencyIds::::get(location), + Some(Token2(0)) + ); + assert_eq!( + CurrencyIdToLocations::::get(Token2(0)), + Some(location) + ); + assert_eq!(CurrencyIdToWeights::::get(Token2(0)), Some(Weight::from_parts(2000_000_000, u64::MAX))); + } + + force_set_location { + let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let metadata = AssetMetadata { + name: b"Bifrost Native Coin".to_vec(), + symbol: b"BNC".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(0u128), + }; + let versioned_location = VersionedLocation::V4(Location::new(1, [Parachain(2001)])); + + let location: xcm::v3::Location = versioned_location.clone().try_into().unwrap(); + + assert_ok!(AssetRegistry::::register_token_metadata( + origin.clone(), + Box::new(metadata.clone()) + )); + + let call = Call::::force_set_location { + currency_id: Token2(0), + location:Box::new(versioned_location.clone()), + weight:Weight::from_parts(2000_000_000, u64::MAX), + }; + }: {call.dispatch_bypass_filter(origin)?} + + update_currency_metadata { + let origin = T::RegisterOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + + assert_ok!(AssetRegistry::::register_token_metadata( + origin.clone(), + Box::new(AssetMetadata { + name: b"Old Token Name".to_vec(), + symbol: b"OTN".to_vec(), + decimals: 10, + minimal_balance: BalanceOf::::unique_saturated_from(1u128), + }) + )); + + let call = Call::::update_currency_metadata { + currency_id: CurrencyId::Token2(0), + asset_name: Some(b"Token Name".to_vec()), + asset_symbol: Some(b"TN".to_vec()), + asset_decimals : Some(12), + asset_minimal_balance : Some(BalanceOf::::unique_saturated_from(1000u128)), + }; + + }: {call.dispatch_bypass_filter(origin)?} + verify { + assert_eq!( + CurrencyMetadatas::::get(CurrencyId::Token2(0)), + Some(AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 12, + minimal_balance: BalanceOf::::unique_saturated_from(1000u128), + }) + ); + } + + impl_benchmark_test_suite!( + AssetRegistry, + crate::mock::ExtBuilder::default().build(), + crate::mock::Runtime +); + +} diff --git a/pallets/deprecated/asset-registry/src/lib.rs b/pallets/deprecated/asset-registry/src/lib.rs new file mode 100644 index 000000000..c35d14481 --- /dev/null +++ b/pallets/deprecated/asset-registry/src/lib.rs @@ -0,0 +1,1013 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! # Asset Registry Module +//! +//! Local and foreign assets management. The foreign assets can be updated without runtime upgrade. + +#![cfg_attr(not(feature = "std"), no_std)] + +pub use bifrost_primitives::{ + AssetIds, CurrencyId, + CurrencyId::{Native, Token, Token2}, + CurrencyIdConversion, CurrencyIdMapping, CurrencyIdRegister, ForeignAssetId, LeasePeriod, + ParaId, PoolId, TokenId, TokenInfo, TokenSymbol, +}; +use frame_support::{ + dispatch::DispatchResult, + ensure, + pallet_prelude::*, + traits::{Currency, EnsureOrigin}, + weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}, +}; +use frame_system::pallet_prelude::*; +use scale_info::{prelude::string::String, TypeInfo}; +use sp_runtime::{ + traits::{One, UniqueSaturatedFrom}, + ArithmeticError, FixedPointNumber, FixedU128, RuntimeDebug, +}; +use sp_std::{boxed::Box, vec::Vec}; +use xcm::{ + opaque::lts::XcmContext, + v3::MultiLocation, + v4::{prelude::*, Asset, Location}, + VersionedLocation, +}; +use xcm_builder::TakeRevenue; +use xcm_executor::{traits::WeightTrader, AssetsInHolding}; + +pub mod migration; +mod mock; +mod tests; +pub mod weights; + +#[cfg(feature = "runtime-benchmarks")] +mod benchmarking; + +pub use pallet::*; +pub use weights::WeightInfo; + +/// Type alias for currency balance. +pub type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + + /// Currency type for withdraw and balance storage. + type Currency: Currency; + + /// Required origin for registering asset. + type RegisterOrigin: EnsureOrigin; + + /// Weight information for the extrinsics in this module. + type WeightInfo: WeightInfo; + } + + #[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)] + pub struct AssetMetadata { + pub name: Vec, + pub symbol: Vec, + pub decimals: u8, + pub minimal_balance: Balance, + } + + #[pallet::error] + pub enum Error { + /// The given location could not be used (e.g. because it cannot be expressed in the + /// desired version of XCM). + BadLocation, + /// Location existed + LocationExisted, + /// AssetId not exists + AssetIdNotExists, + /// AssetId exists + AssetIdExisted, + /// CurrencyId not exists + CurrencyIdNotExists, + /// CurrencyId exists + CurrencyIdExisted, + } + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// The asset registered. + AssetRegistered { asset_id: AssetIds, metadata: AssetMetadata> }, + /// The asset updated. + AssetUpdated { asset_id: AssetIds, metadata: AssetMetadata> }, + /// The CurrencyId registered. + CurrencyIdRegistered { currency_id: CurrencyId, metadata: AssetMetadata> }, + /// Location Force set. + LocationSet { currency_id: CurrencyId, location: Location, weight: Weight }, + /// The CurrencyId updated. + CurrencyIdUpdated { currency_id: CurrencyId, metadata: AssetMetadata> }, + } + + /// Next available Foreign AssetId ID. + /// + /// NextForeignAssetId: ForeignAssetId + #[pallet::storage] + pub type NextForeignAssetId = StorageValue<_, ForeignAssetId, ValueQuery>; + + /// Next available TokenId ID. + /// + /// NextTokenId: TokenId + #[pallet::storage] + pub type NextTokenId = StorageValue<_, TokenId, ValueQuery>; + + /// The storages for Locations. + /// + /// CurrencyIdToLocations: map CurrencyId => Option + #[pallet::storage] + pub type CurrencyIdToLocations = + StorageMap<_, Twox64Concat, CurrencyId, xcm::v3::Location, OptionQuery>; + + /// The storages for CurrencyIds. + /// + /// LocationToCurrencyIds: map Location => Option + #[pallet::storage] + pub type LocationToCurrencyIds = + StorageMap<_, Twox64Concat, xcm::v3::Location, CurrencyId, OptionQuery>; + + #[pallet::storage] + pub type CurrencyIdToWeights = + StorageMap<_, Twox64Concat, CurrencyId, Weight, OptionQuery>; + + /// The storages for AssetMetadatas. + /// + /// AssetMetadatas: map AssetIds => Option + #[pallet::storage] + pub type AssetMetadatas = + StorageMap<_, Twox64Concat, AssetIds, AssetMetadata>, OptionQuery>; + + /// The storages for AssetMetadata. + /// + /// CurrencyMetadatas: map CurrencyId => Option + #[pallet::storage] + pub type CurrencyMetadatas = + StorageMap<_, Twox64Concat, CurrencyId, AssetMetadata>, OptionQuery>; + + #[pallet::genesis_config] + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + pub currency: Vec<(CurrencyId, BalanceOf, Option<(String, String, u8)>)>, + pub vcurrency: Vec, + pub vsbond: Vec<(CurrencyId, u32, u32, u32)>, + pub phantom: PhantomData, + } + + #[pallet::genesis_build] + impl BuildGenesisConfig for GenesisConfig { + fn build(&self) { + for (currency_id, metadata) in + self.currency.iter().map(|(currency_id, minimal_balance, metadata)| { + ( + currency_id, + match &metadata { + None => AssetMetadata { + name: currency_id + .name() + .map(|s| s.as_bytes().to_vec()) + .unwrap_or_default(), + symbol: currency_id + .symbol() + .map(|s| s.as_bytes().to_vec()) + .unwrap_or_default(), + decimals: currency_id.decimals().unwrap_or_default(), + minimal_balance: *minimal_balance, + }, + Some(metadata) => AssetMetadata { + name: metadata.0.as_bytes().to_vec(), + symbol: metadata.1.as_bytes().to_vec(), + decimals: metadata.2, + minimal_balance: *minimal_balance, + }, + }, + ) + }) { + if let CurrencyId::Token2(_token_id) = *currency_id { + Pallet::::get_next_token_id().expect("Token register"); + } + Pallet::::do_register_metadata(*currency_id, &metadata).expect("Token register"); + } + + for (currency, para_id, first_slot, last_slot) in self.vsbond.iter() { + match currency { + Token(symbol) | Native(symbol) => { + AssetIdMaps::::register_vsbond_metadata( + *symbol, + *para_id, + *first_slot, + *last_slot, + ) + .expect("VSBond register"); + }, + Token2(token_id) => { + AssetIdMaps::::register_vsbond2_metadata( + *token_id, + *para_id, + *first_slot, + *last_slot, + ) + .expect("VToken register"); + }, + _ => (), + } + } + + for ¤cy in self.vcurrency.iter() { + match currency { + CurrencyId::VToken(symbol) => { + AssetIdMaps::::register_vtoken_metadata(symbol) + .expect("VToken register"); + }, + CurrencyId::VToken2(token_id) => { + AssetIdMaps::::register_vtoken2_metadata(token_id) + .expect("VToken register"); + }, + CurrencyId::VSToken(symbol) => { + AssetIdMaps::::register_vstoken_metadata(symbol) + .expect("VSToken register"); + }, + CurrencyId::VSToken2(token_id) => { + AssetIdMaps::::register_vstoken2_metadata(token_id) + .expect("VSToken register"); + }, + _ => (), + } + } + } + } + + #[pallet::pallet] + #[pallet::without_storage_info] + pub struct Pallet(_); + + #[pallet::call] + impl Pallet { + #[pallet::call_index(0)] + #[pallet::weight(T::WeightInfo::register_native_asset())] + pub fn register_native_asset( + origin: OriginFor, + currency_id: CurrencyId, + location: Box, + metadata: Box>>, + ) -> DispatchResult { + T::RegisterOrigin::ensure_origin(origin)?; + + let location: Location = + (*location).try_into().map_err(|()| Error::::BadLocation)?; + Self::do_register_native_asset(currency_id, &location, &metadata)?; + + Self::deposit_event(Event::::AssetRegistered { + asset_id: AssetIds::NativeAssetId(currency_id), + metadata: *metadata, + }); + Ok(()) + } + + #[pallet::call_index(1)] + #[pallet::weight(T::WeightInfo::update_native_asset())] + pub fn update_native_asset( + origin: OriginFor, + currency_id: CurrencyId, + location: Box, + metadata: Box>>, + ) -> DispatchResult { + T::RegisterOrigin::ensure_origin(origin)?; + + let location: Location = + (*location).try_into().map_err(|()| Error::::BadLocation)?; + Self::do_update_native_asset(currency_id, &location, &metadata)?; + + Self::deposit_event(Event::::AssetUpdated { + asset_id: AssetIds::NativeAssetId(currency_id), + metadata: *metadata, + }); + Ok(()) + } + + #[pallet::call_index(2)] + #[pallet::weight(T::WeightInfo::register_token_metadata())] + pub fn register_token_metadata( + origin: OriginFor, + metadata: Box>>, + ) -> DispatchResult { + T::RegisterOrigin::ensure_origin(origin)?; + + let token_id = Self::get_next_token_id()?; + let currency_id = Token2(token_id); + Self::do_register_metadata(currency_id, &metadata)?; + + Ok(()) + } + + #[pallet::call_index(3)] + #[pallet::weight(T::WeightInfo::register_vtoken_metadata())] + pub fn register_vtoken_metadata(origin: OriginFor, token_id: TokenId) -> DispatchResult { + T::RegisterOrigin::ensure_origin(origin)?; + + if let Some(token_metadata) = CurrencyMetadatas::::get(Token2(token_id)) { + let vtoken_metadata = Self::convert_to_vtoken_metadata(token_metadata); + Self::do_register_metadata(CurrencyId::VToken2(token_id), &vtoken_metadata)?; + + return Ok(()); + } else { + return Err(Error::::CurrencyIdNotExists)?; + } + } + + #[pallet::call_index(4)] + #[pallet::weight(T::WeightInfo::register_vstoken_metadata())] + pub fn register_vstoken_metadata( + origin: OriginFor, + token_id: TokenId, + ) -> DispatchResult { + T::RegisterOrigin::ensure_origin(origin)?; + + if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token2(token_id)) + { + let vstoken_metadata = Self::convert_to_vstoken_metadata(token_metadata); + Self::do_register_metadata(CurrencyId::VSToken2(token_id), &vstoken_metadata)?; + + return Ok(()); + } else { + return Err(Error::::CurrencyIdNotExists)?; + } + } + + #[pallet::call_index(5)] + #[pallet::weight(T::WeightInfo::register_vsbond_metadata())] + pub fn register_vsbond_metadata( + origin: OriginFor, + token_id: TokenId, + para_id: ParaId, + first_slot: LeasePeriod, + last_slot: LeasePeriod, + ) -> DispatchResult { + T::RegisterOrigin::ensure_origin(origin)?; + + if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token2(token_id)) + { + let vsbond_metadata = Self::convert_to_vsbond_metadata( + token_metadata, + para_id, + first_slot, + last_slot, + ); + Self::do_register_metadata( + CurrencyId::VSBond2(token_id, para_id, first_slot, last_slot), + &vsbond_metadata, + )?; + + return Ok(()); + } else { + return Err(Error::::CurrencyIdNotExists)?; + } + } + + #[pallet::call_index(6)] + #[pallet::weight(T::WeightInfo::register_location())] + pub fn register_location( + origin: OriginFor, + currency_id: CurrencyId, + location: Box, + weight: Weight, + ) -> DispatchResult { + T::RegisterOrigin::ensure_origin(origin)?; + + let location: Location = + (*location).try_into().map_err(|()| Error::::BadLocation)?; + Self::do_register_location(currency_id, &location)?; + Self::do_register_weight(currency_id, weight)?; + + Ok(()) + } + + #[pallet::call_index(7)] + #[pallet::weight(T::WeightInfo::force_set_location())] + pub fn force_set_location( + origin: OriginFor, + currency_id: CurrencyId, + location: Box, + weight: Weight, + ) -> DispatchResult { + T::RegisterOrigin::ensure_origin(origin)?; + + let location: Location = + (*location).try_into().map_err(|()| Error::::BadLocation)?; + + let v3_location = xcm::v3::Location::try_from(location.clone()) + .map_err(|()| Error::::BadLocation)?; + + ensure!( + CurrencyMetadatas::::get(currency_id).is_some(), + Error::::CurrencyIdNotExists + ); + + LocationToCurrencyIds::::insert(v3_location, currency_id); + CurrencyIdToLocations::::insert(currency_id, v3_location); + CurrencyIdToWeights::::insert(currency_id, weight); + + Pallet::::deposit_event(Event::::LocationSet { currency_id, location, weight }); + + Ok(()) + } + + #[pallet::call_index(8)] + #[pallet::weight(T::WeightInfo::update_currency_metadata())] + pub fn update_currency_metadata( + origin: OriginFor, + currency_id: CurrencyId, + asset_name: Option>, + asset_symbol: Option>, + asset_decimals: Option, + asset_minimal_balance: Option>, + ) -> DispatchResult { + T::RegisterOrigin::ensure_origin(origin)?; + + // Check if the currency metadata exists + let mut metadata = + CurrencyMetadatas::::get(currency_id).ok_or(Error::::CurrencyIdNotExists)?; + + // Update the metadata fields based on the provided options + if let Some(name) = asset_name { + metadata.name = name; + } + if let Some(symbol) = asset_symbol { + metadata.symbol = symbol; + } + if let Some(decimals) = asset_decimals { + metadata.decimals = decimals; + } + if let Some(minimal_balance) = asset_minimal_balance { + metadata.minimal_balance = minimal_balance; + } + + // Store the updated metadata + CurrencyMetadatas::::insert(currency_id, metadata.clone()); + Self::deposit_event(Event::::CurrencyIdUpdated { currency_id, metadata }); + + Ok(()) + } + } +} + +impl Pallet { + pub fn get_next_token_id() -> Result { + NextTokenId::::try_mutate(|current| -> Result { + let id = *current; + *current = current.checked_add(One::one()).ok_or(ArithmeticError::Overflow)?; + Ok(id) + }) + } + + pub fn do_register_native_asset( + currency_id: CurrencyId, + location: &Location, + metadata: &AssetMetadata>, + ) -> DispatchResult { + let v3_location = + xcm::v3::Location::try_from(location.clone()).map_err(|()| Error::::BadLocation)?; + + ensure!(LocationToCurrencyIds::::get(v3_location).is_none(), Error::::AssetIdExisted); + ensure!( + CurrencyIdToLocations::::get(currency_id).is_none(), + Error::::LocationExisted + ); + ensure!( + AssetMetadatas::::get(AssetIds::NativeAssetId(currency_id)).is_none(), + Error::::AssetIdExisted + ); + + LocationToCurrencyIds::::insert(v3_location, currency_id); + CurrencyIdToLocations::::insert(currency_id, v3_location); + AssetMetadatas::::insert(AssetIds::NativeAssetId(currency_id), metadata); + + Ok(()) + } + + pub fn convert_to_vtoken_metadata( + token_metadata: AssetMetadata>, + ) -> AssetMetadata> { + let mut name = "Voucher ".as_bytes().to_vec(); + name.extend_from_slice(&token_metadata.symbol); + let mut symbol = "v".as_bytes().to_vec(); + symbol.extend_from_slice(&token_metadata.symbol); + AssetMetadata { name, symbol, ..token_metadata } + } + + pub fn convert_to_vstoken_metadata( + token_metadata: AssetMetadata>, + ) -> AssetMetadata> { + let mut name = "Voucher Slot ".as_bytes().to_vec(); + name.extend_from_slice(&token_metadata.symbol); + let mut symbol = "vs".as_bytes().to_vec(); + symbol.extend_from_slice(&token_metadata.symbol); + AssetMetadata { name, symbol, ..token_metadata } + } + + pub fn convert_to_vsbond_metadata( + token_metadata: AssetMetadata>, + para_id: ParaId, + first_slot: LeasePeriod, + last_slot: LeasePeriod, + ) -> AssetMetadata> { + let name = scale_info::prelude::format!( + "vsBOND-{}-{}-{}-{}", + core::str::from_utf8(&token_metadata.symbol).unwrap_or(""), + para_id, + first_slot, + last_slot + ) + .as_bytes() + .to_vec(); + AssetMetadata { name: name.clone(), symbol: name, ..token_metadata } + } + + pub fn do_register_metadata( + currency_id: CurrencyId, + metadata: &AssetMetadata>, + ) -> DispatchResult { + ensure!(CurrencyMetadatas::::get(currency_id).is_none(), Error::::CurrencyIdExisted); + + CurrencyMetadatas::::insert(currency_id, metadata.clone()); + + Pallet::::deposit_event(Event::::CurrencyIdRegistered { + currency_id, + metadata: metadata.clone(), + }); + + Ok(()) + } + + pub fn do_register_location(currency_id: CurrencyId, location: &Location) -> DispatchResult { + let v3_location = + xcm::v3::Location::try_from(location.clone()).map_err(|()| Error::::BadLocation)?; + + ensure!( + CurrencyMetadatas::::get(currency_id).is_some(), + Error::::CurrencyIdNotExists + ); + ensure!( + LocationToCurrencyIds::::get(v3_location).is_none(), + Error::::CurrencyIdExisted + ); + ensure!( + CurrencyIdToLocations::::get(currency_id).is_none(), + Error::::LocationExisted + ); + + LocationToCurrencyIds::::insert(v3_location, currency_id); + CurrencyIdToLocations::::insert(currency_id, v3_location); + + Ok(()) + } + + pub fn do_register_weight(currency_id: CurrencyId, weight: Weight) -> DispatchResult { + ensure!( + CurrencyMetadatas::::get(currency_id).is_some(), + Error::::CurrencyIdNotExists + ); + + CurrencyIdToWeights::::insert(currency_id, weight); + + Ok(()) + } + + fn do_update_native_asset( + currency_id: CurrencyId, + location: &Location, + metadata: &AssetMetadata>, + ) -> DispatchResult { + let v3_location = + xcm::v3::Location::try_from(location.clone()).map_err(|()| Error::::BadLocation)?; + + ensure!( + LocationToCurrencyIds::::get(v3_location).is_some(), + Error::::AssetIdNotExists + ); + ensure!( + CurrencyIdToLocations::::get(currency_id).is_some(), + Error::::LocationExisted + ); + ensure!( + AssetMetadatas::::get(AssetIds::NativeAssetId(currency_id)).is_some(), + Error::::AssetIdNotExists + ); + + LocationToCurrencyIds::::insert(v3_location, currency_id); + CurrencyIdToLocations::::insert(currency_id, v3_location); + AssetMetadatas::::insert(AssetIds::NativeAssetId(currency_id), metadata); + + Ok(()) + } +} + +pub struct AssetIdMaps(sp_std::marker::PhantomData); + +impl CurrencyIdMapping>> + for AssetIdMaps +{ + fn get_asset_metadata(asset_ids: AssetIds) -> Option>> { + AssetMetadatas::::get(asset_ids) + } + + fn get_currency_metadata(currency_id: CurrencyId) -> Option>> { + CurrencyMetadatas::::get(currency_id) + } + + fn get_all_currency() -> Vec { + CurrencyMetadatas::::iter_keys().collect() + } + + fn get_location(currency_id: CurrencyId) -> Option { + CurrencyIdToLocations::::get(currency_id).map(|location| location.try_into().ok())? + } + + fn get_currency_id(multi_location: Location) -> Option { + let v3_location = xcm::v3::Location::try_from(multi_location).ok()?; + LocationToCurrencyIds::::get(v3_location) + } +} + +impl CurrencyIdConversion for AssetIdMaps { + fn convert_to_token(currency_id: CurrencyId) -> Result { + match currency_id { + CurrencyId::VSBond(TokenSymbol::BNC, 2001, 13, 20) => + Ok(CurrencyId::Token(TokenSymbol::KSM)), + CurrencyId::VToken(TokenSymbol::BNC) => Ok(CurrencyId::Native(TokenSymbol::BNC)), + CurrencyId::VToken(token_symbol) | + CurrencyId::VSToken(token_symbol) | + CurrencyId::VSBond(token_symbol, ..) => Ok(CurrencyId::Token(token_symbol)), + CurrencyId::VToken2(token_id) | + CurrencyId::VSToken2(token_id) | + CurrencyId::VSBond2(token_id, ..) => Ok(CurrencyId::Token2(token_id)), + _ => Err(()), + } + } + + fn convert_to_vtoken(currency_id: CurrencyId) -> Result { + match currency_id { + CurrencyId::Token(token_symbol) | CurrencyId::Native(token_symbol) => + Ok(CurrencyId::VToken(token_symbol)), + CurrencyId::Token2(token_id) => Ok(CurrencyId::VToken2(token_id)), + _ => Err(()), + } + } + + fn convert_to_vstoken(currency_id: CurrencyId) -> Result { + match currency_id { + CurrencyId::Token(token_symbol) => Ok(CurrencyId::VSToken(token_symbol)), + CurrencyId::Token2(token_id) => Ok(CurrencyId::VSToken2(token_id)), + _ => Err(()), + } + } + + fn convert_to_vsbond( + currency_id: CurrencyId, + index: ParaId, + first_slot: LeasePeriod, + last_slot: LeasePeriod, + ) -> Result { + match currency_id { + CurrencyId::Token(token_symbol) => { + let mut vs_bond = CurrencyId::VSBond(token_symbol, index, first_slot, last_slot); + if vs_bond == CurrencyId::VSBond(TokenSymbol::KSM, 2001, 13, 20) { + // fix vsBOND::BNC + vs_bond = CurrencyId::VSBond(TokenSymbol::BNC, 2001, 13, 20); + } + Ok(vs_bond) + }, + CurrencyId::Token2(token_id) => + Ok(CurrencyId::VSBond2(token_id, index, first_slot, last_slot)), + _ => Err(()), + } + } +} + +impl CurrencyIdRegister for AssetIdMaps { + fn check_token_registered(token_symbol: TokenSymbol) -> bool { + CurrencyMetadatas::::get(CurrencyId::Token(token_symbol)).is_some() + } + + fn check_vtoken_registered(token_symbol: TokenSymbol) -> bool { + CurrencyMetadatas::::get(CurrencyId::VToken(token_symbol)).is_some() + } + + fn check_vstoken_registered(token_symbol: TokenSymbol) -> bool { + CurrencyMetadatas::::get(CurrencyId::VSToken(token_symbol)).is_some() + } + + fn check_vsbond_registered( + token_symbol: TokenSymbol, + para_id: ParaId, + first_slot: LeasePeriod, + last_slot: LeasePeriod, + ) -> bool { + CurrencyMetadatas::::get(CurrencyId::VSBond( + token_symbol, + para_id, + first_slot, + last_slot, + )) + .is_some() + } + + fn register_vtoken_metadata(token_symbol: TokenSymbol) -> sp_runtime::DispatchResult { + if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token(token_symbol)) { + let vtoken_metadata = Pallet::::convert_to_vtoken_metadata(token_metadata); + Pallet::::do_register_metadata(CurrencyId::VToken(token_symbol), &vtoken_metadata)?; + return Ok(()); + } else if let Some(token_metadata) = + CurrencyMetadatas::::get(CurrencyId::Native(token_symbol)) + { + let vtoken_metadata = Pallet::::convert_to_vtoken_metadata(token_metadata); + Pallet::::do_register_metadata(CurrencyId::VToken(token_symbol), &vtoken_metadata)?; + return Ok(()); + } else { + return Err(Error::::CurrencyIdNotExists.into()); + } + } + + fn register_vstoken_metadata(token_symbol: TokenSymbol) -> sp_runtime::DispatchResult { + if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token(token_symbol)) { + let vstoken_metadata = Pallet::::convert_to_vstoken_metadata(token_metadata); + Pallet::::do_register_metadata( + CurrencyId::VSToken(token_symbol), + &vstoken_metadata, + )?; + + return Ok(()); + } else { + return Err(Error::::CurrencyIdNotExists.into()); + } + } + + fn register_vsbond_metadata( + token_symbol: TokenSymbol, + para_id: ParaId, + first_slot: LeasePeriod, + last_slot: LeasePeriod, + ) -> sp_runtime::DispatchResult { + let option_token_metadata = + if CurrencyMetadatas::::contains_key(CurrencyId::Token(token_symbol)) { + CurrencyMetadatas::::get(CurrencyId::Token(token_symbol)) + } else if token_symbol == TokenSymbol::BNC && + CurrencyMetadatas::::contains_key(CurrencyId::Native(token_symbol)) + { + CurrencyMetadatas::::get(CurrencyId::Native(token_symbol)) + } else { + None + }; + + if let Some(token_metadata) = option_token_metadata { + let vsbond_metadata = Pallet::::convert_to_vsbond_metadata( + token_metadata, + para_id, + first_slot, + last_slot, + ); + Pallet::::do_register_metadata( + CurrencyId::VSBond(token_symbol, para_id, first_slot, last_slot), + &vsbond_metadata, + )?; + + return Ok(()); + } else { + return Err(Error::::CurrencyIdNotExists.into()); + } + } + + fn check_token2_registered(token_id: TokenId) -> bool { + CurrencyMetadatas::::get(CurrencyId::Token2(token_id)).is_some() + } + + fn check_vtoken2_registered(token_id: TokenId) -> bool { + CurrencyMetadatas::::get(CurrencyId::VToken2(token_id)).is_some() + } + + fn check_vstoken2_registered(token_id: TokenId) -> bool { + CurrencyMetadatas::::get(CurrencyId::VSToken2(token_id)).is_some() + } + + fn check_vsbond2_registered( + token_id: TokenId, + para_id: ParaId, + first_slot: LeasePeriod, + last_slot: LeasePeriod, + ) -> bool { + CurrencyMetadatas::::get(CurrencyId::VSBond2(token_id, para_id, first_slot, last_slot)) + .is_some() + } + + fn register_vtoken2_metadata(token_id: TokenId) -> DispatchResult { + if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token2(token_id)) { + let vtoken_metadata = Pallet::::convert_to_vtoken_metadata(token_metadata); + Pallet::::do_register_metadata(CurrencyId::VToken2(token_id), &vtoken_metadata)?; + + return Ok(()); + } else { + return Err(Error::::CurrencyIdNotExists.into()); + } + } + + fn register_vstoken2_metadata(token_id: TokenId) -> DispatchResult { + if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token2(token_id)) { + let vstoken_metadata = Pallet::::convert_to_vstoken_metadata(token_metadata); + Pallet::::do_register_metadata(CurrencyId::VSToken2(token_id), &vstoken_metadata)?; + + return Ok(()); + } else { + return Err(Error::::CurrencyIdNotExists.into()); + } + } + + fn register_vsbond2_metadata( + token_id: TokenId, + para_id: ParaId, + first_slot: LeasePeriod, + last_slot: LeasePeriod, + ) -> DispatchResult { + if let Some(token_metadata) = CurrencyMetadatas::::get(CurrencyId::Token2(token_id)) { + let vsbond_metadata = Pallet::::convert_to_vsbond_metadata( + token_metadata, + para_id, + first_slot, + last_slot, + ); + Pallet::::do_register_metadata( + CurrencyId::VSBond2(token_id, para_id, first_slot, last_slot), + &vsbond_metadata, + )?; + + return Ok(()); + } else { + return Err(Error::::CurrencyIdNotExists.into()); + } + } + + fn register_blp_metadata(pool_id: PoolId, decimals: u8) -> DispatchResult { + let name = scale_info::prelude::format!("Bifrost Stable Pool Token {}", pool_id) + .as_bytes() + .to_vec(); + let symbol = scale_info::prelude::format!("BLP{}", pool_id).as_bytes().to_vec(); + Pallet::::do_register_metadata( + CurrencyId::BLP(pool_id), + &AssetMetadata { + name, + symbol, + decimals, + minimal_balance: BalanceOf::::unique_saturated_from(1_000_000u128), + }, + ) + } +} + +/// Simple fee calculator that requires payment in a single fungible at a fixed rate. +/// +/// The constant `FixedRate` type parameter should be the concrete fungible ID and the amount of it +/// required for one second of weight. +pub struct FixedRateOfAsset, R: TakeRevenue> { + weight: u64, + amount: u128, + ed_ratio: FixedU128, + location: Option, + _marker: PhantomData<(T, FixedRate, R)>, +} + +impl, R: TakeRevenue> WeightTrader + for FixedRateOfAsset +where + BalanceOf: Into, +{ + fn new() -> Self { + Self { + weight: 0, + amount: 0, + ed_ratio: Default::default(), + location: None, + _marker: PhantomData, + } + } + + fn buy_weight( + &mut self, + weight: Weight, + payment: AssetsInHolding, + _context: &XcmContext, + ) -> Result { + log::trace!(target: "asset-registry::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment); + + // only support first fungible assets now. + let asset_id = payment + .fungible + .iter() + .next() + .map_or(Err(XcmError::TooExpensive), |v| Ok(v.0))?; + + let AssetId(ref location) = asset_id.clone(); + log::debug!(target: "asset-registry::weight", "buy_weight location: {:?}", location); + + let v3_location = + xcm::v3::Location::try_from(location.clone()).map_err(|_| XcmError::InvalidLocation)?; + + if let Some(currency_id) = LocationToCurrencyIds::::get(v3_location) { + if let Some(currency_metadatas) = CurrencyMetadatas::::get(currency_id) { + // The integration tests can ensure the ed is non-zero. + let ed_ratio = FixedU128::saturating_from_rational( + currency_metadatas.minimal_balance.into(), + T::Currency::minimum_balance().into(), + ); + // The WEIGHT_REF_TIME_PER_SECOND is non-zero. + let weight_ratio = FixedU128::saturating_from_rational( + weight.ref_time(), + WEIGHT_REF_TIME_PER_SECOND, + ); + let amount = + ed_ratio.saturating_mul_int(weight_ratio.saturating_mul_int(FixedRate::get())); + + let required = Asset { id: asset_id.clone(), fun: Fungible(amount) }; + + log::trace!( + target: "asset-registry::weight", "buy_weight payment: {:?}, required: {:?}, fixed_rate: {:?}, ed_ratio: {:?}, weight_ratio: {:?}", + payment, required, FixedRate::get(), ed_ratio, weight_ratio + ); + let unused = + payment.clone().checked_sub(required).map_err(|_| XcmError::TooExpensive)?; + self.weight = self.weight.saturating_add(weight.ref_time()); + self.amount = self.amount.saturating_add(amount); + self.ed_ratio = ed_ratio; + self.location = Some(location.clone()); + return Ok(unused); + } + }; + + log::trace!(target: "asset-registry::weight", "no concrete fungible asset"); + Err(XcmError::TooExpensive) + } + + fn refund_weight(&mut self, weight: Weight, _context: &XcmContext) -> Option { + log::trace!( + target: "asset-registry::weight", "refund_weight weight: {:?}, weight: {:?}, amount: {:?}, ed_ratio: {:?}, location: {:?}", + weight, self.weight, self.amount, self.ed_ratio, self.location + ); + let weight = weight.min(Weight::from_parts(self.weight, 0)); + let weight_ratio = + FixedU128::saturating_from_rational(weight.ref_time(), WEIGHT_REF_TIME_PER_SECOND); + let amount = self + .ed_ratio + .saturating_mul_int(weight_ratio.saturating_mul_int(FixedRate::get())); + + self.weight = self.weight.saturating_sub(weight.ref_time()); + self.amount = self.amount.saturating_sub(amount); + + log::trace!(target: "asset-registry::weight", "refund_weight amount: {:?}", amount); + if amount > 0 && self.location.is_some() { + Some(Asset { + fun: Fungible(amount), + id: AssetId( + self.location.clone().expect("checked is non-empty; qed").try_into().unwrap(), + ), + }) + } else { + None + } + } +} + +impl, R: TakeRevenue> Drop for FixedRateOfAsset { + fn drop(&mut self) { + log::trace!(target: "asset-registry::weight", "take revenue, weight: {:?}, amount: {:?}, location: {:?}", self.weight, self.amount, self.location); + if self.amount > 0 && self.location.is_some() { + R::take_revenue(Asset { + fun: Fungible(self.amount), + id: AssetId( + self.location.clone().expect("checked is non-empty; qed").try_into().unwrap(), + ), + }); + } + } +} diff --git a/pallets/asset-registry/src/migration.rs b/pallets/deprecated/asset-registry/src/migration.rs similarity index 100% rename from pallets/asset-registry/src/migration.rs rename to pallets/deprecated/asset-registry/src/migration.rs diff --git a/pallets/deprecated/asset-registry/src/mock.rs b/pallets/deprecated/asset-registry/src/mock.rs new file mode 100644 index 000000000..a948e290c --- /dev/null +++ b/pallets/deprecated/asset-registry/src/mock.rs @@ -0,0 +1,109 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Mocks for asset registry module. + +#![cfg(test)] + +use bifrost_primitives::{AccountId, Balance}; +use frame_support::{ + construct_runtime, derive_impl, ord_parameter_types, pallet_prelude::ConstU32, parameter_types, +}; +use frame_system::EnsureSignedBy; +use sp_runtime::BuildStorage; + +use crate as asset_registry; + +parameter_types!( + pub const BlockHashCount: u32 = 250; +); + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { + type AccountId = AccountId; + type AccountData = pallet_balances::AccountData; + type Block = Block; + type Lookup = sp_runtime::traits::IdentityLookup; +} + +parameter_types! { + pub const ExistentialDeposit: u64 = 1; + pub const MaxReserves: u32 = 50; +} + +impl pallet_balances::Config for Runtime { + type Balance = Balance; + type DustRemoval = (); + type RuntimeEvent = RuntimeEvent; + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type MaxLocks = (); + type MaxReserves = MaxReserves; + type ReserveIdentifier = [u8; 8]; + type WeightInfo = (); + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; + type FreezeIdentifier = (); + type MaxFreezes = ConstU32<0>; +} + +ord_parameter_types! { + pub const CouncilAccount: AccountId = AccountId::from([1u8; 32]); +} +impl asset_registry::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type RegisterOrigin = EnsureSignedBy; + type WeightInfo = (); +} + +type Block = frame_system::mocking::MockBlock; + +construct_runtime!( + pub enum Runtime { + System: frame_system, + Balances: pallet_balances, + AssetRegistry: asset_registry, + } +); + +pub struct ExtBuilder { + balances: Vec<(AccountId, Balance)>, +} + +impl Default for ExtBuilder { + fn default() -> Self { + Self { balances: vec![] } + } +} + +impl ExtBuilder { + pub fn build(self) -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + + pallet_balances::GenesisConfig:: { + balances: self.balances.into_iter().collect::>(), + } + .assimilate_storage(&mut t) + .unwrap(); + + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext + } +} diff --git a/pallets/deprecated/asset-registry/src/tests.rs b/pallets/deprecated/asset-registry/src/tests.rs new file mode 100644 index 000000000..470a22438 --- /dev/null +++ b/pallets/deprecated/asset-registry/src/tests.rs @@ -0,0 +1,519 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Unit tests for asset registry module. + +#![cfg(test)] + +use super::*; +use bifrost_primitives::TokenSymbol; +use frame_support::{assert_noop, assert_ok}; +use mock::{ + AssetRegistry, CouncilAccount, ExtBuilder, Runtime, RuntimeEvent, RuntimeOrigin, System, +}; + +#[test] +fn versioned_multi_location_convert_work() { + ExtBuilder::default().build().execute_with(|| { + let versioned_location = VersionedLocation::V4(Location::from([Parachain(1000)])); + let location: Location = versioned_location.try_into().unwrap(); + assert_eq!(location, Location::new(0, [Parachain(1000)])); + }); +} + +#[test] +fn register_native_asset_works() { + ExtBuilder::default().build().execute_with(|| { + let versioned_location = VersionedLocation::V4(Location::from([Parachain(1000)])); + + assert_ok!(AssetRegistry::register_native_asset( + RuntimeOrigin::signed(CouncilAccount::get()), + Token(TokenSymbol::DOT), + Box::new(versioned_location.clone()), + Box::new(AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 12, + minimal_balance: 1, + }) + )); + System::assert_last_event(RuntimeEvent::AssetRegistry(Event::AssetRegistered { + asset_id: AssetIds::NativeAssetId(Token(TokenSymbol::DOT)), + metadata: AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 12, + minimal_balance: 1, + }, + })); + + assert_eq!( + AssetMetadatas::::get(AssetIds::NativeAssetId(Token(TokenSymbol::DOT))), + Some(AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 12, + minimal_balance: 1, + }) + ); + // Can't duplicate + assert_noop!( + AssetRegistry::register_native_asset( + RuntimeOrigin::signed(CouncilAccount::get()), + Token(TokenSymbol::DOT), + Box::new(versioned_location), + Box::new(AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 12, + minimal_balance: 1, + }) + ), + Error::::AssetIdExisted + ); + }); +} + +#[test] +fn update_native_asset_works() { + let versioned_location = VersionedLocation::V4(Location::from([Parachain(1000)])); + + ExtBuilder::default().build().execute_with(|| { + assert_noop!( + AssetRegistry::update_native_asset( + RuntimeOrigin::signed(CouncilAccount::get()), + Token(TokenSymbol::DOT), + Box::new(versioned_location.clone()), + Box::new(AssetMetadata { + name: b"New Token Name".to_vec(), + symbol: b"NTN".to_vec(), + decimals: 13, + minimal_balance: 2, + }) + ), + Error::::AssetIdNotExists + ); + + assert_ok!(AssetRegistry::register_native_asset( + RuntimeOrigin::signed(CouncilAccount::get()), + Token(TokenSymbol::DOT), + Box::new(versioned_location.clone()), + Box::new(AssetMetadata { + name: b"Token Name".to_vec(), + symbol: b"TN".to_vec(), + decimals: 12, + minimal_balance: 1, + }) + )); + + assert_ok!(AssetRegistry::update_native_asset( + RuntimeOrigin::signed(CouncilAccount::get()), + Token(TokenSymbol::DOT), + Box::new(versioned_location.clone()), + Box::new(AssetMetadata { + name: b"New Token Name".to_vec(), + symbol: b"NTN".to_vec(), + decimals: 13, + minimal_balance: 2, + }) + )); + + System::assert_last_event(RuntimeEvent::AssetRegistry(Event::AssetUpdated { + asset_id: AssetIds::NativeAssetId(Token(TokenSymbol::DOT)), + metadata: AssetMetadata { + name: b"New Token Name".to_vec(), + symbol: b"NTN".to_vec(), + decimals: 13, + minimal_balance: 2, + }, + })); + + assert_eq!( + AssetMetadatas::::get(AssetIds::NativeAssetId(Token(TokenSymbol::DOT))), + Some(AssetMetadata { + name: b"New Token Name".to_vec(), + symbol: b"NTN".to_vec(), + decimals: 13, + minimal_balance: 2, + }) + ); + }); +} + +#[test] +fn register_token_metadata_should_work() { + ExtBuilder::default().build().execute_with(|| { + let metadata = AssetMetadata { + name: b"Bifrost Native Coin".to_vec(), + symbol: b"BNC".to_vec(), + decimals: 12, + minimal_balance: 0, + }; + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + assert_eq!(CurrencyMetadatas::::get(Token2(0)), Some(metadata.clone())) + }) +} + +#[test] +fn register_vtoken_metadata_should_work() { + ExtBuilder::default().build().execute_with(|| { + let metadata = AssetMetadata { + name: b"Bifrost Native Coin".to_vec(), + symbol: b"BNC".to_vec(), + decimals: 12, + minimal_balance: 0, + }; + let v_metadata = AssetMetadata { + name: b"Voucher BNC".to_vec(), + symbol: b"vBNC".to_vec(), + decimals: 12, + minimal_balance: 0, + }; + assert_noop!( + AssetRegistry::register_vtoken_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + 1 + ), + Error::::CurrencyIdNotExists + ); + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + assert_ok!(AssetRegistry::register_vtoken_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + 0 + )); + + assert_eq!( + CurrencyMetadatas::::get(CurrencyId::VToken2(0)), + Some(v_metadata.clone()) + ) + }) +} + +#[test] +fn register_vstoken_metadata_should_work() { + ExtBuilder::default().build().execute_with(|| { + let metadata = AssetMetadata { + name: b"KSM Native Token".to_vec(), + symbol: b"KSM".to_vec(), + decimals: 12, + minimal_balance: 0, + }; + let v_metadata = AssetMetadata { + name: b"Voucher Slot KSM".to_vec(), + symbol: b"vsKSM".to_vec(), + decimals: 12, + minimal_balance: 0, + }; + assert_noop!( + AssetRegistry::register_vtoken_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + 1 + ), + Error::::CurrencyIdNotExists + ); + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + assert_ok!(AssetRegistry::register_vstoken_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + 0 + )); + + assert_eq!( + CurrencyMetadatas::::get(CurrencyId::VSToken2(0)), + Some(v_metadata.clone()) + ) + }) +} + +#[test] +fn register_vsbond_metadata_should_work() { + ExtBuilder::default().build().execute_with(|| { + let metadata = AssetMetadata { + name: b"KSM Native Token".to_vec(), + symbol: b"KSM".to_vec(), + decimals: 12, + minimal_balance: 0, + }; + let name = "vsBOND-KSM-2001-10-20".as_bytes().to_vec(); + let v_metadata = + AssetMetadata { name: name.clone(), symbol: name, decimals: 12, minimal_balance: 0 }; + assert_noop!( + AssetRegistry::register_vtoken_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + 1 + ), + Error::::CurrencyIdNotExists + ); + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + assert_ok!(AssetRegistry::register_vsbond_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + 0, + 2001, + 10, + 20 + )); + + assert_eq!( + CurrencyMetadatas::::get(CurrencyId::VSBond2(0, 2001, 10, 20)), + Some(v_metadata.clone()) + ) + }) +} + +#[test] +fn register_multilocation_should_work() { + ExtBuilder::default().build().execute_with(|| { + let metadata = AssetMetadata { + name: b"Bifrost Native Coin".to_vec(), + symbol: b"BNC".to_vec(), + decimals: 12, + minimal_balance: 0, + }; + + let versioned_location = VersionedLocation::V4(Location::new(1, [Parachain(2001)])); + let location: xcm::v3::Location = versioned_location.clone().try_into().unwrap(); + + assert_noop!( + AssetRegistry::register_location( + RuntimeOrigin::signed(CouncilAccount::get()), + Token2(0), + Box::new(versioned_location.clone()), + Weight::from_parts(2000_000_000, 0) + ), + Error::::CurrencyIdNotExists + ); + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + assert_ok!(AssetRegistry::register_location( + RuntimeOrigin::signed(CouncilAccount::get()), + Token2(0), + Box::new(versioned_location.clone()), + Weight::from_parts(2000_000_000, 0) + )); + + assert_noop!( + AssetRegistry::register_location( + RuntimeOrigin::signed(CouncilAccount::get()), + Token2(0), + Box::new(versioned_location.clone()), + Weight::from_parts(2000_000_000, 0) + ), + Error::::CurrencyIdExisted + ); + + assert_eq!(LocationToCurrencyIds::::get(location), Some(Token2(0))); + assert_eq!(CurrencyIdToLocations::::get(Token2(0)), Some(location)); + assert_eq!( + CurrencyIdToWeights::::get(Token2(0)), + Some(Weight::from_parts(2000_000_000, 0)) + ); + }) +} + +#[test] +fn force_set_multilocation_should_work() { + ExtBuilder::default().build().execute_with(|| { + let metadata = AssetMetadata { + name: b"Bifrost Native Coin".to_vec(), + symbol: b"BNC".to_vec(), + decimals: 12, + minimal_balance: 0, + }; + let versioned_location = VersionedLocation::V4(Location::new(1, [Parachain(2001)])); + let location: xcm::v3::Location = versioned_location.clone().try_into().unwrap(); + + assert_noop!( + AssetRegistry::force_set_location( + RuntimeOrigin::signed(CouncilAccount::get()), + Token2(0), + Box::new(versioned_location.clone()), + Weight::from_parts(2000_000_000, 0) + ), + Error::::CurrencyIdNotExists + ); + + assert_ok!(AssetRegistry::register_token_metadata( + RuntimeOrigin::signed(CouncilAccount::get()), + Box::new(metadata.clone()) + )); + + assert_ok!(AssetRegistry::force_set_location( + RuntimeOrigin::signed(CouncilAccount::get()), + Token2(0), + Box::new(versioned_location.clone()), + Weight::from_parts(2000_000_000, 0) + )); + + assert_ok!(AssetRegistry::force_set_location( + RuntimeOrigin::signed(CouncilAccount::get()), + Token2(0), + Box::new(versioned_location.clone()), + Weight::from_parts(2000_000_000, 0) + )); + + assert_eq!(LocationToCurrencyIds::::get(location), Some(Token2(0))); + assert_eq!(CurrencyIdToLocations::::get(Token2(0)), Some(location)); + assert_eq!( + CurrencyIdToWeights::::get(Token2(0)), + Some(Weight::from_parts(2000_000_000, 0)) + ); + }) +} + +#[test] +fn update_currency_metadata_should_work() { + ExtBuilder::default().build().execute_with(|| { + let caller = CouncilAccount::get(); + let currency_id = CurrencyId::Token2(0); + let name = b"Updated Name".to_vec(); + let symbol = b"UN".to_vec(); + let decimals: u8 = 10; + let minimal_balance = 1000u32.into(); + + // Pre-insert a currency_metadata to update + CurrencyMetadatas::::insert( + currency_id, + AssetMetadata { + name: b"Old Name".to_vec(), + symbol: b"ON".to_vec(), + decimals: 8, + minimal_balance: 1u32.into(), + }, + ); + + // Ensure the origin has the required permissions + let origin = RuntimeOrigin::signed(caller); + assert_ok!(AssetRegistry::update_currency_metadata( + origin, + currency_id, + Some(name.clone()), + Some(symbol.clone()), + Some(decimals), + Some(minimal_balance) + )); + + System::assert_last_event(RuntimeEvent::AssetRegistry(crate::Event::CurrencyIdUpdated { + currency_id, + metadata: AssetMetadata { + name: name.clone(), + symbol: symbol.clone(), + decimals, + minimal_balance, + }, + })); + + // Verify the updated metadata + let updated_metadata = CurrencyMetadatas::::get(currency_id).unwrap(); + assert_eq!(updated_metadata.name, name); + assert_eq!(updated_metadata.symbol, symbol); + assert_eq!(updated_metadata.decimals, decimals); + assert_eq!(updated_metadata.minimal_balance, minimal_balance); + }) +} + +#[test] +fn update_currency_metadata_should_work_no_change() { + ExtBuilder::default().build().execute_with(|| { + let caller = CouncilAccount::get(); + let currency_id = CurrencyId::Token2(0); + let name = None; + let symbol = None; + let decimals = None; + let minimal_balance = None; + + let old_metadata = AssetMetadata { + name: b"Old Name".to_vec(), + symbol: b"ON".to_vec(), + decimals: 8, + minimal_balance: 1u32.into(), + }; + + // Pre-insert a currency_metadata to update + CurrencyMetadatas::::insert(currency_id, old_metadata.clone()); + + // Ensure the origin has the required permissions + let origin = RuntimeOrigin::signed(caller); + assert_ok!(AssetRegistry::update_currency_metadata( + origin, + currency_id, + name, + symbol, + decimals, + minimal_balance + )); + + // Verify the event + System::assert_last_event(RuntimeEvent::AssetRegistry(crate::Event::CurrencyIdUpdated { + currency_id, + metadata: old_metadata.clone(), + })); + + // Verify the updated metadata + let updated_metadata = CurrencyMetadatas::::get(currency_id).unwrap(); + assert_eq!(updated_metadata, old_metadata); + }); +} + +#[test] +fn update_currency_metadata_nonexistent_currency_id() { + ExtBuilder::default().build().execute_with(|| { + let caller = CouncilAccount::get(); + let currency_id = CurrencyId::Token2(1); // Non-existent currency ID + let name = Some(b"Updated Name".to_vec()); + let symbol = Some(b"UN".to_vec()); + let decimals = Some(10); + let minimal_balance = Some(1000u32.into()); + + // Ensure the origin has the required permissions + let origin = RuntimeOrigin::signed(caller); + assert_noop!( + AssetRegistry::update_currency_metadata( + origin, + currency_id, + name, + symbol, + decimals, + minimal_balance + ), + Error::::CurrencyIdNotExists + ); + }); +} diff --git a/pallets/deprecated/asset-registry/src/weights.rs b/pallets/deprecated/asset-registry/src/weights.rs new file mode 100644 index 000000000..162c6fad6 --- /dev/null +++ b/pallets/deprecated/asset-registry/src/weights.rs @@ -0,0 +1,190 @@ +// This file is part of Bifrost. + +// Copyright (C) Liebi Technologies PTE. LTD. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// 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. + +//! Autogenerated weights for bifrost_asset_registry +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-14, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! HOSTNAME: `bifrost-jenkins`, CPU: `Intel(R) Xeon(R) CPU E5-26xx v4` +//! WASM-EXECUTION: Compiled, CHAIN: Some("bifrost-kusama-local"), DB CACHE: 1024 + +// Executed Command: +// target/release/bifrost +// benchmark +// pallet +// --chain=bifrost-kusama-local +// --steps=50 +// --repeat=20 +// --pallet=bifrost_asset_registry +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./pallets/asset-registry/src/weights.rs +// --template=./weight-template/pallet-weight-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for bifrost_asset_registry. +pub trait WeightInfo { + fn register_native_asset() -> Weight; + fn update_native_asset() -> Weight; + fn register_token_metadata() -> Weight; + fn register_vtoken_metadata() -> Weight; + fn register_vstoken_metadata() -> Weight; + fn register_vsbond_metadata() -> Weight; + fn register_location() -> Weight; + fn force_set_location() -> Weight; + fn update_currency_metadata() -> Weight; +} + +// For backwards compatibility and tests +impl WeightInfo for () { + /// Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) + /// Proof Skipped: AssetRegistry LocationToCurrencyIds (max_values: None, max_size: None, mode: Measured) + /// Storage: AssetRegistry CurrencyIdToLocations (r:1 w:1) + /// Proof Skipped: AssetRegistry CurrencyIdToLocations (max_values: None, max_size: None, mode: Measured) + /// Storage: AssetRegistry AssetMetadatas (r:1 w:1) + /// Proof Skipped: AssetRegistry AssetMetadatas (max_values: None, max_size: None, mode: Measured) + fn register_native_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `118` + // Estimated: `3583` + // Minimum execution time: 52_056_000 picoseconds. + Weight::from_parts(53_012_000, 3583) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + } + /// Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) + /// Proof Skipped: AssetRegistry LocationToCurrencyIds (max_values: None, max_size: None, mode: Measured) + /// Storage: AssetRegistry CurrencyIdToLocations (r:1 w:1) + /// Proof Skipped: AssetRegistry CurrencyIdToLocations (max_values: None, max_size: None, mode: Measured) + /// Storage: AssetRegistry AssetMetadatas (r:1 w:1) + /// Proof Skipped: AssetRegistry AssetMetadatas (max_values: None, max_size: None, mode: Measured) + fn update_native_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `250` + // Estimated: `3715` + // Minimum execution time: 59_891_000 picoseconds. + Weight::from_parts(60_869_000, 3715) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + } + /// Storage: AssetRegistry NextTokenId (r:1 w:1) + /// Proof Skipped: AssetRegistry NextTokenId (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:1) + /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) + fn register_token_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `607` + // Estimated: `4072` + // Minimum execution time: 46_860_000 picoseconds. + Weight::from_parts(48_151_000, 4072) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + } + /// Storage: AssetRegistry CurrencyMetadatas (r:2 w:1) + /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) + fn register_vtoken_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `779` + // Estimated: `6719` + // Minimum execution time: 53_699_000 picoseconds. + Weight::from_parts(54_646_000, 6719) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: AssetRegistry CurrencyMetadatas (r:2 w:1) + /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) + fn register_vstoken_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `705` + // Estimated: `6645` + // Minimum execution time: 52_491_000 picoseconds. + Weight::from_parts(53_682_000, 6645) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: AssetRegistry CurrencyMetadatas (r:2 w:1) + /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) + fn register_vsbond_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `763` + // Estimated: `6703` + // Minimum execution time: 55_589_000 picoseconds. + Weight::from_parts(56_804_000, 6703) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) + /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) + /// Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) + /// Proof Skipped: AssetRegistry LocationToCurrencyIds (max_values: None, max_size: None, mode: Measured) + /// Storage: AssetRegistry CurrencyIdToLocations (r:1 w:1) + /// Proof Skipped: AssetRegistry CurrencyIdToLocations (max_values: None, max_size: None, mode: Measured) + /// Storage: AssetRegistry CurrencyIdToWeights (r:0 w:1) + /// Proof Skipped: AssetRegistry CurrencyIdToWeights (max_values: None, max_size: None, mode: Measured) + fn register_location() -> Weight { + // Proof Size summary in bytes: + // Measured: `683` + // Estimated: `4148` + // Minimum execution time: 45_469_000 picoseconds. + Weight::from_parts(48_623_000, 4148) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + } + /// Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) + /// Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) + /// Storage: AssetRegistry LocationToCurrencyIds (r:0 w:1) + /// Proof Skipped: AssetRegistry LocationToCurrencyIds (max_values: None, max_size: None, mode: Measured) + /// Storage: AssetRegistry CurrencyIdToWeights (r:0 w:1) + /// Proof Skipped: AssetRegistry CurrencyIdToWeights (max_values: None, max_size: None, mode: Measured) + /// Storage: AssetRegistry CurrencyIdToLocations (r:0 w:1) + /// Proof Skipped: AssetRegistry CurrencyIdToLocations (max_values: None, max_size: None, mode: Measured) + fn force_set_location() -> Weight { + // Proof Size summary in bytes: + // Measured: `683` + // Estimated: `4148` + // Minimum execution time: 52_878_000 picoseconds. + Weight::from_parts(55_012_000, 4148) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + } + /// Storage: `AssetRegistry::CurrencyMetadatas` (r:1 w:1) + /// Proof: `AssetRegistry::CurrencyMetadatas` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn update_currency_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `409` + // Estimated: `3874` + // Minimum execution time: 12_000_000 picoseconds. + Weight::from_parts(13_000_000, 3874) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } +} diff --git a/pallets/slpx/src/benchmarking.rs b/pallets/slpx/src/benchmarking.rs index 2c77e7f99..8a43cd007 100644 --- a/pallets/slpx/src/benchmarking.rs +++ b/pallets/slpx/src/benchmarking.rs @@ -45,8 +45,8 @@ fn init_whitelist() -> (T::AccountId BalanceOf::::unique_saturated_from(100_000_000_000_000u128), )); - CurrencyIdToLocations::::insert(KSM, xcm::v3::Location::default()); - CurrencyIdToLocations::::insert(VKSM, xcm::v3::Location::default()); + CurrencyIdToLocations::::insert(KSM, xcm::v4::Location::default()); + CurrencyIdToLocations::::insert(VKSM, xcm::v4::Location::default()); (caller, receiver) } diff --git a/primitives/src/traits.rs b/primitives/src/traits.rs index a3423ec73..c6cf28de0 100644 --- a/primitives/src/traits.rs +++ b/primitives/src/traits.rs @@ -186,30 +186,9 @@ pub trait CurrencyIdRegister { last_slot: crate::LeasePeriod, ) -> bool; fn register_vtoken_metadata(token_symbol: TokenSymbol) -> DispatchResult; - fn register_vstoken_metadata(token_symbol: TokenSymbol) -> DispatchResult; - fn register_vsbond_metadata( - token_symbol: TokenSymbol, - para_id: crate::ParaId, - first_slot: crate::LeasePeriod, - last_slot: crate::LeasePeriod, - ) -> DispatchResult; fn check_token2_registered(token_id: TokenId) -> bool; fn check_vtoken2_registered(token_id: TokenId) -> bool; - fn check_vstoken2_registered(token_id: TokenId) -> bool; - fn check_vsbond2_registered( - token_id: TokenId, - para_id: crate::ParaId, - first_slot: crate::LeasePeriod, - last_slot: crate::LeasePeriod, - ) -> bool; fn register_vtoken2_metadata(token_id: TokenId) -> DispatchResult; - fn register_vstoken2_metadata(token_id: TokenId) -> DispatchResult; - fn register_vsbond2_metadata( - token_id: TokenId, - para_id: crate::ParaId, - first_slot: crate::LeasePeriod, - last_slot: crate::LeasePeriod, - ) -> DispatchResult; fn register_blp_metadata(pool_id: PoolId, decimals: u8) -> DispatchResult; } @@ -239,19 +218,6 @@ impl CurrencyIdRegister for () { Ok(()) } - fn register_vstoken_metadata(_token_symbol: TokenSymbol) -> DispatchResult { - Ok(()) - } - - fn register_vsbond_metadata( - _token_symbol: TokenSymbol, - _para_id: ParaId, - _first_slot: LeasePeriod, - _last_slot: LeasePeriod, - ) -> DispatchResult { - Ok(()) - } - fn check_token2_registered(_token_id: TokenId) -> bool { false } @@ -260,36 +226,10 @@ impl CurrencyIdRegister for () { false } - fn check_vstoken2_registered(_token_id: TokenId) -> bool { - false - } - - fn check_vsbond2_registered( - _token_id: TokenId, - _para_id: ParaId, - _first_slot: LeasePeriod, - _last_slot: LeasePeriod, - ) -> bool { - false - } - fn register_vtoken2_metadata(_token_id: TokenId) -> DispatchResult { Ok(()) } - fn register_vstoken2_metadata(_token_id: TokenId) -> DispatchResult { - Ok(()) - } - - fn register_vsbond2_metadata( - _token_id: TokenId, - _para_id: ParaId, - _first_slot: LeasePeriod, - _last_slot: LeasePeriod, - ) -> DispatchResult { - Ok(()) - } - fn register_blp_metadata(_pool_id: PoolId, _decimals: u8) -> DispatchResult { Ok(()) } diff --git a/runtime/bifrost-kusama/src/weights/bifrost_asset_registry.rs b/runtime/bifrost-kusama/src/weights/bifrost_asset_registry.rs index 927135cec..cbc3b0ac0 100644 --- a/runtime/bifrost-kusama/src/weights/bifrost_asset_registry.rs +++ b/runtime/bifrost-kusama/src/weights/bifrost_asset_registry.rs @@ -54,36 +54,6 @@ use sp_std::marker::PhantomData; /// Weight functions for bifrost_asset_registry. pub struct BifrostWeight(PhantomData); impl bifrost_asset_registry::WeightInfo for BifrostWeight { - // Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) - // Proof Skipped: AssetRegistry LocationToCurrencyIds (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry CurrencyIdToLocations (r:1 w:1) - // Proof Skipped: AssetRegistry CurrencyIdToLocations (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry AssetMetadatas (r:1 w:1) - // Proof Skipped: AssetRegistry AssetMetadatas (max_values: None, max_size: None, mode: Measured) - fn register_native_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `118` - // Estimated: `3583` - // Minimum execution time: 49_553 nanoseconds. - Weight::from_parts(50_599_000, 3583) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(3)) - } - // Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) - // Proof Skipped: AssetRegistry LocationToCurrencyIds (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry CurrencyIdToLocations (r:1 w:1) - // Proof Skipped: AssetRegistry CurrencyIdToLocations (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry AssetMetadatas (r:1 w:1) - // Proof Skipped: AssetRegistry AssetMetadatas (max_values: None, max_size: None, mode: Measured) - fn update_native_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `250` - // Estimated: `3715` - // Minimum execution time: 56_917 nanoseconds. - Weight::from_parts(57_419_000, 3715) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(3)) - } // Storage: AssetRegistry NextTokenId (r:1 w:1) // Proof Skipped: AssetRegistry NextTokenId (max_values: Some(1), max_size: None, mode: Measured) // Storage: AssetRegistry CurrencyMetadatas (r:1 w:1) @@ -108,28 +78,6 @@ impl bifrost_asset_registry::WeightInfo for BifrostWeig .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) } - // Storage: AssetRegistry CurrencyMetadatas (r:2 w:1) - // Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - fn register_vstoken_metadata() -> Weight { - // Proof Size summary in bytes: - // Measured: `705` - // Estimated: `6645` - // Minimum execution time: 49_492 nanoseconds. - Weight::from_parts(50_943_000, 6645) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - // Storage: AssetRegistry CurrencyMetadatas (r:2 w:1) - // Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - fn register_vsbond_metadata() -> Weight { - // Proof Size summary in bytes: - // Measured: `763` - // Estimated: `6703` - // Minimum execution time: 52_709 nanoseconds. - Weight::from_parts(54_285_000, 6703) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } // Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) // Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) // Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) diff --git a/runtime/bifrost-polkadot/src/weights/bifrost_asset_registry.rs b/runtime/bifrost-polkadot/src/weights/bifrost_asset_registry.rs index 927135cec..cbc3b0ac0 100644 --- a/runtime/bifrost-polkadot/src/weights/bifrost_asset_registry.rs +++ b/runtime/bifrost-polkadot/src/weights/bifrost_asset_registry.rs @@ -54,36 +54,6 @@ use sp_std::marker::PhantomData; /// Weight functions for bifrost_asset_registry. pub struct BifrostWeight(PhantomData); impl bifrost_asset_registry::WeightInfo for BifrostWeight { - // Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) - // Proof Skipped: AssetRegistry LocationToCurrencyIds (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry CurrencyIdToLocations (r:1 w:1) - // Proof Skipped: AssetRegistry CurrencyIdToLocations (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry AssetMetadatas (r:1 w:1) - // Proof Skipped: AssetRegistry AssetMetadatas (max_values: None, max_size: None, mode: Measured) - fn register_native_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `118` - // Estimated: `3583` - // Minimum execution time: 49_553 nanoseconds. - Weight::from_parts(50_599_000, 3583) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(3)) - } - // Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1) - // Proof Skipped: AssetRegistry LocationToCurrencyIds (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry CurrencyIdToLocations (r:1 w:1) - // Proof Skipped: AssetRegistry CurrencyIdToLocations (max_values: None, max_size: None, mode: Measured) - // Storage: AssetRegistry AssetMetadatas (r:1 w:1) - // Proof Skipped: AssetRegistry AssetMetadatas (max_values: None, max_size: None, mode: Measured) - fn update_native_asset() -> Weight { - // Proof Size summary in bytes: - // Measured: `250` - // Estimated: `3715` - // Minimum execution time: 56_917 nanoseconds. - Weight::from_parts(57_419_000, 3715) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(3)) - } // Storage: AssetRegistry NextTokenId (r:1 w:1) // Proof Skipped: AssetRegistry NextTokenId (max_values: Some(1), max_size: None, mode: Measured) // Storage: AssetRegistry CurrencyMetadatas (r:1 w:1) @@ -108,28 +78,6 @@ impl bifrost_asset_registry::WeightInfo for BifrostWeig .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) } - // Storage: AssetRegistry CurrencyMetadatas (r:2 w:1) - // Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - fn register_vstoken_metadata() -> Weight { - // Proof Size summary in bytes: - // Measured: `705` - // Estimated: `6645` - // Minimum execution time: 49_492 nanoseconds. - Weight::from_parts(50_943_000, 6645) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } - // Storage: AssetRegistry CurrencyMetadatas (r:2 w:1) - // Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) - fn register_vsbond_metadata() -> Weight { - // Proof Size summary in bytes: - // Measured: `763` - // Estimated: `6703` - // Minimum execution time: 52_709 nanoseconds. - Weight::from_parts(54_285_000, 6703) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } // Storage: AssetRegistry CurrencyMetadatas (r:1 w:0) // Proof Skipped: AssetRegistry CurrencyMetadatas (max_values: None, max_size: None, mode: Measured) // Storage: AssetRegistry LocationToCurrencyIds (r:1 w:1)