diff --git a/Cargo.lock b/Cargo.lock index c720f89c9c..94f35f7806 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -115,7 +115,7 @@ dependencies = [ [[package]] name = "altair-runtime" -version = "0.10.34" +version = "0.10.35" dependencies = [ "axelar-gateway-precompile", "cfg-primitives", @@ -993,7 +993,7 @@ dependencies = [ [[package]] name = "centrifuge-runtime" -version = "0.10.26" +version = "0.10.27" dependencies = [ "axelar-gateway-precompile", "cfg-primitives", @@ -2451,7 +2451,7 @@ dependencies = [ [[package]] name = "development-runtime" -version = "0.10.43" +version = "0.10.44" dependencies = [ "axelar-gateway-precompile", "cfg-primitives", diff --git a/pallets/block-rewards/src/migrations.rs b/pallets/block-rewards/src/migrations.rs index de7083b42a..3af4a8a66b 100644 --- a/pallets/block-rewards/src/migrations.rs +++ b/pallets/block-rewards/src/migrations.rs @@ -19,6 +19,7 @@ use frame_support::{ }; #[cfg(feature = "try-runtime")] use num_traits::Zero; +#[cfg(feature = "try-runtime")] use parity_scale_codec::{Decode, Encode}; use sp_runtime::FixedPointNumber; #[cfg(feature = "try-runtime")] @@ -164,133 +165,3 @@ pub mod init { } } } - -pub mod v2 { - use frame_support::{ - pallet_prelude::ValueQuery, storage_alias, DefaultNoBound, RuntimeDebugNoBound, - }; - use parity_scale_codec::MaxEncodedLen; - use scale_info::TypeInfo; - - use super::*; - use crate::{CollatorChanges, SessionChanges}; - - const LOG_PREFIX: &str = "RelativeTreasuryInflation"; - - #[derive( - Encode, Decode, TypeInfo, DefaultNoBound, MaxEncodedLen, PartialEq, Eq, RuntimeDebugNoBound, - )] - #[scale_info(skip_type_params(T))] - struct OldSessionData { - pub collator_reward: T::Balance, - pub total_reward: T::Balance, - pub collator_count: u32, - } - - #[derive( - PartialEq, - Clone, - DefaultNoBound, - Encode, - Decode, - TypeInfo, - MaxEncodedLen, - RuntimeDebugNoBound, - )] - #[scale_info(skip_type_params(T))] - struct OldSessionChanges { - pub collators: CollatorChanges, - pub collator_count: Option, - pub collator_reward: Option, - pub total_reward: Option, - } - - #[storage_alias] - type ActiveSessionData = StorageValue, OldSessionData, ValueQuery>; - #[storage_alias] - type NextSessionChanges = StorageValue, OldSessionChanges, ValueQuery>; - - pub struct RelativeTreasuryInflationMigration( - PhantomData<(T, InflationRate)>, - ); - - impl OnRuntimeUpgrade - for RelativeTreasuryInflationMigration - where - T: Config, - InflationPercentage: Get, - { - fn on_runtime_upgrade() -> Weight { - if Pallet::::on_chain_storage_version() == StorageVersion::new(1) { - let active = ActiveSessionData::::take(); - let next = NextSessionChanges::::take(); - - pallet::ActiveSessionData::::put(SessionData { - collator_reward: active.collator_reward, - collator_count: active.collator_count, - treasury_inflation_rate: inflation_rate::(InflationPercentage::get()), - last_update: T::Time::now(), - }); - log::info!("{LOG_PREFIX} Translated ActiveSessionData"); - - pallet::NextSessionChanges::::put(SessionChanges { - collators: next.collators, - collator_count: next.collator_count, - collator_reward: next.collator_reward, - treasury_inflation_rate: Some(inflation_rate::(InflationPercentage::get())), - last_update: T::Time::now(), - }); - log::info!("{LOG_PREFIX} Translated NextSessionChanges"); - Pallet::::current_storage_version().put::>(); - - T::DbWeight::get().reads_writes(1, 5) - } else { - log::info!("{LOG_PREFIX} BlockRewards pallet already on version 2, migration can be removed"); - T::DbWeight::get().reads(1) - } - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, TryRuntimeError> { - assert_eq!( - Pallet::::on_chain_storage_version(), - StorageVersion::new(1), - ); - assert!( - Pallet::::on_chain_storage_version() < Pallet::::current_storage_version() - ); - - let active = ActiveSessionData::::get(); - let next = NextSessionChanges::::get(); - - log::info!("{LOG_PREFIX} PRE UPGRADE: Finished"); - - Ok((active, next).encode()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(pre_state: Vec) -> Result<(), TryRuntimeError> { - let (old_active, old_next): (OldSessionData, OldSessionChanges) = - Decode::decode(&mut pre_state.as_slice()).expect("Pre state valid; qed"); - let active = pallet::ActiveSessionData::::get(); - let next = pallet::NextSessionChanges::::get(); - - assert_eq!(old_active.collator_reward, active.collator_reward); - assert_eq!(old_active.collator_count, active.collator_count); - assert_eq!(old_next.collators, next.collators); - assert_eq!(old_next.collator_count, next.collator_count); - assert_eq!(old_next.collator_reward, next.collator_reward); - assert_eq!( - next.treasury_inflation_rate, - Some(inflation_rate::(InflationPercentage::get())) - ); - assert_eq!( - Pallet::::current_storage_version(), - Pallet::::on_chain_storage_version() - ); - - log::info!("{LOG_PREFIX} POST UPGRADE: Finished"); - Ok(()) - } - } -} diff --git a/pallets/loans/src/entities/loans.rs b/pallets/loans/src/entities/loans.rs index 74209b01a7..5a32d34473 100644 --- a/pallets/loans/src/entities/loans.rs +++ b/pallets/loans/src/entities/loans.rs @@ -580,62 +580,3 @@ impl TryFrom<(T::PoolId, ActiveLoan)> for ActiveLoanInfo { }) } } - -/// Migration module that contains old loans types. -/// Can be removed once chains contains pallet-loans version v3 -pub(crate) mod v2 { - use cfg_traits::Seconds; - use parity_scale_codec::Decode; - - use crate::{ - entities::pricing::{external::v2::ExternalActivePricing, internal::InternalActivePricing}, - types::{LoanRestrictions, RepaidAmount, RepaymentSchedule}, - AssetOf, Config, - }; - - #[derive(Decode)] - pub enum ActivePricing { - Internal(InternalActivePricing), - External(ExternalActivePricing), - } - - #[derive(Decode)] - pub struct ActiveLoan { - schedule: RepaymentSchedule, - collateral: AssetOf, - restrictions: LoanRestrictions, - borrower: T::AccountId, - write_off_percentage: T::Rate, - origination_date: Seconds, - pricing: ActivePricing, - total_borrowed: T::Balance, - total_repaid: RepaidAmount, - repayments_on_schedule_until: Seconds, - } - - impl ActiveLoan { - pub fn migrate(self) -> crate::entities::loans::ActiveLoan { - crate::entities::loans::ActiveLoan { - schedule: self.schedule, - collateral: self.collateral, - restrictions: self.restrictions, - borrower: self.borrower, - write_off_percentage: self.write_off_percentage, - origination_date: self.origination_date, - pricing: match self.pricing { - ActivePricing::Internal(inner) => { - crate::entities::pricing::ActivePricing::Internal(inner) - } - ActivePricing::External(inner) => { - crate::entities::pricing::ActivePricing::External( - inner.migrate(self.origination_date), - ) - } - }, - total_borrowed: self.total_borrowed, - total_repaid: self.total_repaid, - repayments_on_schedule_until: self.repayments_on_schedule_until, - } - } - } -} diff --git a/pallets/loans/src/entities/pricing/external.rs b/pallets/loans/src/entities/pricing/external.rs index 0bc614cf31..9718e8b860 100644 --- a/pallets/loans/src/entities/pricing/external.rs +++ b/pallets/loans/src/entities/pricing/external.rs @@ -288,38 +288,3 @@ impl ExternalActivePricing { Ok(()) } } - -/// Migration module that contains old loans types. -/// Can be removed once chains contains pallet-loans version v3 -pub(crate) mod v2 { - use cfg_traits::Seconds; - use parity_scale_codec::Decode; - - use crate::{ - entities::{interest::ActiveInterestRate, pricing::external::ExternalPricing}, - Config, - }; - - #[derive(Decode)] - pub struct ExternalActivePricing { - info: ExternalPricing, - outstanding_quantity: T::Quantity, - interest: ActiveInterestRate, - latest_settlement_price: T::Balance, - } - - impl ExternalActivePricing { - pub fn migrate( - self, - settlement_price_updated: Seconds, - ) -> crate::entities::pricing::external::ExternalActivePricing { - crate::entities::pricing::external::ExternalActivePricing { - info: self.info, - outstanding_quantity: self.outstanding_quantity, - interest: self.interest, - latest_settlement_price: self.latest_settlement_price, - settlement_price_updated, - } - } - } -} diff --git a/pallets/loans/src/lib.rs b/pallets/loans/src/lib.rs index 44bc9e25e8..73844a4f63 100644 --- a/pallets/loans/src/lib.rs +++ b/pallets/loans/src/lib.rs @@ -65,8 +65,6 @@ mod tests; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; -mod migrations; - pub use pallet::*; pub use weights::WeightInfo; @@ -438,13 +436,6 @@ pub mod pallet { } } - #[pallet::hooks] - impl Hooks> for Pallet { - fn on_runtime_upgrade() -> frame_support::weights::Weight { - migrations::migrate_from_v2_to_v3::() - } - } - #[pallet::call] impl Pallet { /// Creates a new loan against the collateral provided diff --git a/pallets/loans/src/migrations.rs b/pallets/loans/src/migrations.rs deleted file mode 100644 index ace3393389..0000000000 --- a/pallets/loans/src/migrations.rs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2024 Centrifuge Foundation (centrifuge.io). -// -// This file is part of the Centrifuge chain project. -// Centrifuge 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 (see http://www.gnu.org/licenses). -// Centrifuge 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. - -use cfg_traits::PoolNAV; -use frame_support::{ - dispatch::GetStorageVersion, inherent::Vec, log, pallet_prelude::StorageVersion, traits::Get, - weights::Weight, -}; - -use crate::{ActiveLoans, Config, Pallet}; - -mod v2 { - use frame_support::{pallet_prelude::*, storage_alias}; - - use crate::{entities::loans::v2, Config, Pallet}; - - pub type ActiveLoansVec = BoundedVec< - (::LoanId, v2::ActiveLoan), - ::MaxActiveLoansPerPool, - >; - - #[storage_alias] - pub type ActiveLoans = StorageMap< - Pallet, - Blake2_128Concat, - ::PoolId, - ActiveLoansVec, - ValueQuery, - >; -} - -pub fn migrate_from_v2_to_v3() -> Weight { - if Pallet::::on_chain_storage_version() == StorageVersion::new(2) { - log::info!("Loans: Starting migration v2 -> v3"); - - let mut changed_pools = Vec::new(); - ActiveLoans::::translate::, _>(|pool_id, active_loans| { - changed_pools.push(pool_id); - Some( - active_loans - .into_iter() - .map(|(loan_id, active_loan)| (loan_id, active_loan.migrate())) - .collect::>() - .try_into() - .expect("size doest not change, qed"), - ) - }); - - for pool_id in &changed_pools { - match Pallet::::update_nav(*pool_id) { - Ok(_) => log::info!("Loans: updated portfolio for pool_id: {pool_id:?}"), - Err(e) => log::error!("Loans: error updating the portfolio for {pool_id:?}: {e:?}"), - } - } - - Pallet::::current_storage_version().put::>(); - - let count = changed_pools.len() as u64; - log::info!("Loans: Migrated {} pools", count); - T::DbWeight::get().reads_writes(count + 1, count + 1) - } else { - // wrong storage version - log::warn!("Loans: Migration did not execute. This probably should be removed"); - T::DbWeight::get().reads_writes(1, 0) - } -} diff --git a/runtime/altair/Cargo.toml b/runtime/altair/Cargo.toml index f38cbaff4b..6bb71fc462 100644 --- a/runtime/altair/Cargo.toml +++ b/runtime/altair/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "altair-runtime" -version = "0.10.34" +version = "0.10.35" build = "build.rs" authors.workspace = true edition.workspace = true diff --git a/runtime/altair/src/lib.rs b/runtime/altair/src/lib.rs index 5f09873b29..146266ce77 100644 --- a/runtime/altair/src/lib.rs +++ b/runtime/altair/src/lib.rs @@ -149,7 +149,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("altair"), impl_name: create_runtime_str!("altair"), authoring_version: 1, - spec_version: 1034, + spec_version: 1035, impl_version: 1, #[cfg(not(feature = "disable-runtime-api"))] apis: RUNTIME_API_VERSIONS, @@ -1946,7 +1946,7 @@ pub type Executive = frame_executive::Executive< frame_system::ChainContext, Runtime, AllPalletsWithSystem, - migrations::UpgradeAltair1034, + migrations::UpgradeAltair1035, >; // Frame Order in this block dictates the index of each one in the metadata diff --git a/runtime/altair/src/migrations.rs b/runtime/altair/src/migrations.rs index ef5a3bfc34..c4c6eceb93 100644 --- a/runtime/altair/src/migrations.rs +++ b/runtime/altair/src/migrations.rs @@ -10,602 +10,6 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use cfg_primitives::{PoolId, TrancheId}; -use cfg_types::tokens::{CurrencyId, CustomMetadata, ForeignAssetId, StakingCurrency}; -use frame_support::{ - dispatch::{Decode, Encode, MaxEncodedLen, TypeInfo}, - traits::OnRuntimeUpgrade, - weights::Weight, - RuntimeDebugNoBound, -}; -use orml_traits::asset_registry::AssetMetadata; - -frame_support::parameter_types! { - pub const NftSalesPalletName: &'static str = "NftSales"; - pub const MigrationPalletName: &'static str = "Migration"; - pub const AnnualTreasuryInflationPercent: u32 = 3; -} - -/// The migration set for Altair 1034 @ Kusama. It includes all the migrations -/// that have to be applied on that chain. -pub type UpgradeAltair1034 = ( - // Updates asset custom metadata from mid 2023 to latest (two fields missing/mismatching) - translate_asset_metadata::Migration, - // Removes hardcoded AUSD currency id and migrates balance - ausd_to_foreign::CurrencyIdRefactorMigration, - // At minimum, bumps storage version from 1 to 2 - runtime_common::migrations::nuke::ResetPallet, - // At minimum, bumps storage version from 0 to 3 - runtime_common::migrations::nuke::ResetPallet, - // At minimum, bumps storage version from 0 to 2 - runtime_common::migrations::nuke::ResetPallet, - // At minimum, bumps storage version from 0 to 1 - runtime_common::migrations::nuke::ResetPallet, - // Funds pallet_rewards::Instance2 account with existential deposit - pallet_rewards::migrations::new_instance::FundExistentialDeposit< - crate::Runtime, - pallet_rewards::Instance2, - crate::NativeToken, - crate::ExistentialDeposit, - >, - // Removes metadata containing xcm_v1 locations of registered assets and sets to hardcoded ones - // containing xcm_v3 locations - runtime_common::migrations::asset_registry_xcmv3::Migration< - crate::Runtime, - asset_registry::AltairAssets, - 5, - 5, - 2, - 9, - >, - // Low weight, mainly bumps storage version to latest (v1 to v2) - crate::DmpQueue, - // Low weight, mainly bumps storage version to latest (v2 to v3) - crate::XcmpQueue, - // Low weight, bumps uninitialized storage version from v0 to v1 - pallet_xcm::migration::v1::MigrateToV1, - // Sets currently unset safe XCM version to v2 - xcm_v2_to_v3::SetSafeXcmVersion, - // Sets account codes for all precompiles - runtime_common::migrations::precompile_account_codes::Migration, - // Migrates EpochExecution V1 to V2 - runtime_common::migrations::epoch_execution::Migration, - // Probably not needed, as storage is likely not populated. Migrates currency used in allowlist - runtime_common::migrations::transfer_allowlist_currency::Migration, - // Removes unused nft-sales pallet - runtime_common::migrations::nuke::KillPallet, - // Removes unused migration pallet - runtime_common::migrations::nuke::KillPallet, - // Apply relative treasury inflation - pallet_block_rewards::migrations::v2::RelativeTreasuryInflationMigration< - crate::Runtime, - AnnualTreasuryInflationPercent, - >, - // Bump balances storage version from v0 to v1 and mark balance of CheckingAccount as inactive, - // see https://github.com/paritytech/substrate/pull/12813 - pallet_balances::migration::MigrateToTrackInactive, - // Assets were already migrated to V3 MultiLocation but version not increased from 0 to 2 - runtime_common::migrations::increase_storage_version::Migration, - // Data was already moved but storage version not increased from 0 to 4 - runtime_common::migrations::increase_storage_version::Migration, -); - -#[allow(clippy::upper_case_acronyms)] -#[derive( - Clone, - Copy, - Default, - PartialOrd, - Ord, - PartialEq, - Eq, - RuntimeDebugNoBound, - Encode, - Decode, - TypeInfo, - MaxEncodedLen, -)] -pub enum OldCurrencyId { - // The Native token, representing AIR in Altair and CFG in Centrifuge. - #[default] - #[codec(index = 0)] - Native, - - /// A Tranche token - #[codec(index = 1)] - Tranche(PoolId, TrancheId), - - /// DEPRECATED - Will be removed in the next Altair RU 1034 when the - /// orml_tokens' balances are migrated to the new CurrencyId for AUSD. - #[codec(index = 2)] - KSM, - - /// DEPRECATED - Will be removed in the next Altair RU 1034 when the - /// orml_tokens' balances are migrated to the new CurrencyId for AUSD. - #[codec(index = 3)] - AUSD, - - /// A foreign asset - #[codec(index = 4)] - ForeignAsset(ForeignAssetId), - - /// A staking currency - #[codec(index = 5)] - Staking(StakingCurrency), -} - -mod asset_registry { - use cfg_primitives::Balance; - use cfg_types::{ - tokens::{CrossChainTransferability, CurrencyId, CustomMetadata}, - xcm::XcmMetadata, - }; - use sp_std::{vec, vec::Vec}; - use xcm::{v3::prelude::*, VersionedMultiLocation}; - - pub struct AltairAssets; - impl runtime_common::migrations::asset_registry_xcmv3::AssetsToMigrate for AltairAssets { - fn get_assets_to_migrate() -> Vec<( - CurrencyId, - orml_asset_registry::AssetMetadata, - )> { - let mut gk = [0u8; 32]; - gk[1] = 1; - - // 0x0081 - let mut gk_acala = [0u8; 32]; - gk_acala[..2].copy_from_slice(&[0, 129]); - - // Skipping AUSD since it seems that should be registered differently, lets do - // it manually later on - vec![ - ( - CurrencyId::Native, - orml_asset_registry::AssetMetadata { - decimals: 18, - name: b"Altair".to_vec(), - symbol: b"AIR".to_vec(), - existential_deposit: 1_000_000_000_000u128, - location: Some(VersionedMultiLocation::V3(MultiLocation::new( - 1, - Junctions::X2( - Parachain(crate::ParachainInfo::parachain_id().into()), - GeneralKey { - length: 2, - data: gk, - }, - ), - ))), - additional: CustomMetadata { - mintable: false, - permissioned: false, - pool_currency: false, - transferability: CrossChainTransferability::Xcm(XcmMetadata { - fee_per_second: None, - }), - local_representation: None, - }, - }, - ), - ( - CurrencyId::ForeignAsset(1), - orml_asset_registry::AssetMetadata { - decimals: 6, - name: b"Tether USDT".to_vec(), - symbol: b"USDT".to_vec(), - existential_deposit: 10_000u128, - location: Some(VersionedMultiLocation::V3(MultiLocation::new( - 1, - Junctions::X3(Parachain(1000), PalletInstance(50), GeneralIndex(1984)), - ))), - additional: CustomMetadata { - mintable: false, - permissioned: false, - pool_currency: true, - transferability: CrossChainTransferability::Xcm(XcmMetadata { - fee_per_second: None, - }), - local_representation: None, - }, - }, - ), - ( - CurrencyId::ForeignAsset(2), - orml_asset_registry::AssetMetadata { - decimals: 12, - name: b"Acala Dollar".to_vec(), - symbol: b"aUSD".to_vec(), - existential_deposit: 10_000_000_000u128, - location: Some(VersionedMultiLocation::V3(MultiLocation::new( - 1, - Junctions::X2( - Parachain(2000), - GeneralKey { - length: 2, - data: gk_acala, - }, - ), - ))), - additional: CustomMetadata { - mintable: false, - permissioned: false, - pool_currency: true, - transferability: CrossChainTransferability::Xcm(XcmMetadata { - fee_per_second: None, - }), - local_representation: None, - }, - }, - ), - ( - CurrencyId::ForeignAsset(3), - orml_asset_registry::AssetMetadata { - decimals: 12, - name: b"Kusama".to_vec(), - symbol: b"KSM".to_vec(), - existential_deposit: 10_000_000_000u128, - location: Some(VersionedMultiLocation::V3(MultiLocation::new( - 1, - Junctions::Here, - ))), - additional: CustomMetadata { - mintable: false, - permissioned: false, - pool_currency: false, - transferability: CrossChainTransferability::Xcm(XcmMetadata { - fee_per_second: None, - }), - local_representation: None, - }, - }, - ), - ] - } - } -} - -pub mod translate_asset_metadata { - use cfg_primitives::Balance; - use frame_support::{ - dispatch::{Decode, Encode, MaxEncodedLen, TypeInfo}, - storage_alias, - traits::Get, - Twox64Concat, - }; - #[cfg(feature = "try-runtime")] - use sp_runtime::DispatchError; - #[cfg(feature = "try-runtime")] - use sp_std::vec::Vec; - - use super::*; - - const LOG_PREFIX: &str = "TranslateMetadata"; - - #[derive( - Clone, - Copy, - Default, - PartialOrd, - Ord, - PartialEq, - Eq, - Debug, - Encode, - Decode, - TypeInfo, - MaxEncodedLen, - )] - pub struct XcmMetadata { - pub fee_per_second: Option, - } - - #[derive( - Clone, - Copy, - Default, - PartialOrd, - Ord, - PartialEq, - Eq, - Debug, - Encode, - Decode, - TypeInfo, - MaxEncodedLen, - )] - struct OldCustomMetadata { - pub xcm: XcmMetadata, - pub mintable: bool, - pub permissioned: bool, - pub pool_currency: bool, - } - - #[storage_alias] - type Metadata = StorageMap< - orml_asset_registry::Pallet, - Twox64Concat, - OldCurrencyId, - AssetMetadata, - >; - - pub struct Migration(sp_std::marker::PhantomData); - - impl OnRuntimeUpgrade for Migration - where - T: orml_asset_registry::Config< - CustomMetadata = CustomMetadata, - AssetId = CurrencyId, - Balance = Balance, - >, - { - fn on_runtime_upgrade() -> Weight { - let mut weight = Weight::zero(); - orml_asset_registry::Metadata::::translate::< - AssetMetadata, - _, - >(|_, meta| { - weight.saturating_accrue(T::DbWeight::get().writes(1)); - Some(AssetMetadata { - decimals: meta.decimals, - name: meta.name, - symbol: meta.symbol, - existential_deposit: meta.existential_deposit, - location: meta.location, - additional: CustomMetadata { - mintable: meta.additional.mintable, - permissioned: meta.additional.permissioned, - pool_currency: meta.additional.pool_currency, - ..Default::default() - }, - }) - }); - log::info!("{LOG_PREFIX} Done translating asset metadata"); - - weight - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, DispatchError> { - let num_assets = Metadata::::iter_keys().count() as u32; - log::info!( - "{LOG_PREFIX} PRE UPGRADE: Finished with {} registered assets", - num_assets - ); - - Ok(num_assets.encode()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(pre_state: Vec) -> Result<(), DispatchError> { - let n_pre: u32 = Decode::decode(&mut pre_state.as_slice()) - .expect("pre_ugprade provides a valid state; qed"); - let n = orml_asset_registry::Metadata::::iter_keys().count() as u32; - assert_eq!(n_pre, n); - - log::info!("{LOG_PREFIX} POST UPGRADE: Finished"); - - Ok(()) - } - } -} - -mod ausd_to_foreign { - use cfg_primitives::{AccountId, Balance}; - use cfg_types::tokens::CurrencyId; - #[cfg(feature = "try-runtime")] - use frame_support::ensure; - use frame_support::{ - pallet_prelude::ValueQuery, storage::unhashed, storage_alias, Blake2_128Concat, - StoragePrefixedMap, Twox64Concat, - }; - use orml_tokens::AccountData; - use parity_scale_codec::{Decode, Encode}; - #[cfg(feature = "try-runtime")] - use sp_runtime::traits::Zero; - #[cfg(feature = "try-runtime")] - use sp_runtime::DispatchError; - use sp_runtime::Saturating; - use sp_std::vec::Vec; - - use super::*; - use crate::Runtime; - - const DEPRECATED_AUSD_CURRENCY_ID: OldCurrencyId = OldCurrencyId::AUSD; - const NEW_AUSD_CURRENCY_ID: CurrencyId = CurrencyId::ForeignAsset(2); - const LOG_PREFIX: &str = "MigrateAUSD"; - - /// As we dropped `CurrencyId::KSM` and `CurrencyId::AUSD`, we need to - /// migrate the balances under the dropped variants in favour of the new, - /// corresponding `CurrencyId::ForeignAsset`. We have never transferred KSM - /// so we only need to deal with AUSD. - pub struct CurrencyIdRefactorMigration(sp_std::marker::PhantomData); - - #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)] - pub struct OldState { - pub total_issuance: Balance, - pub entries: Vec<(AccountId, AccountData)>, - } - - #[storage_alias] - type TotalIssuance = - StorageMap, Twox64Concat, OldCurrencyId, Balance, ValueQuery>; - - #[storage_alias] - type Accounts = StorageDoubleMap< - orml_tokens::Pallet, - Blake2_128Concat, - AccountId, - Twox64Concat, - OldCurrencyId, - AccountData, - ValueQuery, - >; - - impl OnRuntimeUpgrade for CurrencyIdRefactorMigration - where - T: orml_asset_registry::Config - + orml_tokens::Config - + frame_system::Config, - { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, DispatchError> { - let total_issuance = TotalIssuance::::get(DEPRECATED_AUSD_CURRENCY_ID); - let entries: Vec<(AccountId, AccountData)> = Accounts::::iter() - .filter(|(_, old_currency_id, _)| *old_currency_id == DEPRECATED_AUSD_CURRENCY_ID) - .map(|(account, _, account_data)| (account, account_data)) - .collect::<_>(); - - log::info!( - "{LOG_PREFIX} PRE-UPGRADE: Counted accounts to be migrated is {} with total issuance of {total_issuance}", entries.iter().count() - ); - - Ok(OldState { - total_issuance, - entries, - } - .encode()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(state: Vec) -> Result<(), DispatchError> { - let old_state = OldState::decode(&mut state.as_ref()) - .map_err(|_| "Error decoding pre-upgrade state")?; - - let new_total_issuance = orml_tokens::TotalIssuance::::get(NEW_AUSD_CURRENCY_ID); - - ensure!( - old_state.total_issuance == new_total_issuance, - "The old AUSD issuance differs from the new one" - ); - ensure!( - TotalIssuance::::get(DEPRECATED_AUSD_CURRENCY_ID).is_zero(), - "The total issuance of old AUSD is not zero!" - ); - - for (account, account_data) in old_state.entries { - ensure!( - orml_tokens::Pallet::::accounts(&account, NEW_AUSD_CURRENCY_ID) - == account_data.clone(), - "The account data under the new AUSD Currency does NOT match the old one" - ); - ensure!( - Accounts::::get(&account, DEPRECATED_AUSD_CURRENCY_ID) == Default::default(), - "The account data for old AUSD is not cleared" - ); - } - - log::info!("{LOG_PREFIX} POST-UPGRADE: Done"); - - Ok(()) - } - - fn on_runtime_upgrade() -> Weight { - use frame_support::traits::tokens::fungibles::Mutate; - - let mut migrated_entries: u64 = 0; - - // Burn all AUSD tokens under the old CurrencyId and mint them under the new one - Accounts::::iter() - .filter(|(_, old_currency_id, _)| *old_currency_id == DEPRECATED_AUSD_CURRENCY_ID) - .for_each(|(account, _, account_data)| { - log::info!( - "{LOG_PREFIX} Migrating account with balance: {}", - account_data.free - ); - - let balance = account_data.free; - - // Remove account data and reduce total issuance manually at the end - Accounts::::remove(account.clone(), DEPRECATED_AUSD_CURRENCY_ID); - - // Now mint the amount under the new CurrencyID - as Mutate>::mint_into( - NEW_AUSD_CURRENCY_ID, - &account, - balance, - ) - .map_err(|e| { - log::error!( - "Failed to mint_into burn_from({:?}, {:?}, {balance}): {:?}", - NEW_AUSD_CURRENCY_ID, - account, - e - ) - }) - .ok(); - - migrated_entries += 1; - }); - log::info!( - "{LOG_PREFIX} Number of migrated accounts: {:?} ", - migrated_entries - ); - - TotalIssuance::::remove(DEPRECATED_AUSD_CURRENCY_ID); - - // Remove undecodable storage entries - let (reads, writes) = remove_undecodable_storage_keys::(); - log::info!("{LOG_PREFIX} Removed {writes} undecodable storage entries from Accounts"); - - log::info!("{LOG_PREFIX} Done"); - - // Approximate weight given for every entry migration there are two calls being - // made, so counting the reads and writes for each call. - ::DbWeight::get().reads_writes( - migrated_entries.saturating_mul(5).saturating_add(reads), - migrated_entries - .saturating_mul(4) - .saturating_add(writes.saturating_add(1)), - ) - } - } - - fn remove_undecodable_storage_keys() -> (u64, u64) { - let prefix = orml_tokens::Accounts::::final_prefix(); - let mut previous_key = prefix.clone().to_vec(); - let mut reads: u64 = 1; - let mut writes: u64 = 0; - while let Some(next) = - sp_io::storage::next_key(&previous_key).filter(|n| n.starts_with(&prefix)) - { - reads.saturating_accrue(1); - previous_key = next; - let maybe_value = unhashed::get::(&previous_key); - match maybe_value { - Some(_) => continue, - None => { - log::info!( - "Removing Account key which could not be decoded at {:?}", - previous_key - ); - unhashed::kill(&previous_key); - writes.saturating_accrue(1); - continue; - } - } - } - - (reads, writes) - } -} - -mod xcm_v2_to_v3 { - use super::*; - use crate::{PolkadotXcm, RuntimeOrigin}; - - pub struct SetSafeXcmVersion; - - impl OnRuntimeUpgrade for SetSafeXcmVersion { - fn on_runtime_upgrade() -> Weight { - // Unfortunately, SafeXcmVersion storage is not leaked to runtime, so we can't - // do any pre- or post-upgrade checks - PolkadotXcm::force_default_xcm_version( - RuntimeOrigin::root(), - Some(cfg_primitives::SAFE_XCM_VERSION), - ) - .unwrap_or_else(|_| log::error!("Failed to set safe XCM version on runtime upgrade, requires manual call via governance")); - - crate::RocksDbWeight::get().writes(1) - } - } -} +/// The migration set for Altair @ Kusama. +/// It includes all the migrations that have to be applied on that chain. +pub type UpgradeAltair1035 = (); diff --git a/runtime/centrifuge/Cargo.toml b/runtime/centrifuge/Cargo.toml index 2767683f09..0268a4b0ab 100644 --- a/runtime/centrifuge/Cargo.toml +++ b/runtime/centrifuge/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "centrifuge-runtime" -version = "0.10.26" +version = "0.10.27" build = "build.rs" authors.workspace = true edition.workspace = true diff --git a/runtime/centrifuge/src/lib.rs b/runtime/centrifuge/src/lib.rs index ebab64c90d..57c379f2f3 100644 --- a/runtime/centrifuge/src/lib.rs +++ b/runtime/centrifuge/src/lib.rs @@ -153,7 +153,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("centrifuge"), impl_name: create_runtime_str!("centrifuge"), authoring_version: 1, - spec_version: 1026, + spec_version: 1027, impl_version: 1, #[cfg(not(feature = "disable-runtime-api"))] apis: RUNTIME_API_VERSIONS, @@ -2061,7 +2061,7 @@ pub type Executive = frame_executive::Executive< frame_system::ChainContext, Runtime, AllPalletsWithSystem, - migrations::UpgradeCentrifuge1026, + migrations::UpgradeCentrifuge1027, >; // Frame Order in this block dictates the index of each one in the metadata diff --git a/runtime/centrifuge/src/migrations.rs b/runtime/centrifuge/src/migrations.rs index ca0ac12d1a..ab32ab23f6 100644 --- a/runtime/centrifuge/src/migrations.rs +++ b/runtime/centrifuge/src/migrations.rs @@ -10,190 +10,6 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use cfg_primitives::{Balance, PoolId}; -use cfg_types::tokens::{ - usdc::{ - CURRENCY_ID_AXELAR, CURRENCY_ID_DOT_NATIVE, CURRENCY_ID_LOCAL, CURRENCY_ID_LP_ARB, - CURRENCY_ID_LP_BASE, CURRENCY_ID_LP_CELO, CURRENCY_ID_LP_CELO_WORMHOLE, CURRENCY_ID_LP_ETH, - LOCAL_ASSET_ID, - }, - CurrencyId, LocalAssetId, -}; - -frame_support::parameter_types! { - pub const ClaimsPalletName: &'static str = "Claims"; - pub const MigrationPalletName: &'static str = "Migration"; - pub const UsdcVariants: [CurrencyId; 6] = [CURRENCY_ID_DOT_NATIVE, CURRENCY_ID_AXELAR, CURRENCY_ID_LP_ETH, CURRENCY_ID_LP_BASE, CURRENCY_ID_LP_ARB, CURRENCY_ID_LP_CELO]; - pub const LocalAssetIdUsdc: LocalAssetId = LOCAL_ASSET_ID; - pub const LocalCurrencyIdUsdc: CurrencyId = CURRENCY_ID_LOCAL; - pub const PoolIdAnemoy: PoolId = 4_139_607_887; - pub const PoolCurrencyAnemoy: CurrencyId = CURRENCY_ID_DOT_NATIVE; - pub const UsdcDot: CurrencyId = CURRENCY_ID_DOT_NATIVE; - pub const UsdcEth: CurrencyId = CURRENCY_ID_LP_ETH; - pub const UsdcBase: CurrencyId = CURRENCY_ID_LP_BASE; - pub const UsdcArb: CurrencyId = CURRENCY_ID_LP_ARB; - pub const UsdcCeloWormhole: CurrencyId = CURRENCY_ID_LP_CELO_WORMHOLE; - pub const UsdcCelo: CurrencyId = CURRENCY_ID_LP_CELO; - pub const MinOrderAmount: Balance = 10u128.pow(6); - pub const AnnualTreasuryInflationPercent: u32 = 3; -} - -pub type UpgradeCentrifuge1026 = ( - runtime_common::migrations::epoch_execution::Migration, - // Migrates the currency used in `pallet-transfer-allowlist` from our global currency to a - // special filter currency enum - runtime_common::migrations::transfer_allowlist_currency::Migration, - // Removes tinlake reward claims pallet - runtime_common::migrations::nuke::KillPallet, - // Register LocalUSDC - runtime_common::migrations::local_currency::register::Migration< - super::Runtime, - LocalCurrencyIdUsdc, - >, - // Register new canonical USDC on Celo - runtime_common::migrations::update_celo_usdcs::AddNewCeloUsdc, - // Update custom metadata by initiating local representation for all assets - runtime_common::migrations::local_currency::translate_metadata::Migration< - super::Runtime, - UsdcVariants, - LocalAssetIdUsdc, - >, - // Change name and symbol of Celo Wormhole USDC - // NOTE: Needs to happen after metadata translation because expects new CustomMetadata - runtime_common::migrations::update_celo_usdcs::UpdateWormholeUsdc, - // Switch pool currency from Polkadot USDC to Local USDC - runtime_common::migrations::local_currency::migrate_pool_currency::Migration< - super::Runtime, - PoolIdAnemoy, - PoolCurrencyAnemoy, - LocalCurrencyIdUsdc, - >, - // Removes unused migration pallet - runtime_common::migrations::nuke::KillPallet, - // Sets account codes for all precompiles - runtime_common::migrations::precompile_account_codes::Migration, - // Bumps storage version from 0 to 1 - runtime_common::migrations::nuke::ResetPallet, - // Apply relative treasury inflation - pallet_block_rewards::migrations::v2::RelativeTreasuryInflationMigration< - crate::Runtime, - AnnualTreasuryInflationPercent, - >, - // Bump balances storage version from v0 to v1 and mark balance of CheckingAccount as inactive, - // see https://github.com/paritytech/substrate/pull/12813 - pallet_balances::migration::MigrateToTrackInactive, - // Assets were already migrated to V3 MultiLocation but version not increased from 0 to 2 - runtime_common::migrations::increase_storage_version::Migration, - // Burns tokens from other domains that are falsly not burned when they were transferred back - // to their domain - burn_unburned::Migration, - // Bumps storage version from 0 to 1 - runtime_common::migrations::nuke::ResetPallet< - crate::ForeignInvestments, - crate::RocksDbWeight, - 0, - >, -); - -mod burn_unburned { - const LOG_PREFIX: &str = "BurnUnburnedMigration: "; - const LP_ETH_USDC: CurrencyId = CurrencyId::ForeignAsset(100_001); - const ETH_DOMAIN: Domain = Domain::EVM(1); - - use cfg_types::{domain_address::Domain, tokens::CurrencyId}; - use frame_support::traits::{ - fungibles::Mutate, - tokens::{Fortitude, Precision}, - OnRuntimeUpgrade, - }; - use pallet_order_book::weights::Weight; - use sp_runtime::traits::{Convert, Get}; - - pub struct Migration - where - T: orml_tokens::Config + frame_system::Config, - { - _phantom: sp_std::marker::PhantomData, - } - - impl OnRuntimeUpgrade for Migration - where - T: orml_tokens::Config + frame_system::Config, - { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { - use sp_runtime::traits::Zero; - - let pre_data = orml_tokens::Accounts::::get( - >::convert(ETH_DOMAIN), - LP_ETH_USDC, - ); - - if !pre_data.frozen.is_zero() || !pre_data.reserved.is_zero() { - log::error!( - "{LOG_PREFIX} AccountData of Ethereum domain account has non free balances..." - ); - } - let total_issuance = orml_tokens::TotalIssuance::::get(LP_ETH_USDC); - assert_eq!(total_issuance, pre_data.free); - - log::info!( - "{LOG_PREFIX} AccountData of Ethereum domain account has free balance of: {:?}", - pre_data.free - ); - - Ok(sp_std::vec::Vec::new()) - } - - fn on_runtime_upgrade() -> Weight { - let data = orml_tokens::Accounts::::get( - >::convert(ETH_DOMAIN), - LP_ETH_USDC, - ); - if let Err(e) = orml_tokens::Pallet::::burn_from( - LP_ETH_USDC, - &>::convert(ETH_DOMAIN), - data.free, - Precision::Exact, - Fortitude::Force, - ) { - log::error!( - "{LOG_PREFIX} Burning from Ethereum domain account failed with: {:?}. Migration failed...", - e - ); - } else { - log::info!( - "{LOG_PREFIX} Successfully burned {:?} LP_ETH_USDC from Ethereum domain account", - data.free - ); - } - - T::DbWeight::get().writes(2) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { - use sp_runtime::traits::Zero; - - assert!(orml_tokens::TotalIssuance::::get(LP_ETH_USDC).is_zero()); - - let post_data = orml_tokens::Accounts::::get( - >::convert(ETH_DOMAIN), - LP_ETH_USDC, - ); - - if !post_data.free.is_zero() - || !post_data.frozen.is_zero() - || !post_data.reserved.is_zero() - { - log::error!( - "{LOG_PREFIX} AccountData of Ethereum domain account SHOULD be zero. Migration failed." - ); - } else { - log::info!("{LOG_PREFIX} Migration successfully finished.") - } - - Ok(()) - } - } -} +/// The migration set for Centrifuge @ Polkadot. +/// It includes all the migrations that have to be applied on that chain. +pub type UpgradeCentrifuge1027 = (); diff --git a/runtime/common/src/migrations/asset_registry_xcmv3.rs b/runtime/common/src/migrations/asset_registry_xcmv3.rs deleted file mode 100644 index a9327856e3..0000000000 --- a/runtime/common/src/migrations/asset_registry_xcmv3.rs +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright 2023 Centrifuge Foundation (centrifuge.io). -// This file is part of Centrifuge chain project. - -// Centrifuge 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 (see http://www.gnu.org/licenses). - -// Centrifuge 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. - -use cfg_primitives::Balance; -use cfg_types::tokens::{CurrencyId, CustomMetadata}; -use frame_support::{ - traits::OnRuntimeUpgrade, - weights::{constants::RocksDbWeight, Weight}, - StoragePrefixedMap, -}; -use orml_traits::asset_registry::AssetMetadata; -#[cfg(feature = "try-runtime")] -use parity_scale_codec::Encode; -#[cfg(feature = "try-runtime")] -use sp_arithmetic::traits::Zero; -#[cfg(feature = "try-runtime")] -use sp_runtime::DispatchError; -use sp_std::vec::Vec; - -pub struct Migration< - T, - Assets, - const EXPECTED_MAINNET_LOC_COUNT: u32, - const EXPECTED_MAINNET_META_COUNT: u32, - const EXPECTED_TESTNET_LOC_COUNT: u32, - const EXPECTED_TESTNET_META_COUNT: u32, ->(sp_std::marker::PhantomData<(T, Assets)>); - -impl< - T, - Assets, - const EXPECTED_MAINNET_LOC_COUNT: u32, - const EXPECTED_MAINNET_META_COUNT: u32, - const EXPECTED_TESTNET_LOC_COUNT: u32, - const EXPECTED_TESTNET_META_COUNT: u32, - > OnRuntimeUpgrade - for Migration< - T, - Assets, - EXPECTED_MAINNET_LOC_COUNT, - EXPECTED_MAINNET_META_COUNT, - EXPECTED_TESTNET_LOC_COUNT, - EXPECTED_TESTNET_META_COUNT, - > where - T: orml_asset_registry::Config, - ::Balance: From, - ::CustomMetadata: From, - ::AssetId: From, - AssetMetadata< - ::Balance, - ::CustomMetadata, - >: From>, - Assets: AssetsToMigrate, -{ - fn on_runtime_upgrade() -> Weight { - log::info!("💎 AssetRegistryMultilocationToXCMV3: on_runtime_upgrade: started"); - // Complexity: 2 reads - let (loc_count, meta_count) = Self::get_key_counts(); - - if Self::check_key_counts(loc_count, meta_count).is_err() { - return RocksDbWeight::get().reads(loc_count.saturating_add(meta_count).into()); - } - - // Complexity: O(loc_count) writes - let result = orml_asset_registry::LocationToAssetId::::clear(loc_count, None); - match result.maybe_cursor { - None => log::info!("💎 AssetRegistryMultilocationToXCMV3: Cleared all LocationToAssetId entries successfully"), - Some(_) => { - log::error!( - "💎 AssetRegistryMultilocationToXCMV3: LocationToAssetId not fully cleared: {:?} remaining", - orml_asset_registry::LocationToAssetId::::iter_keys().count() - ) - } - } - log::info!( - "💎 AssetRegistryMultilocationToXCMV3: LocationToAssetId clearing iteration result. backend: {} unique: {} loops: {}", - result.backend, - result.unique, - result.loops, - ); - - // Complexity: O(meta_count) writes - let result = orml_asset_registry::Metadata::::clear(meta_count, None); - match result.maybe_cursor { - None => log::info!("Cleared all Metadata entries successfully"), - Some(_) => log::error!("Metadata not fully cleared"), - } - log::info!( - "💎 AssetRegistryMultilocationToXCMV3: Metadata clearing iteration result. backend: {} unique: {} loops: {}", - result.backend, - result.unique, - result.loops, - ); - - let assets = Assets::get_assets_to_migrate(); - log::info!( - "💎 AssetRegistryMultilocationToXCMV3: Starting migration of {:?} assets", - assets.iter().len() - ); - - // Complexity: O(meta_count + loc_count) writes - assets.into_iter().for_each(|(asset_id, asset_metadata)| { - log::debug!("Migrating asset: {:?}", asset_id); - orml_asset_registry::Pallet::::do_register_asset_without_asset_processor( - asset_metadata.into(), - asset_id.into(), - ) - .map_err(|e| log::error!("Failed to register asset id: {:?}", e)) - .ok(); - }); - - log::info!("💎 AssetRegistryMultilocationToXCMV3: on_runtime_upgrade: completed!"); - RocksDbWeight::get().reads_writes( - loc_count.saturating_add(meta_count).into(), - loc_count - .saturating_add(meta_count) - .saturating_mul(2) - .into(), - ) - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, DispatchError> { - log::info!("💎 AssetRegistryMultilocationToXCMV3: pre-upgrade: started"); - let (loc_count, meta_count) = Self::get_key_counts(); - - Self::check_key_counts(loc_count, meta_count)?; - - log::info!("💎 AssetRegistryMultilocationToXCMV3: pre-upgrade: done"); - Ok((loc_count, meta_count).encode()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_old_counts: Vec) -> Result<(), DispatchError> { - log::info!("💎 AssetRegistryMultilocationToXCMV3: post-upgrade: started"); - let (loc_count, meta_count) = Self::get_key_counts(); - - // Should not check for strict equality as at least the location count is - // expected to have increased - // * For Centrifuge we can check post_upgrade >= pre_upgrade - // * For Altair, we remove one of the two AUSD variants and thus have less - // registered currencies - assert!(!loc_count.is_zero()); - assert!(!meta_count.is_zero()); - - log::info!("💎 AssetRegistryMultilocationToXCMV3: post_upgrade: storage was updated!"); - Ok(()) - } -} - -impl< - T: orml_asset_registry::Config, - AssetsToMigrate, - const EXPECTED_MAINNET_LOC_COUNT: u32, - const EXPECTED_MAINNET_META_COUNT: u32, - const EXPECTED_TESTNET_LOC_COUNT: u32, - const EXPECTED_TESTNET_META_COUNT: u32, - > - Migration< - T, - AssetsToMigrate, - EXPECTED_MAINNET_LOC_COUNT, - EXPECTED_MAINNET_META_COUNT, - EXPECTED_TESTNET_LOC_COUNT, - EXPECTED_TESTNET_META_COUNT, - > -{ - fn get_key_counts() -> (u32, u32) { - // let loc_count = - // orml_asset_registry::LocationToAssetId::::iter_keys().count() as u32; - // let meta_count = orml_asset_registry::Metadata::::iter_keys().count() as - // u32; - let loc_count = Self::count_storage_keys( - orml_asset_registry::LocationToAssetId::::final_prefix().as_ref(), - ); - let meta_count = - Self::count_storage_keys(orml_asset_registry::Metadata::::final_prefix().as_ref()); - - log::info!( - "💎 AssetRegistryMultilocationToXCMV3: Found {} LocationToAssetId keys ", - loc_count - ); - log::info!( - "💎 AssetRegistryMultilocationToXCMV3: Found {} Metadata keys ", - meta_count - ); - - (loc_count, meta_count) - } - - fn check_key_counts(loc_count: u32, meta_count: u32) -> Result<(), &'static str> { - match (loc_count, meta_count) { - (loc, meta) - if (loc, meta) == (EXPECTED_MAINNET_LOC_COUNT, EXPECTED_MAINNET_META_COUNT) => - { - Ok(()) - } - (loc, meta) - if (loc, meta) == (EXPECTED_TESTNET_LOC_COUNT, EXPECTED_TESTNET_META_COUNT) => - { - Ok(()) - } - _ => Err("💎 AssetRegistryMultilocationToXCMV3: Unexpected counters"), - } - } - - pub fn count_storage_keys(prefix: &[u8]) -> u32 { - let mut count = 0; - let mut next_key = prefix.to_vec(); - loop { - match sp_io::storage::next_key(&next_key) { - Some(key) if !key.starts_with(prefix) => break count, - Some(key) => { - next_key = key; - count += 1; - } - None => { - break count; - } - } - } - } -} - -pub trait AssetsToMigrate { - fn get_assets_to_migrate() -> Vec<( - CurrencyId, - orml_asset_registry::AssetMetadata, - )>; -} diff --git a/runtime/common/src/migrations/epoch_execution.rs b/runtime/common/src/migrations/epoch_execution.rs deleted file mode 100644 index 340d9f24dd..0000000000 --- a/runtime/common/src/migrations/epoch_execution.rs +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2023 Centrifuge Foundation (centrifuge.io). -// -// This file is part of the Centrifuge chain project. -// Centrifuge 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 (see http://www.gnu.org/licenses). -// Centrifuge 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. - -use frame_support::traits::{Get, GetStorageVersion, OnRuntimeUpgrade}; -use pallet_order_book::weights::Weight; -use pallet_pool_system::{Config, EpochExecution, EpochExecutionInfo, Nav, Pallet as PoolSystem}; -#[cfg(feature = "try-runtime")] -use parity_scale_codec::{Decode, Encode}; -use sp_runtime::traits::Zero; - -const LOG_PREFIX: &str = "EpochExecutionMigration: "; - -pub(crate) mod v1 { - use frame_support::{ - dispatch::{Decode, Encode, MaxEncodedLen, TypeInfo}, - pallet_prelude::Get, - RuntimeDebug, - }; - use pallet_pool_system::{tranches::EpochExecutionTranches, Config, EpochSolution}; - - #[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] - pub(crate) struct EpochExecutionInfo< - Balance, - BalanceRatio, - EpochId, - Weight, - BlockNumber, - TrancheCurrency, - MaxTranches, - > where - MaxTranches: Get, - { - pub epoch: EpochId, - pub nav: Balance, - pub reserve: Balance, - pub max_reserve: Balance, - pub tranches: - EpochExecutionTranches, - pub best_submission: Option>, - pub challenge_period_end: Option, - } - - pub(crate) type EpochExecutionInfoOf = EpochExecutionInfo< - ::Balance, - ::BalanceRatio, - ::EpochId, - ::TrancheWeight, - ::BlockNumber, - ::TrancheCurrency, - ::MaxTranches, - >; - - #[cfg(feature = "try-runtime")] - #[frame_support::storage_alias] - pub(crate) type EpochExecution = StorageMap< - pallet_pool_system::Pallet, - frame_support::Blake2_128Concat, - ::PoolId, - EpochExecutionInfoOf, - >; -} - -pub struct Migration -where - T: Config + frame_system::Config, -{ - _phantom: sp_std::marker::PhantomData, -} - -impl OnRuntimeUpgrade for Migration -where - T: Config + frame_system::Config, -{ - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { - frame_support::ensure!( - PoolSystem::::on_chain_storage_version() == 1, - "Can only upgrade from PoolSystem version 1" - ); - let count = v1::EpochExecution::::iter().count() as u32; - log::info!( - "{LOG_PREFIX} EpochExecution count pre migration is {}", - count - ); - - Ok(count.encode()) - } - - fn on_runtime_upgrade() -> Weight { - let mut weight = T::DbWeight::get().reads(1); - if PoolSystem::::on_chain_storage_version() != 1 { - log::info!( - "{LOG_PREFIX} Skipping on_runtime_upgrade: executed on wrong storage version. Expected version 1" - ); - return weight; - } - - EpochExecution::::translate::, _>(|_, old| { - weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); - Some(EpochExecutionInfo { - epoch: old.epoch, - nav: Nav::<::Balance>::new(old.nav, ::Balance::zero()), - tranches: old.tranches, - best_submission: old.best_submission, - challenge_period_end: old.challenge_period_end, - }) - }); - - PoolSystem::::current_storage_version().put::>(); - - weight.saturating_add(T::DbWeight::get().writes(1)) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(state: sp_std::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { - frame_support::ensure!( - PoolSystem::::on_chain_storage_version() - == PoolSystem::::current_storage_version(), - "EpochExecutionMigration: StorageVersion of PoolSystem is not 2" - ); - - let old_count: u32 = Decode::decode(&mut &state[..]) - .expect("EpochExecutionMigration: pre_upgrade provides a valid state; qed"); - let new_count = EpochExecution::::iter().count() as u32; - log::info!("{LOG_PREFIX} EpochExecutionV2 count post migration is {new_count}",); - frame_support::ensure!( - old_count == new_count, - "EpochExecutionMigration: Mismatch in pre and post counters, must migrate all EpochExecution values!" - ); - - Ok(()) - } -} diff --git a/runtime/common/src/migrations/local_currency.rs b/runtime/common/src/migrations/local_currency.rs deleted file mode 100644 index 26907eebeb..0000000000 --- a/runtime/common/src/migrations/local_currency.rs +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright 2023 Centrifuge Foundation (centrifuge.io). -// This file is part of Centrifuge chain project. - -// Centrifuge 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 (see http://www.gnu.org/licenses). - -// Centrifuge 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. - -use cfg_types::tokens::{CurrencyId, CustomMetadata}; -use frame_support::{ - traits::{Get, OnRuntimeUpgrade}, - weights::Weight, -}; -use orml_traits::asset_registry::AssetMetadata; -#[cfg(feature = "try-runtime")] -use sp_runtime::DispatchError; -#[cfg(feature = "try-runtime")] -use sp_std::vec; -use sp_std::vec::Vec; - -pub mod register { - use cfg_primitives::Balance; - #[cfg(feature = "try-runtime")] - use cfg_types::tokens::LocalAssetId; - use cfg_types::tokens::{CrossChainTransferability, CurrencyId}; - use orml_traits::asset_registry::Mutate; - - use super::*; - - const LOG_PREFIX: &str = "RegisterLocalCurrency"; - - pub struct Migration(sp_std::marker::PhantomData<(T, LocalCurrency)>); - - impl OnRuntimeUpgrade for Migration - where - T: orml_asset_registry::Config< - CustomMetadata = CustomMetadata, - AssetId = CurrencyId, - Balance = Balance, - >, - LocalCurrency: Get, - { - fn on_runtime_upgrade() -> Weight { - as Mutate>::register_asset( - Some(LocalCurrency::get()), - AssetMetadata { - decimals: 6, - name: "Local USDC".as_bytes().to_vec(), - symbol: "localUSDC".as_bytes().to_vec(), - existential_deposit: 1000u128, - location: None, - additional: CustomMetadata { - transferability: CrossChainTransferability::None, - mintable: false, - permissioned: false, - pool_currency: true, - local_representation: None, - }, - }, - ) - .map_err(|e| { - log::error!( - "{LOG_PREFIX} Failed to register local asset due to error {:?}", - e - ); - }) - .ok(); - - log::info!("{LOG_PREFIX} Done registering local currency"); - - T::DbWeight::get().writes(1) - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, DispatchError> { - assert!(matches!( - LocalCurrency::get(), - CurrencyId::LocalAsset(LocalAssetId(_)) - )); - assert!(!orml_asset_registry::Metadata::::contains_key( - LocalCurrency::get() - )); - - log::info!("{LOG_PREFIX} PRE UPGRADE: Finished"); - - Ok(vec![]) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_: Vec) -> Result<(), DispatchError> { - assert!(orml_asset_registry::Metadata::::contains_key( - LocalCurrency::get() - )); - - log::info!("{LOG_PREFIX} POST UPGRADE: Finished"); - Ok(()) - } - } -} - -pub mod translate_metadata { - use cfg_primitives::Balance; - use cfg_types::tokens::{CrossChainTransferability, LocalAssetId}; - use frame_support::dispatch::{Decode, Encode, MaxEncodedLen, TypeInfo}; - #[cfg(feature = "try-runtime")] - use orml_traits::asset_registry::Inspect; - - use super::*; - - const LOG_PREFIX: &str = "TranslateMetadata"; - - #[derive( - Clone, - Copy, - Default, - PartialOrd, - Ord, - PartialEq, - Eq, - Debug, - Encode, - Decode, - TypeInfo, - MaxEncodedLen, - )] - struct OldCustomMetadata { - pub transferability: CrossChainTransferability, - pub mintable: bool, - pub permissioned: bool, - pub pool_currency: bool, - } - - pub struct Migration(sp_std::marker::PhantomData<(T, AssetList, Local)>); - - impl OnRuntimeUpgrade for Migration - where - T: orml_asset_registry::Config< - CustomMetadata = CustomMetadata, - AssetId = CurrencyId, - Balance = Balance, - >, - AssetList: Get>, - Local: Get, - { - fn on_runtime_upgrade() -> Weight { - let mut weight = Weight::zero(); - orml_asset_registry::Metadata::::translate::< - AssetMetadata, - _, - >(|currency_id, meta| { - weight.saturating_accrue(T::DbWeight::get().writes(1)); - Some(AssetMetadata { - decimals: meta.decimals, - name: meta.name, - symbol: meta.symbol, - existential_deposit: meta.existential_deposit, - location: meta.location, - additional: CustomMetadata { - transferability: meta.additional.transferability, - mintable: meta.additional.mintable, - permissioned: meta.additional.permissioned, - pool_currency: meta.additional.pool_currency, - local_representation: init_local_representation( - currency_id, - AssetList::get(), - Local::get(), - ), - }, - }) - }); - log::info!("{LOG_PREFIX} Done translating asset metadata"); - - weight - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, DispatchError> { - let num_assets = orml_asset_registry::Metadata::::iter_keys().count() as u32; - log::info!( - "{LOG_PREFIX} PRE UPGRADE: Finished with {} registered assets", - num_assets - ); - - Ok(num_assets.encode()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(pre_state: Vec) -> Result<(), DispatchError> { - let n_pre: u32 = Decode::decode(&mut pre_state.as_slice()) - .expect("pre_ugprade provides a valid state; qed"); - let n = orml_asset_registry::Metadata::::iter_keys().count() as u32; - assert_eq!(n_pre, n); - - let local_currency_id: CurrencyId = Local::get().into(); - let local_meta = - as Inspect>::metadata(&local_currency_id) - .expect("Local asset was just registered; qed"); - log::info!("{LOG_PREFIX} CheckAssetIntegrity: Local meta exists"); - - for variant in AssetList::get().into_iter() { - log::info!("{LOG_PREFIX} Checking asset {:?}", variant); - let variant_meta = as Inspect>::metadata(&variant) - .expect("Asset variant is registered; qed"); - assert_eq!(variant_meta.decimals, local_meta.decimals); - assert_eq!( - variant_meta.additional.local_representation, - Some(Local::get()) - ); - } - - log::info!("{LOG_PREFIX} POST UPGRADE: Finished"); - - Ok(()) - } - } - - fn init_local_representation( - currency_id: CurrencyId, - check_list: Vec, - local_asset_id: LocalAssetId, - ) -> Option { - if check_list.iter().any(|c| c == ¤cy_id) { - log::info!( - "{LOG_PREFIX} Set local representation of asset variant {:?}", - currency_id - ); - Some(local_asset_id) - } else { - log::info!( - "{LOG_PREFIX} Skipping setting local representation of asset variant {:?}", - currency_id - ); - None - } - } -} - -pub mod migrate_pool_currency { - use cfg_primitives::{PoolId, TrancheId}; - use cfg_traits::investments::TrancheCurrency as _; - use cfg_types::tokens::TrancheCurrency; - use orml_traits::asset_registry::Inspect; - use sp_runtime::traits::Zero; - - use super::*; - - const LOG_PREFIX: &str = "MigratePoolCurrency"; - - pub struct Migration( - sp_std::marker::PhantomData<(T, TargetPoolId, CurrencyOut, CurrencyIn)>, - ); - - impl OnRuntimeUpgrade - for Migration - where - T: pallet_pool_system::Config< - TrancheId = TrancheId, - PoolId = PoolId, - CurrencyId = CurrencyId, - > + orml_asset_registry::Config - + pallet_investments::Config, - TargetPoolId: Get<::PoolId>, - CurrencyOut: Get, - CurrencyIn: Get, - ::AssetId: From, - ::CurrencyId: From, - { - fn on_runtime_upgrade() -> Weight { - let to = CurrencyIn::get(); - let from = CurrencyOut::get(); - let mut weight = T::DbWeight::get().reads(3); - - match ( - check_local_coupling::(from, to), - has_pending_invest_orders::(TargetPoolId::get()), - ) { - (Some(true), false) => { - pallet_pool_system::Pool::::mutate(TargetPoolId::get(), |maybe_pool| { - if let Some(pool) = maybe_pool { - pool.currency = to; - } - }); - weight.saturating_accrue(T::DbWeight::get().writes(1)); - log::info!("{LOG_PREFIX} Migrated pool currency"); - } - (_, false) => { - log::info!("{LOG_PREFIX} Skipping pool currency migration due to local coupling issues"); - } - (_, true) => { - log::info!("{LOG_PREFIX} Skipping pool currency migration due non-empty active investment orders"); - } - } - - weight - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, DispatchError> { - assert!( - check_local_coupling::(CurrencyOut::get().into(), CurrencyIn::get().into()) - .unwrap() - ); - - let pool = - pallet_pool_system::Pool::::get(TargetPoolId::get()).expect("Pool should exist"); - assert!(pool.currency == CurrencyOut::get().into()); - assert!(!has_pending_invest_orders::(TargetPoolId::get())); - - log::info!("{LOG_PREFIX} PRE UPGRADE: Finished"); - - Ok(vec![]) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_: Vec) -> Result<(), DispatchError> { - let pool = - pallet_pool_system::Pool::::get(TargetPoolId::get()).expect("Pool should exist"); - assert!(pool.currency == CurrencyIn::get().into()); - - log::info!("{LOG_PREFIX} POST UPGRADE: Finished"); - - Ok(()) - } - } - - fn check_local_coupling(from: CurrencyId, to: CurrencyId) -> Option - where - T: pallet_pool_system::Config - + orml_asset_registry::Config, - ::AssetId: From, - { - let to_meta = as Inspect>::metadata(&to); - let from_meta = as Inspect>::metadata(&from); - - match (from_meta, to_meta) { - (Some(meta), Some(_)) => { - let to_currency_id: CurrencyId = meta - .additional - .local_representation - .map(|x| x.try_into().ok())??; - if to_currency_id == to { - Some(true) - } else { - log::error!( - "{LOG_PREFIX} CurrencyOut does not have CurrencyIn set as local currency" - ); - Some(false) - } - } - (Some(_), None) => { - log::error!("{LOG_PREFIX} CurrencyIn is not registered"); - None - } - _ => { - log::error!("{LOG_PREFIX} CurrencyOut is not registered"); - None - } - } - } - - fn has_pending_invest_orders(pool_id: PoolId) -> bool - where - T: pallet_investments::Config, - T: pallet_pool_system::Config< - PoolId = PoolId, - TrancheId = TrancheId, - CurrencyId = CurrencyId, - >, - { - if let Some(t) = pallet_pool_system::Pool::::get(pool_id) { - t.tranches.ids.into_iter().any(|tranche_id| { - !pallet_investments::ActiveInvestOrders::::get(TrancheCurrency::generate( - pool_id, tranche_id, - )) - .amount - .is_zero() - }) - } else { - false - } - } -} diff --git a/runtime/common/src/migrations/mod.rs b/runtime/common/src/migrations/mod.rs index e1919f42a8..6d331c0302 100644 --- a/runtime/common/src/migrations/mod.rs +++ b/runtime/common/src/migrations/mod.rs @@ -12,165 +12,6 @@ //! Centrifuge Runtime-Common Migrations -pub mod asset_registry_xcmv3; -pub mod epoch_execution; pub mod increase_storage_version; -pub mod local_currency; pub mod nuke; -pub mod orml_tokens; pub mod precompile_account_codes; -pub mod transfer_allowlist_currency; - -pub mod update_celo_usdcs { - use cfg_primitives::Balance; - use cfg_types::tokens::{ - usdc::{CURRENCY_ID_LP_CELO, CURRENCY_ID_LP_CELO_WORMHOLE}, - CrossChainTransferability, CurrencyId, CustomMetadata, - }; - use frame_support::{traits::OnRuntimeUpgrade, weights::Weight}; - use hex_literal::hex; - use orml_traits::asset_registry::{AssetMetadata, Mutate}; - use sp_runtime::traits::Get; - #[cfg(feature = "try-runtime")] - use sp_std::{vec, vec::Vec}; - use xcm::v3::{ - Junction::{AccountKey20, GlobalConsensus, PalletInstance}, - Junctions::X3, - NetworkId::Ethereum, - }; - - const LOG_PREFIX_ADD: &str = "AddNewCeloUsdc"; - const LOG_PREFIX_UPDATE: &str = "UpdateCeloWormholeUsdc"; - - pub struct AddNewCeloUsdc(sp_std::marker::PhantomData); - - impl OnRuntimeUpgrade for AddNewCeloUsdc - where - T: orml_asset_registry::Config< - CustomMetadata = CustomMetadata, - AssetId = CurrencyId, - Balance = Balance, - >, - { - fn on_runtime_upgrade() -> Weight { - as Mutate>::register_asset( - Some(CURRENCY_ID_LP_CELO), - AssetMetadata { - decimals: 6, - name: "LP Celo Wrapped USDC ".as_bytes().to_vec(), - symbol: "LpCeloUSDC".as_bytes().to_vec(), - existential_deposit: 1000u128, - location: Some( - X3( - PalletInstance(103), - GlobalConsensus(Ethereum { chain_id: 42220 }), - AccountKey20 { - // https://www.circle.com/blog/usdc-now-available-on-celo - key: hex!("cebA9300f2b948710d2653dD7B07f33A8B32118C"), - network: None, - }, - ) - .into(), - ), - additional: CustomMetadata { - transferability: CrossChainTransferability::LiquidityPools, - mintable: false, - permissioned: false, - pool_currency: true, - local_representation: None, - }, - }, - ) - .map_err(|e| { - log::error!( - "{LOG_PREFIX_ADD} Failed to register new canonical Celo USDC due to error {:?}", - e - ); - }) - .ok(); - - log::info!("{LOG_PREFIX_ADD} Done registering new canonical Celo USDC currency"); - - T::DbWeight::get().writes(1) - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::DispatchError> { - assert!(!orml_asset_registry::Metadata::::contains_key( - CURRENCY_ID_LP_CELO - )); - - log::info!("{LOG_PREFIX_ADD} PRE UPGRADE: Finished"); - - Ok(vec![]) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_: Vec) -> Result<(), sp_runtime::DispatchError> { - assert!(orml_asset_registry::Metadata::::contains_key( - CURRENCY_ID_LP_CELO - )); - - log::info!("{LOG_PREFIX_ADD} POST UPGRADE: Finished"); - Ok(()) - } - } - - pub struct UpdateWormholeUsdc(sp_std::marker::PhantomData); - - impl OnRuntimeUpgrade for UpdateWormholeUsdc - where - T: orml_asset_registry::Config< - CustomMetadata = CustomMetadata, - AssetId = CurrencyId, - Balance = Balance, - >, - { - fn on_runtime_upgrade() -> Weight { - as Mutate>::update_asset( - CURRENCY_ID_LP_CELO_WORMHOLE, - None, - Some("LP Celo Wrapped Wormhole USDC ".as_bytes().to_vec()), - Some("LpCeloWormUSDC ".as_bytes().to_vec()), - None, - None, - None, - ) - .map_err(|e| { - log::error!( - "{LOG_PREFIX_UPDATE} Failed to update wormhole Celo USDC due to error {:?}", - e - ); - }) - .ok(); - - log::info!("{LOG_PREFIX_UPDATE} Done updating wormhole Celo USDC currency"); - - T::DbWeight::get().writes(1) - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::DispatchError> { - assert!(orml_asset_registry::Metadata::::contains_key( - CURRENCY_ID_LP_CELO_WORMHOLE - )); - - log::info!("{LOG_PREFIX_UPDATE} PRE UPGRADE: Finished"); - - Ok(vec![]) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_: Vec) -> Result<(), sp_runtime::DispatchError> { - assert_eq!( - orml_asset_registry::Metadata::::get(CURRENCY_ID_LP_CELO_WORMHOLE) - .expect("Wormhole Celo USDC exists; qed") - .name, - "LP Celo Wrapped Wormhole USDC ".as_bytes().to_vec() - ); - - log::info!("{LOG_PREFIX_UPDATE} POST UPGRADE: Finished"); - Ok(()) - } - } -} diff --git a/runtime/common/src/migrations/orml_tokens.rs b/runtime/common/src/migrations/orml_tokens.rs deleted file mode 100644 index 6ef6485250..0000000000 --- a/runtime/common/src/migrations/orml_tokens.rs +++ /dev/null @@ -1,5 +0,0 @@ -use frame_support::traits::OnRuntimeUpgrade; - -pub struct Migration(sp_std::marker::PhantomData); - -impl OnRuntimeUpgrade for Migration where T: orml_tokens::Config + frame_system::Config {} diff --git a/runtime/common/src/migrations/transfer_allowlist_currency.rs b/runtime/common/src/migrations/transfer_allowlist_currency.rs deleted file mode 100644 index ff7fca6e79..0000000000 --- a/runtime/common/src/migrations/transfer_allowlist_currency.rs +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2023 Centrifuge Foundation (centrifuge.io). -// This file is part of Centrifuge chain project. - -// Centrifuge 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 (see http://www.gnu.org/licenses). - -// Centrifuge 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. - -use cfg_primitives::{AccountId, BlockNumber}; -use cfg_types::{ - locations::Location, - tokens::{CurrencyId, FilterCurrency}, -}; -use frame_support::{ - dispatch::GetStorageVersion, - pallet_prelude::{NMapKey, OptionQuery}, - storage::types::{StorageDoubleMap, StorageNMap}, - traits::{Get, OnRuntimeUpgrade, StorageInstance}, - weights::Weight, - Blake2_128Concat, Twox64Concat, -}; -use pallet_transfer_allowlist::{AllowanceDetails, AllowanceMetadata}; -#[cfg(feature = "try-runtime")] -use parity_scale_codec::{Decode, Encode}; -#[cfg(feature = "try-runtime")] -use sp_runtime::DispatchError; - -const LOG_PREFIX: &str = "TransferAllowlist-CurrencyMigration: "; - -struct DelayPrefix; -impl StorageInstance for DelayPrefix { - const STORAGE_PREFIX: &'static str = "AccountCurrencyTransferCountDelay"; - - fn pallet_prefix() -> &'static str { - "TransferAllowList" - } -} -type OldAccountCurrencyTransferCountDelay = StorageDoubleMap< - DelayPrefix, - Twox64Concat, - AccountId, - Twox64Concat, - CurrencyId, - AllowanceMetadata, - OptionQuery, ->; - -struct AllowancePrefix; -impl StorageInstance for AllowancePrefix { - const STORAGE_PREFIX: &'static str = "AccountCurrencyTransferAllowance"; - - fn pallet_prefix() -> &'static str { - "TransferAllowList" - } -} -type OldAccountCurrencyTransferAllowance = StorageNMap< - AllowancePrefix, - ( - NMapKey, - NMapKey, - NMapKey, - ), - AllowanceDetails, - OptionQuery, ->; - -pub struct Migration(sp_std::marker::PhantomData); -impl< - T: pallet_transfer_allowlist::Config< - AccountId = AccountId, - Location = Location, - CurrencyId = FilterCurrency, - BlockNumber = BlockNumber, - >, - > OnRuntimeUpgrade for Migration -{ - fn on_runtime_upgrade() -> Weight { - let weight = T::DbWeight::get().reads(1); - if pallet_transfer_allowlist::Pallet::::on_chain_storage_version() != 0 { - log::info!( - "{LOG_PREFIX} Skipping on_runtime_upgrade: executed on wrong storage version. Expected version 0" - ); - return weight; - } - - log::info!("{LOG_PREFIX} Migrating allowlist storage keys started..."); - - let mut counter = 0; - OldAccountCurrencyTransferAllowance::translate::, _>( - |(account, currency_id, location), allowance| { - pallet_transfer_allowlist::AccountCurrencyTransferAllowance::::insert( - (account, FilterCurrency::Specific(currency_id), location), - allowance, - ); - - counter += 1; - // We will remove the storage here, as we are inserting the new storage above - None - }, - ); - - OldAccountCurrencyTransferCountDelay::translate::, _>( - |account, currency_id, delay| { - pallet_transfer_allowlist::AccountCurrencyTransferCountDelay::::insert( - account, - FilterCurrency::Specific(currency_id), - delay, - ); - - counter += 1; - // We will remove the storage here, as we are inserting the new storage above - None - }, - ); - - pallet_transfer_allowlist::STORAGE_VERSION.put::>(); - - log::info!("{LOG_PREFIX} Migrating allowlist storage keys finished."); - - weight.saturating_add(T::DbWeight::get().reads_writes(counter, counter.saturating_mul(2))) - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, DispatchError> { - log::info!("{LOG_PREFIX} PRE UPGRADE: Starting..."); - - let count_allowance = OldAccountCurrencyTransferAllowance::iter().count() as u64; - log::info!("{LOG_PREFIX} Counted {count_allowance} keys in old allowance storage."); - - let count_delay = OldAccountCurrencyTransferCountDelay::iter().count() as u64; - log::info!("{LOG_PREFIX} Counted {count_delay} keys in old delay storage."); - - log::info!("{LOG_PREFIX} PRE UPGRADE: Finished."); - Ok((count_allowance, count_delay).encode()) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(state: sp_std::vec::Vec) -> Result<(), DispatchError> { - log::info!("{LOG_PREFIX} POST UPGRADE: Starting..."); - let (count_allowance_pre, count_delay_pre): (u64, u64) = - Decode::decode(&mut state.as_slice()) - .map_err(|_| DispatchError::Other("{LOG_PREFIX} Failed decoding state."))?; - - let count_allowance_after = - pallet_transfer_allowlist::AccountCurrencyTransferCountDelay::::iter().count() - as u64; - - if count_allowance_after != count_allowance_pre { - log::error!("{LOG_PREFIX} Delay migration failed. Got: {count_allowance_after}, Expected: {count_allowance_pre}"); - } - - let count_delay_after = - pallet_transfer_allowlist::AccountCurrencyTransferCountDelay::::iter().count() - as u64; - - if count_delay_after != count_delay_pre { - log::error!("{LOG_PREFIX} Delay migration failed. Got: {count_delay_after}, Expected: {count_delay_pre}"); - } - - log::info!("{LOG_PREFIX} POST UPGRADE: Finished."); - - Ok(()) - } -} diff --git a/runtime/development/Cargo.toml b/runtime/development/Cargo.toml index 05dff3db18..d87175cc6b 100644 --- a/runtime/development/Cargo.toml +++ b/runtime/development/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "development-runtime" -version = "0.10.43" +version = "0.10.44" build = "build.rs" authors.workspace = true edition.workspace = true diff --git a/runtime/development/src/lib.rs b/runtime/development/src/lib.rs index cc86650c13..649897708f 100644 --- a/runtime/development/src/lib.rs +++ b/runtime/development/src/lib.rs @@ -157,7 +157,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("centrifuge-devel"), impl_name: create_runtime_str!("centrifuge-devel"), authoring_version: 1, - spec_version: 1043, + spec_version: 1044, impl_version: 1, #[cfg(not(feature = "disable-runtime-api"))] apis: RUNTIME_API_VERSIONS, @@ -2042,7 +2042,7 @@ pub type Executive = frame_executive::Executive< frame_system::ChainContext, Runtime, AllPalletsWithSystem, - crate::migrations::UpgradeDevelopment1043, + crate::migrations::UpgradeDevelopment1044, >; // Frame Order in this block dictates the index of each one in the metadata diff --git a/runtime/development/src/migrations.rs b/runtime/development/src/migrations.rs index fff72d8738..2fd798b2c3 100644 --- a/runtime/development/src/migrations.rs +++ b/runtime/development/src/migrations.rs @@ -10,5 +10,6 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -pub type UpgradeDevelopment1043 = - (runtime_common::migrations::increase_storage_version::ForceMigration,); +/// The migration set for Development & Demo. +/// It includes all the migrations that have to be applied on that chain. +pub type UpgradeDevelopment1044 = ();