From e12f4400a6af89d347c2ee5895bf4dcb8ca43e72 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Mon, 9 Dec 2024 17:43:46 -0300 Subject: [PATCH 01/41] add basics for foreign asset creation via token reserve WIP --- pallets/moonbeam-foreign-assets/src/lib.rs | 69 ++++++++++++++++++-- pallets/moonbeam-foreign-assets/src/mock.rs | 11 ++++ pallets/moonbeam-foreign-assets/src/tests.rs | 25 +++++-- runtime/moonbase/src/xcm_config.rs | 19 ++++-- runtime/moonbeam/src/xcm_config.rs | 12 +++- runtime/moonriver/src/lib.rs | 2 +- runtime/moonriver/src/xcm_config.rs | 20 +++--- 7 files changed, 130 insertions(+), 28 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index 1d92d8facd..d40a6eb4fb 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -108,10 +108,11 @@ pub enum AssetStatus { pub mod pallet { use super::*; use pallet_evm::{GasWeightMapping, Runner}; - use sp_runtime::traits::{AccountIdConversion, Convert}; + use sp_runtime::traits::{AccountIdConversion, AtLeast32BitUnsigned, BlockNumber, Convert}; use xcm_executor::traits::ConvertLocation; use xcm_executor::traits::Error as MatchError; use xcm_executor::AssetsInHolding; + use frame_support::traits::{Currency, ReservableCurrency}; #[pallet::pallet] #[pallet::without_storage_info] @@ -147,7 +148,7 @@ pub mod pallet { /// Hook to be called when new foreign asset is registered. type OnForeignAssetCreated: ForeignAssetCreatedHook; - /// Maximum nulmbers of differnt foreign assets + /// Maximum numbers of differnt foreign assets type MaxForeignAssets: Get; /// The overarching event type. @@ -158,8 +159,30 @@ pub mod pallet { // Convert XCM Location to H160 type XcmLocationToH160: ConvertLocation; + + /// Amount of tokens required to lock for creating a new foreign asset + type ForeignAssetDeposit: Get>; + + /// The block number type for the pallet + type BlockNumber: BlockNumber; + + /// The balance type for locking funds + type Balance: Member + + Parameter + + AtLeast32BitUnsigned + + Default + + Copy + + MaybeSerializeDeserialize + + MaxEncodedLen + + TypeInfo; + + /// The currency type for locking funds + type Currency: ReservableCurrency; } + type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; + pub type AssetBalance = U256; pub type AssetId = u128; @@ -177,6 +200,8 @@ pub mod pallet { EvmCallPauseFail, EvmCallUnpauseFail, EvmInternalError, + /// Account has insufficient balance for locking + InsufficientBalance, InvalidSymbol, InvalidTokenName, LocationAlreadyExists, @@ -191,6 +216,7 @@ pub mod pallet { contract_address: H160, asset_id: AssetId, xcm_location: Location, + deposit: BalanceOf }, /// Changed the xcm type mapping for a given asset id ForeignAssetXcmLocationChanged { @@ -207,6 +233,10 @@ pub mod pallet { asset_id: AssetId, xcm_location: Location, }, + /// Tokens have been locked for asset creation + TokensLocked(T::AccountId, AssetId, AssetBalance), + /// Lock verification failed + LockVerificationFailed(T::AccountId, AssetId), } /// Mapping from an asset id to a Foreign asset type. @@ -225,6 +255,22 @@ pub mod pallet { pub type AssetsByLocation = StorageMap<_, Blake2_128Concat, Location, (AssetId, AssetStatus)>; + /// Mapping from an asset id to it's details information + #[pallet::storage] + #[pallet::getter(fn assets_creation_details)] + pub type AssetsCreationDetails = StorageMap< + _, + Blake2_128Concat, + AssetId, + AssetCreationDetails> + >; + + #[derive(Clone, Copy, Decode, Encode, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)] + pub struct AssetCreationDetails { + pub creator: AccountId, + pub deposit: Balance + } + impl Pallet { /// The account ID of this pallet #[inline] @@ -279,13 +325,13 @@ pub mod pallet { // Insert the association foreigAsset->assetId AssetsById::::insert(&asset_id, &xcm_location); AssetsByLocation::::insert(&xcm_location, (asset_id, AssetStatus::Active)); - - T::OnForeignAssetCreated::on_asset_created(&xcm_location, &asset_id); + let deposit = T::ForeignAssetDeposit::get(); Self::deposit_event(Event::ForeignAssetCreated { contract_address, asset_id, xcm_location, + deposit }); Ok(()) } @@ -355,7 +401,7 @@ pub mod pallet { symbol: BoundedVec>, name: BoundedVec>, ) -> DispatchResult { - T::ForeignAssetCreatorOrigin::ensure_origin(origin)?; + T::ForeignAssetCreatorOrigin::ensure_origin(origin.clone())?; // Ensure such an assetId does not exist ensure!( @@ -380,20 +426,31 @@ pub mod pallet { let symbol = core::str::from_utf8(&symbol).map_err(|_| Error::::InvalidSymbol)?; let name = core::str::from_utf8(&name).map_err(|_| Error::::InvalidTokenName)?; - + let creator = ensure_signed(origin)?; let contract_address = EvmCaller::::erc20_create(asset_id, decimals, symbol, name)?; + let deposit = T::ForeignAssetDeposit::get(); // Insert the association assetId->foreigAsset // Insert the association foreigAsset->assetId AssetsById::::insert(&asset_id, &xcm_location); AssetsByLocation::::insert(&xcm_location, (asset_id, AssetStatus::Active)); + // Reserve _deposit_ amount of funds from the caller + ::Currency::reserve(&creator, deposit)?; + + // Insert the amount that is reserved from the user + AssetsCreationDetails::::insert(&asset_id, AssetCreationDetails { + creator, + deposit + }); + T::OnForeignAssetCreated::on_asset_created(&xcm_location, &asset_id); Self::deposit_event(Event::ForeignAssetCreated { contract_address, asset_id, xcm_location, + deposit }); Ok(()) } diff --git a/pallets/moonbeam-foreign-assets/src/mock.rs b/pallets/moonbeam-foreign-assets/src/mock.rs index 4f81769a24..60eddbecac 100644 --- a/pallets/moonbeam-foreign-assets/src/mock.rs +++ b/pallets/moonbeam-foreign-assets/src/mock.rs @@ -29,6 +29,7 @@ use xcm::latest::Location; pub type Balance = u128; +pub type BlockNumber = u32; type AccountId = MockAccount; type Block = frame_system::mocking::MockBlock; @@ -175,6 +176,10 @@ impl sp_runtime::traits::Convert for AccountIdToH160 { } } +parameter_types! { + pub const ForeignAssetDeposit: u64 = 1; +} + impl crate::Config for Test { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = Everything; @@ -188,6 +193,12 @@ impl crate::Config for Test { type RuntimeEvent = RuntimeEvent; type WeightInfo = (); type XcmLocationToH160 = (); + type ForeignAssetDeposit = (); + type BlockNumber = BlockNumber; + type Balance = Balance; + + type Currency = Balances; + } pub(crate) struct ExtBuilder { diff --git a/pallets/moonbeam-foreign-assets/src/tests.rs b/pallets/moonbeam-foreign-assets/src/tests.rs index ee7689f17b..32d1394a50 100644 --- a/pallets/moonbeam-foreign-assets/src/tests.rs +++ b/pallets/moonbeam-foreign-assets/src/tests.rs @@ -18,7 +18,7 @@ use crate::*; use mock::*; use frame_support::{assert_noop, assert_ok}; -use precompile_utils::testing::Bob; +use precompile_utils::testing::{Alice, Bob}; use xcm::latest::prelude::*; fn encode_ticker(str_: &str) -> BoundedVec> { @@ -34,7 +34,7 @@ fn create_foreign_and_freeze_unfreeze() { ExtBuilder::default().build().execute_with(|| { // create foreign asset assert_ok!(EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::root(), + RuntimeOrigin::from(Some(Alice.into())), 1, Location::parent(), 18, @@ -47,12 +47,22 @@ fn create_foreign_and_freeze_unfreeze() { EvmForeignAssets::assets_by_location(Location::parent()), Some((1, AssetStatus::Active)), ); + assert_eq!( + EvmForeignAssets::assets_by_location(Location::parent()), + Some((1, AssetStatus::Active)), + ); + assert_eq!( + EvmForeignAssets::assets_creation_details(&1), + Some(AssetCreationDetails { creator: Alice.into(), deposit: 1}) + ); + expect_events(vec![crate::Event::ForeignAssetCreated { contract_address: H160([ 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ]), asset_id: 1, xcm_location: Location::parent(), + deposit: 1, }]); let (xcm_location, asset_id): (Location, u128) = get_asset_created_hook_invocation() @@ -66,6 +76,10 @@ fn create_foreign_and_freeze_unfreeze() { EvmForeignAssets::assets_by_location(&Location::parent()), Some((1, AssetStatus::Active)) ); + assert_eq!( + EvmForeignAssets::assets_creation_details(&1), + Some(AssetCreationDetails { creator: Alice.into(), deposit: 1}) + ); // Unfreeze should return AssetNotFrozen error assert_noop!( @@ -192,6 +206,7 @@ fn test_root_can_change_foreign_asset_for_asset_id() { ]), asset_id: 1, xcm_location: Location::parent(), + deposit: 1 }, crate::Event::ForeignAssetXcmLocationChanged { asset_id: 1, @@ -216,7 +231,7 @@ fn test_location_already_exist_error() { ExtBuilder::default().build().execute_with(|| { // Setup: create a first foreign asset taht we will try to override assert_ok!(EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::root(), + RuntimeOrigin::from(Some(Alice.into())), 1, Location::parent(), 18, @@ -226,7 +241,7 @@ fn test_location_already_exist_error() { assert_noop!( EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::root(), + RuntimeOrigin::from(Some(Alice.into())), 2, Location::parent(), 18, @@ -238,7 +253,7 @@ fn test_location_already_exist_error() { // Setup: create a second foreign asset that will try to override the first one assert_ok!(EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::root(), + RuntimeOrigin::from(Some(Alice.into())), 2, Location::new(2, *&[]), 18, diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index d556e4a8e1..878e7886c0 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -58,6 +58,7 @@ use xcm::latest::prelude::{ use xcm_executor::traits::{CallDispatcher, ConvertLocation, JustTry}; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; +use parachains_common::BlockNumber; use xcm_primitives::{ AbsoluteAndRelativeReserve, AccountIdToCurrencyId, AccountIdToLocation, AsAssetType, IsBridgedConcreteAssetFrom, MultiNativeAsset, SignedToAccountId20, UtilityAvailableCalls, @@ -695,13 +696,13 @@ impl frame_support::traits::Contains for EvmForeignAssetIdFilter { } } -pub type ForeignAssetManagerOrigin = EitherOfDiverse< - EnsureRoot, - EitherOfDiverse< - pallet_collective::EnsureProportionMoreThan, - governance::custom_origins::FastGeneralAdmin, - >, ->; +parameter_types! { + /// Balance in the native currency that will be reserved from the user + /// to create a new foreign asset + pub ForeignAssetDeposit: u64 = 100; +} + +pub type ForeignAssetManagerOrigin = frame_system::EnsureSigned; impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; @@ -716,6 +717,10 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = moonbase_weights::pallet_moonbeam_foreign_assets::WeightInfo; type XcmLocationToH160 = LocationToH160; + type ForeignAssetDeposit = ForeignAssetDeposit; + type BlockNumber = BlockNumber; + type Currency = Balances; + type Balance = Balance; } pub struct AssetFeesFilter; diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index f9a01b255e..30685419be 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -71,7 +71,7 @@ use sp_std::{ convert::{From, Into, TryFrom}, prelude::*, }; - +use moonbeam_core_primitives::BlockNumber; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; parameter_types! { @@ -689,6 +689,12 @@ pub type ForeignAssetManagerOrigin = EitherOfDiverse< >, >; +parameter_types! { + /// Balance in the native currency that will be reserved from the user + /// to create a new foreign asset + pub ForeignAssetDeposit: u64 = 100; +} + impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; @@ -702,6 +708,10 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = moonbeam_weights::pallet_moonbeam_foreign_assets::WeightInfo; type XcmLocationToH160 = LocationToH160; + type ForeignAssetDeposit = ForeignAssetDeposit; + type BlockNumber = BlockNumber; + type Currency = Balances; + type Balance = Balance; } pub struct AssetFeesFilter; diff --git a/runtime/moonriver/src/lib.rs b/runtime/moonriver/src/lib.rs index 5fc1def9d3..00faf1fb5c 100644 --- a/runtime/moonriver/src/lib.rs +++ b/runtime/moonriver/src/lib.rs @@ -328,7 +328,7 @@ impl pallet_balances::Config for Runtime { type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; + type MaxFreezes = ConstU32<50>; type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type WeightInfo = moonriver_weights::pallet_balances::WeightInfo; diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index bdaa8da76b..4a0898de9c 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -71,7 +71,7 @@ use sp_std::{ convert::{From, Into, TryFrom}, prelude::*, }; - +use moonbeam_core_primitives::BlockNumber; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; parameter_types! { @@ -694,13 +694,13 @@ impl frame_support::traits::Contains for EvmForeignAssetIdFilter { } } -pub type ForeignAssetManagerOrigin = EitherOfDiverse< - EnsureRoot, - EitherOfDiverse< - pallet_collective::EnsureProportionMoreThan, - governance::custom_origins::FastGeneralAdmin, - >, ->; +parameter_types! { + /// Balance in the native currency that will be reserved from the user + /// to create a new foreign asset + pub ForeignAssetDeposit: u64 = 100; +} + +pub type ForeignAssetManagerOrigin = frame_system::EnsureSigned; impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; @@ -715,6 +715,10 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = moonriver_weights::pallet_moonbeam_foreign_assets::WeightInfo; type XcmLocationToH160 = LocationToH160; + type ForeignAssetDeposit = ForeignAssetDeposit; + type BlockNumber = BlockNumber; + type Currency = Balances; + type Balance = Balance; } pub struct AssetFeesFilter; From 31616cdb1c400cfe27c1a0278b64adc8ad929201 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Thu, 12 Dec 2024 19:55:37 -0300 Subject: [PATCH 02/41] create new extrinsic for the new way of creating foreign assets --- pallets/moonbeam-foreign-assets/src/lib.rs | 74 ++++++++++++++++++++-- 1 file changed, 67 insertions(+), 7 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index d40a6eb4fb..05ec3e4fe5 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -426,9 +426,10 @@ pub mod pallet { let symbol = core::str::from_utf8(&symbol).map_err(|_| Error::::InvalidSymbol)?; let name = core::str::from_utf8(&name).map_err(|_| Error::::InvalidTokenName)?; - let creator = ensure_signed(origin)?; + let owner_account = ensure_signed(origin)?; let contract_address = EvmCaller::::erc20_create(asset_id, decimals, symbol, name)?; let deposit = T::ForeignAssetDeposit::get(); + let owner = AssetOwner::::Account(owner_account.clone()); // Insert the association assetId->foreigAsset // Insert the association foreigAsset->assetId @@ -436,13 +437,10 @@ pub mod pallet { AssetsByLocation::::insert(&xcm_location, (asset_id, AssetStatus::Active)); // Reserve _deposit_ amount of funds from the caller - ::Currency::reserve(&creator, deposit)?; + ::Currency::reserve(&owner_account, deposit)?; // Insert the amount that is reserved from the user - AssetsCreationDetails::::insert(&asset_id, AssetCreationDetails { - creator, - deposit - }); + AssetsCreationDetails::::insert(&asset_id, AssetCreationDetails { owner, deposit }); T::OnForeignAssetCreated::on_asset_created(&xcm_location, &asset_id); @@ -450,7 +448,7 @@ pub mod pallet { contract_address, asset_id, xcm_location, - deposit + deposit, }); Ok(()) } @@ -556,6 +554,68 @@ pub mod pallet { }); Ok(()) } + + #[pallet::call_index(4)] + #[pallet::weight(::WeightInfo::create_foreign_asset_reserve())] + pub fn create_foreign_asset_reserve( + origin: OriginFor, + asset_id: AssetId, + xcm_location: Location, + decimals: u8, + symbol: BoundedVec>, + name: BoundedVec>, + ) -> DispatchResult { + let owner_account = ensure_signed(origin)?; + + // Ensure such an assetId does not exist + ensure!( + !AssetsById::::contains_key(&asset_id), + Error::::AssetAlreadyExists + ); + + ensure!( + !AssetsByLocation::::contains_key(&xcm_location), + Error::::LocationAlreadyExists + ); + + ensure!( + AssetsById::::count() < T::MaxForeignAssets::get(), + Error::::TooManyForeignAssets + ); + + ensure!( + T::AssetIdFilter::contains(&asset_id), + Error::::AssetIdFiltered + ); + + let symbol = core::str::from_utf8(&symbol).map_err(|_| Error::::InvalidSymbol)?; + let name = core::str::from_utf8(&name).map_err(|_| Error::::InvalidTokenName)?; + let contract_address = + crate::evm::EvmCaller::::erc20_create(asset_id, decimals, symbol, name)?; + let deposit = T::ForeignAssetDeposit::get(); + let owner = AssetOwner::::Account(owner_account.clone()); + + // Insert the association assetId->foreigAsset + // Insert the association foreigAsset->assetId + AssetsById::::insert(&asset_id, &xcm_location); + AssetsByLocation::::insert(&xcm_location, (asset_id, crate::AssetStatus::Active)); + + // Reserve _deposit_ amount of funds from the caller + ::Currency::reserve(&owner_account, deposit)?; + + // Insert the amount that is reserved from the user + AssetsCreationDetails::::insert(&asset_id, AssetCreationDetails { owner, deposit }); + + T::OnForeignAssetCreated::on_asset_created(&xcm_location, &asset_id); + + Self::deposit_event(Event::ForeignAssetCreated { + contract_address, + asset_id, + xcm_location, + deposit, + }); + Ok(()) + } } impl xcm_executor::traits::TransactAsset for Pallet { From a50448e17618c6ed43ea8a1a1c612e61498c9d24 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Thu, 12 Dec 2024 19:56:07 -0300 Subject: [PATCH 03/41] ensure the modifier is the owner of the asset (migration needed) --- pallets/moonbeam-foreign-assets/src/lib.rs | 64 +++++++++++++++------- 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index 05ec3e4fe5..2375f9c028 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -107,12 +107,12 @@ pub enum AssetStatus { #[pallet] pub mod pallet { use super::*; + use frame_support::traits::{Currency, ReservableCurrency}; use pallet_evm::{GasWeightMapping, Runner}; use sp_runtime::traits::{AccountIdConversion, AtLeast32BitUnsigned, BlockNumber, Convert}; use xcm_executor::traits::ConvertLocation; use xcm_executor::traits::Error as MatchError; use xcm_executor::AssetsInHolding; - use frame_support::traits::{Currency, ReservableCurrency}; #[pallet::pallet] #[pallet::without_storage_info] @@ -122,7 +122,7 @@ pub mod pallet { pub const PALLET_ID: frame_support::PalletId = frame_support::PalletId(*b"forgasst"); #[pallet::config] - pub trait Config: frame_system::Config + pallet_evm::Config { + pub trait Config: frame_system::Config + pallet_evm::Config + scale_info::TypeInfo { // Convert AccountId to H160 type AccountIdToH160: Convert; @@ -202,6 +202,7 @@ pub mod pallet { EvmInternalError, /// Account has insufficient balance for locking InsufficientBalance, + OriginIsNotAssetCreator, InvalidSymbol, InvalidTokenName, LocationAlreadyExists, @@ -216,7 +217,7 @@ pub mod pallet { contract_address: H160, asset_id: AssetId, xcm_location: Location, - deposit: BalanceOf + deposit: BalanceOf, }, /// Changed the xcm type mapping for a given asset id ForeignAssetXcmLocationChanged { @@ -255,20 +256,23 @@ pub mod pallet { pub type AssetsByLocation = StorageMap<_, Blake2_128Concat, Location, (AssetId, AssetStatus)>; - /// Mapping from an asset id to it's details information + /// Mapping from an asset id to its creation details #[pallet::storage] #[pallet::getter(fn assets_creation_details)] - pub type AssetsCreationDetails = StorageMap< - _, - Blake2_128Concat, - AssetId, - AssetCreationDetails> - >; - - #[derive(Clone, Copy, Decode, Encode, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)] - pub struct AssetCreationDetails { - pub creator: AccountId, - pub deposit: Balance + pub type AssetsCreationDetails = + StorageMap<_, Blake2_128Concat, AssetId, AssetCreationDetails>; + + #[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] + pub enum AssetOwner { + Governance, + Root, + Account(T::AccountId), + } + + #[derive(Clone, Decode, Encode, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)] + pub struct AssetCreationDetails { + pub owner: AssetOwner, + pub deposit: BalanceOf, } impl Pallet { @@ -331,7 +335,7 @@ pub mod pallet { contract_address, asset_id, xcm_location, - deposit + deposit, }); Ok(()) } @@ -386,6 +390,28 @@ pub mod pallet { AssetsByLocation::::insert(&asset_location, (asset_id, AssetStatus::Active)); AssetsById::::insert(&asset_id, asset_location); } + + /// Ensures that the origin has the required permissions to modifiy an asset + fn ensure_asset_owner(origin: OriginFor, asset_id: AssetId) -> DispatchResult { + let asset_details = AssetsCreationDetails::::get(&asset_id); + let caller = ensure_signed(origin.clone())?; + + match asset_details { + Some(data) => match data.owner { + AssetOwner::Account(account) => { + ensure!(account == caller, Error::::OriginIsNotAssetCreator); + } + AssetOwner::Governance | AssetOwner::Root => { + ::ForeignAssetFreezerOrigin::ensure_origin(origin)?; + } + }, + None => { + ::ForeignAssetFreezerOrigin::ensure_origin(origin)?; + } + } + + Ok(()) + } } #[pallet::call] @@ -463,7 +489,7 @@ pub mod pallet { asset_id: AssetId, new_xcm_location: Location, ) -> DispatchResult { - T::ForeignAssetModifierOrigin::ensure_origin(origin)?; + Self::ensure_asset_owner(origin.clone(), asset_id)?; let previous_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; @@ -496,7 +522,7 @@ pub mod pallet { asset_id: AssetId, allow_xcm_deposit: bool, ) -> DispatchResult { - T::ForeignAssetFreezerOrigin::ensure_origin(origin)?; + Self::ensure_asset_owner(origin.clone(), asset_id)?; let xcm_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; @@ -530,7 +556,7 @@ pub mod pallet { #[pallet::call_index(3)] #[pallet::weight(::WeightInfo::unfreeze_foreign_asset())] pub fn unfreeze_foreign_asset(origin: OriginFor, asset_id: AssetId) -> DispatchResult { - T::ForeignAssetUnfreezerOrigin::ensure_origin(origin)?; + Self::ensure_asset_owner(origin.clone(), asset_id)?; let xcm_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; From 942bf9c1d35498ed4d4bcbb5115a96427259457e Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Thu, 12 Dec 2024 19:57:39 -0300 Subject: [PATCH 04/41] add default weights --- pallets/moonbeam-foreign-assets/src/weights.rs | 10 ++++++++++ .../src/weights/pallet_moonbeam_foreign_assets.rs | 4 ++++ .../src/weights/pallet_moonbeam_foreign_assets.rs | 4 ++++ .../src/weights/pallet_moonbeam_foreign_assets.rs | 4 ++++ 4 files changed, 22 insertions(+) diff --git a/pallets/moonbeam-foreign-assets/src/weights.rs b/pallets/moonbeam-foreign-assets/src/weights.rs index 8b270fa1c5..b627c14f75 100644 --- a/pallets/moonbeam-foreign-assets/src/weights.rs +++ b/pallets/moonbeam-foreign-assets/src/weights.rs @@ -52,6 +52,7 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_foreign_asset_creator. pub trait WeightInfo { fn create_foreign_asset() -> Weight; + fn create_foreign_asset_reserve() -> Weight; fn change_xcm_location() -> Weight; fn freeze_foreign_asset() -> Weight; fn unfreeze_foreign_asset() -> Weight; @@ -75,6 +76,11 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } + + fn create_foreign_asset_reserve() -> Weight { + Weight::default() + } + /// Storage: `ForeignAssetsCreator::AssetIdToForeignAsset` (r:1 w:1) /// Proof: `ForeignAssetsCreator::AssetIdToForeignAsset` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `ForeignAssetsCreator::ForeignAssetToAssetId` (r:0 w:2) @@ -176,4 +182,8 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } + + fn create_foreign_asset_reserve() -> Weight { + Weight::default() + } } diff --git a/runtime/moonbase/src/weights/pallet_moonbeam_foreign_assets.rs b/runtime/moonbase/src/weights/pallet_moonbeam_foreign_assets.rs index a164942619..b061b649a1 100644 --- a/runtime/moonbase/src/weights/pallet_moonbeam_foreign_assets.rs +++ b/runtime/moonbase/src/weights/pallet_moonbeam_foreign_assets.rs @@ -170,4 +170,8 @@ impl pallet_moonbeam_foreign_assets::WeightInfo for Wei .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } + + fn create_foreign_asset_reserve() -> Weight { + Weight::default() + } } diff --git a/runtime/moonbeam/src/weights/pallet_moonbeam_foreign_assets.rs b/runtime/moonbeam/src/weights/pallet_moonbeam_foreign_assets.rs index 2daa581cd4..ff039f3e1b 100644 --- a/runtime/moonbeam/src/weights/pallet_moonbeam_foreign_assets.rs +++ b/runtime/moonbeam/src/weights/pallet_moonbeam_foreign_assets.rs @@ -170,4 +170,8 @@ impl pallet_moonbeam_foreign_assets::WeightInfo for Wei .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } + + fn create_foreign_asset_reserve() -> Weight { + Weight::default() + } } diff --git a/runtime/moonriver/src/weights/pallet_moonbeam_foreign_assets.rs b/runtime/moonriver/src/weights/pallet_moonbeam_foreign_assets.rs index 2daa581cd4..ff039f3e1b 100644 --- a/runtime/moonriver/src/weights/pallet_moonbeam_foreign_assets.rs +++ b/runtime/moonriver/src/weights/pallet_moonbeam_foreign_assets.rs @@ -170,4 +170,8 @@ impl pallet_moonbeam_foreign_assets::WeightInfo for Wei .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } + + fn create_foreign_asset_reserve() -> Weight { + Weight::default() + } } From 793236a38c45725eb796364e4703d6012f8ac81d Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Thu, 12 Dec 2024 19:57:48 -0300 Subject: [PATCH 05/41] format --- pallets/moonbeam-foreign-assets/src/tests.rs | 12 +++++++++--- runtime/moonbeam/src/xcm_config.rs | 4 ++-- runtime/moonriver/src/xcm_config.rs | 4 ++-- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/tests.rs b/pallets/moonbeam-foreign-assets/src/tests.rs index 32d1394a50..43d507e094 100644 --- a/pallets/moonbeam-foreign-assets/src/tests.rs +++ b/pallets/moonbeam-foreign-assets/src/tests.rs @@ -53,7 +53,10 @@ fn create_foreign_and_freeze_unfreeze() { ); assert_eq!( EvmForeignAssets::assets_creation_details(&1), - Some(AssetCreationDetails { creator: Alice.into(), deposit: 1}) + Some(AssetCreationDetails { + creator: Alice.into(), + deposit: 1 + }) ); expect_events(vec![crate::Event::ForeignAssetCreated { @@ -78,7 +81,10 @@ fn create_foreign_and_freeze_unfreeze() { ); assert_eq!( EvmForeignAssets::assets_creation_details(&1), - Some(AssetCreationDetails { creator: Alice.into(), deposit: 1}) + Some(AssetCreationDetails { + creator: Alice.into(), + deposit: 1 + }) ); // Unfreeze should return AssetNotFrozen error @@ -206,7 +212,7 @@ fn test_root_can_change_foreign_asset_for_asset_id() { ]), asset_id: 1, xcm_location: Location::parent(), - deposit: 1 + deposit: 1, }, crate::Event::ForeignAssetXcmLocationChanged { asset_id: 1, diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index 30685419be..b7400d8715 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -66,13 +66,13 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; +use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; +use moonbeam_core_primitives::BlockNumber; use sp_core::Get; use sp_std::{ convert::{From, Into, TryFrom}, prelude::*, }; -use moonbeam_core_primitives::BlockNumber; -use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; parameter_types! { // The network Id of the relay diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index 4a0898de9c..0c547152ca 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -66,13 +66,13 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; +use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; +use moonbeam_core_primitives::BlockNumber; use sp_core::Get; use sp_std::{ convert::{From, Into, TryFrom}, prelude::*, }; -use moonbeam_core_primitives::BlockNumber; -use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; parameter_types! { // The network Id of the relay From d3cedc25f7fec975293a0b500e012c2a7a4f9b3f Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Thu, 2 Jan 2025 17:59:40 -0300 Subject: [PATCH 06/41] simplify logic, rollback to granular origins per operation --- pallets/moonbeam-foreign-assets/src/lib.rs | 28 +++------------------- runtime/moonbase/src/xcm_config.rs | 4 ++-- runtime/moonbeam/src/xcm_config.rs | 4 ++-- runtime/moonriver/src/xcm_config.rs | 4 ++-- 4 files changed, 9 insertions(+), 31 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index 2375f9c028..ce52ecd708 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -390,28 +390,6 @@ pub mod pallet { AssetsByLocation::::insert(&asset_location, (asset_id, AssetStatus::Active)); AssetsById::::insert(&asset_id, asset_location); } - - /// Ensures that the origin has the required permissions to modifiy an asset - fn ensure_asset_owner(origin: OriginFor, asset_id: AssetId) -> DispatchResult { - let asset_details = AssetsCreationDetails::::get(&asset_id); - let caller = ensure_signed(origin.clone())?; - - match asset_details { - Some(data) => match data.owner { - AssetOwner::Account(account) => { - ensure!(account == caller, Error::::OriginIsNotAssetCreator); - } - AssetOwner::Governance | AssetOwner::Root => { - ::ForeignAssetFreezerOrigin::ensure_origin(origin)?; - } - }, - None => { - ::ForeignAssetFreezerOrigin::ensure_origin(origin)?; - } - } - - Ok(()) - } } #[pallet::call] @@ -489,7 +467,7 @@ pub mod pallet { asset_id: AssetId, new_xcm_location: Location, ) -> DispatchResult { - Self::ensure_asset_owner(origin.clone(), asset_id)?; + T::ForeignAssetModifierOrigin::ensure_origin(origin)?; let previous_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; @@ -522,7 +500,7 @@ pub mod pallet { asset_id: AssetId, allow_xcm_deposit: bool, ) -> DispatchResult { - Self::ensure_asset_owner(origin.clone(), asset_id)?; + T::ForeignAssetFreezerOrigin::ensure_origin(origin)?; let xcm_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; @@ -556,7 +534,7 @@ pub mod pallet { #[pallet::call_index(3)] #[pallet::weight(::WeightInfo::unfreeze_foreign_asset())] pub fn unfreeze_foreign_asset(origin: OriginFor, asset_id: AssetId) -> DispatchResult { - Self::ensure_asset_owner(origin.clone(), asset_id)?; + T::ForeignAssetUnfreezerOrigin::ensure_origin(origin)?; let xcm_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index 878e7886c0..eee9d11d98 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -36,7 +36,7 @@ use frame_support::{ traits::{EitherOfDiverse, Everything, Nothing, PalletInfoAccess, TransformOrigin}, }; -use frame_system::{EnsureRoot, RawOrigin}; +use frame_system::{EnsureRoot, EnsureSigned, RawOrigin}; use sp_core::{ConstU32, H160, H256}; use sp_weights::Weight; use xcm_builder::{ @@ -708,7 +708,7 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin; + type ForeignAssetCreatorOrigin = EnsureSigned; type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin; type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin; type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin; diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index b7400d8715..187dfebb90 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -36,7 +36,7 @@ use sp_runtime::{ }; use sp_weights::Weight; -use frame_system::{EnsureRoot, RawOrigin}; +use frame_system::{EnsureRoot, EnsureSigned, RawOrigin}; use sp_core::{ConstU32, H160, H256}; use xcm_builder::{ @@ -699,7 +699,7 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin; + type ForeignAssetCreatorOrigin = EnsureSigned; type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin; type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin; type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin; diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index 0c547152ca..504aaa974a 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -36,7 +36,7 @@ use sp_runtime::{ }; use sp_weights::Weight; -use frame_system::{EnsureRoot, RawOrigin}; +use frame_system::{EnsureRoot, EnsureSigned, RawOrigin}; use sp_core::{ConstU32, H160, H256}; use xcm_builder::{ @@ -706,7 +706,7 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin; + type ForeignAssetCreatorOrigin = EnsureSigned; type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin; type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin; type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin; From abb9290f08bf412faf95f2fa424f299b0e8d658a Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Fri, 3 Jan 2025 17:11:25 -0300 Subject: [PATCH 07/41] remove unused extrinsic --- pallets/moonbeam-foreign-assets/src/lib.rs | 62 ---------------------- 1 file changed, 62 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index ce52ecd708..07542a75d3 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -558,68 +558,6 @@ pub mod pallet { }); Ok(()) } - - #[pallet::call_index(4)] - #[pallet::weight(::WeightInfo::create_foreign_asset_reserve())] - pub fn create_foreign_asset_reserve( - origin: OriginFor, - asset_id: AssetId, - xcm_location: Location, - decimals: u8, - symbol: BoundedVec>, - name: BoundedVec>, - ) -> DispatchResult { - let owner_account = ensure_signed(origin)?; - - // Ensure such an assetId does not exist - ensure!( - !AssetsById::::contains_key(&asset_id), - Error::::AssetAlreadyExists - ); - - ensure!( - !AssetsByLocation::::contains_key(&xcm_location), - Error::::LocationAlreadyExists - ); - - ensure!( - AssetsById::::count() < T::MaxForeignAssets::get(), - Error::::TooManyForeignAssets - ); - - ensure!( - T::AssetIdFilter::contains(&asset_id), - Error::::AssetIdFiltered - ); - - let symbol = core::str::from_utf8(&symbol).map_err(|_| Error::::InvalidSymbol)?; - let name = core::str::from_utf8(&name).map_err(|_| Error::::InvalidTokenName)?; - let contract_address = - crate::evm::EvmCaller::::erc20_create(asset_id, decimals, symbol, name)?; - let deposit = T::ForeignAssetDeposit::get(); - let owner = AssetOwner::::Account(owner_account.clone()); - - // Insert the association assetId->foreigAsset - // Insert the association foreigAsset->assetId - AssetsById::::insert(&asset_id, &xcm_location); - AssetsByLocation::::insert(&xcm_location, (asset_id, crate::AssetStatus::Active)); - - // Reserve _deposit_ amount of funds from the caller - ::Currency::reserve(&owner_account, deposit)?; - - // Insert the amount that is reserved from the user - AssetsCreationDetails::::insert(&asset_id, AssetCreationDetails { owner, deposit }); - - T::OnForeignAssetCreated::on_asset_created(&xcm_location, &asset_id); - - Self::deposit_event(Event::ForeignAssetCreated { - contract_address, - asset_id, - xcm_location, - deposit, - }); - Ok(()) - } } impl xcm_executor::traits::TransactAsset for Pallet { From f7b300ef7f4d7749d161030bcac60522f787ad31 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Fri, 3 Jan 2025 17:11:36 -0300 Subject: [PATCH 08/41] improve readability --- pallets/moonbeam-foreign-assets/src/lib.rs | 26 ++++++++++++++------- pallets/moonbeam-foreign-assets/src/mock.rs | 4 ++-- runtime/moonbase/src/xcm_config.rs | 4 ++-- runtime/moonbeam/src/xcm_config.rs | 4 ++-- runtime/moonriver/src/xcm_config.rs | 4 ++-- 5 files changed, 25 insertions(+), 17 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index 07542a75d3..9502ec9d14 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -161,7 +161,7 @@ pub mod pallet { type XcmLocationToH160: ConvertLocation; /// Amount of tokens required to lock for creating a new foreign asset - type ForeignAssetDeposit: Get>; + type ForeignAssetCreationDeposit: Get>; /// The block number type for the pallet type BlockNumber: BlockNumber; @@ -217,7 +217,7 @@ pub mod pallet { contract_address: H160, asset_id: AssetId, xcm_location: Location, - deposit: BalanceOf, + deposit: Option>, }, /// Changed the xcm type mapping for a given asset id ForeignAssetXcmLocationChanged { @@ -265,14 +265,13 @@ pub mod pallet { #[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] pub enum AssetOwner { Governance, - Root, Account(T::AccountId), } #[derive(Clone, Decode, Encode, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)] pub struct AssetCreationDetails { pub owner: AssetOwner, - pub deposit: BalanceOf, + pub deposit: Option>, } impl Pallet { @@ -292,6 +291,8 @@ pub mod pallet { H160(buffer) } + /// This method only exists for migration purposes and will be deleted once the + /// foreign assets migration is finished. pub fn register_foreign_asset( asset_id: AssetId, xcm_location: Location, @@ -324,18 +325,22 @@ pub mod pallet { let name = core::str::from_utf8(&name).map_err(|_| Error::::InvalidTokenName)?; let contract_address = EvmCaller::::erc20_create(asset_id, decimals, symbol, name)?; + let owner = AssetOwner::::Governance; // Insert the association assetId->foreigAsset // Insert the association foreigAsset->assetId AssetsById::::insert(&asset_id, &xcm_location); AssetsByLocation::::insert(&xcm_location, (asset_id, AssetStatus::Active)); - let deposit = T::ForeignAssetDeposit::get(); + AssetsCreationDetails::::insert( + &asset_id, + AssetCreationDetails { owner, deposit: None } + ); Self::deposit_event(Event::ForeignAssetCreated { contract_address, asset_id, xcm_location, - deposit, + deposit: None, }); Ok(()) } @@ -432,7 +437,7 @@ pub mod pallet { let name = core::str::from_utf8(&name).map_err(|_| Error::::InvalidTokenName)?; let owner_account = ensure_signed(origin)?; let contract_address = EvmCaller::::erc20_create(asset_id, decimals, symbol, name)?; - let deposit = T::ForeignAssetDeposit::get(); + let deposit = T::ForeignAssetCreationDeposit::get(); let owner = AssetOwner::::Account(owner_account.clone()); // Insert the association assetId->foreigAsset @@ -444,7 +449,10 @@ pub mod pallet { ::Currency::reserve(&owner_account, deposit)?; // Insert the amount that is reserved from the user - AssetsCreationDetails::::insert(&asset_id, AssetCreationDetails { owner, deposit }); + AssetsCreationDetails::::insert( + &asset_id, + AssetCreationDetails { owner, deposit: Some(deposit) } + ); T::OnForeignAssetCreated::on_asset_created(&xcm_location, &asset_id); @@ -452,7 +460,7 @@ pub mod pallet { contract_address, asset_id, xcm_location, - deposit, + deposit: Some(deposit), }); Ok(()) } diff --git a/pallets/moonbeam-foreign-assets/src/mock.rs b/pallets/moonbeam-foreign-assets/src/mock.rs index df5af5e78b..ccf2518183 100644 --- a/pallets/moonbeam-foreign-assets/src/mock.rs +++ b/pallets/moonbeam-foreign-assets/src/mock.rs @@ -178,7 +178,7 @@ impl sp_runtime::traits::Convert for AccountIdToH160 { } parameter_types! { - pub const ForeignAssetDeposit: u64 = 1; + pub const ForeignAssetCreationDeposit: u64 = 1; } impl crate::Config for Test { @@ -194,7 +194,7 @@ impl crate::Config for Test { type RuntimeEvent = RuntimeEvent; type WeightInfo = (); type XcmLocationToH160 = (); - type ForeignAssetDeposit = (); + type ForeignAssetCreationDeposit = (); type BlockNumber = BlockNumber; type Balance = Balance; diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index eee9d11d98..801686e521 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -699,7 +699,7 @@ impl frame_support::traits::Contains for EvmForeignAssetIdFilter { parameter_types! { /// Balance in the native currency that will be reserved from the user /// to create a new foreign asset - pub ForeignAssetDeposit: u64 = 100; + pub ForeignAssetCreationDeposit: u64 = 100; } pub type ForeignAssetManagerOrigin = frame_system::EnsureSigned; @@ -717,7 +717,7 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = moonbase_weights::pallet_moonbeam_foreign_assets::WeightInfo; type XcmLocationToH160 = LocationToH160; - type ForeignAssetDeposit = ForeignAssetDeposit; + type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit; type BlockNumber = BlockNumber; type Currency = Balances; type Balance = Balance; diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index 187dfebb90..12e14c2fd6 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -692,7 +692,7 @@ pub type ForeignAssetManagerOrigin = EitherOfDiverse< parameter_types! { /// Balance in the native currency that will be reserved from the user /// to create a new foreign asset - pub ForeignAssetDeposit: u64 = 100; + pub ForeignAssetCreationDeposit: u64 = 100; } impl pallet_moonbeam_foreign_assets::Config for Runtime { @@ -708,7 +708,7 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = moonbeam_weights::pallet_moonbeam_foreign_assets::WeightInfo; type XcmLocationToH160 = LocationToH160; - type ForeignAssetDeposit = ForeignAssetDeposit; + type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit; type BlockNumber = BlockNumber; type Currency = Balances; type Balance = Balance; diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index 504aaa974a..9751fde73f 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -697,7 +697,7 @@ impl frame_support::traits::Contains for EvmForeignAssetIdFilter { parameter_types! { /// Balance in the native currency that will be reserved from the user /// to create a new foreign asset - pub ForeignAssetDeposit: u64 = 100; + pub ForeignAssetCreationDeposit: u64 = 100; } pub type ForeignAssetManagerOrigin = frame_system::EnsureSigned; @@ -715,7 +715,7 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = moonriver_weights::pallet_moonbeam_foreign_assets::WeightInfo; type XcmLocationToH160 = LocationToH160; - type ForeignAssetDeposit = ForeignAssetDeposit; + type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit; type BlockNumber = BlockNumber; type Currency = Balances; type Balance = Balance; From 4283fd441f6504cbbb83ed043cb4ebbae6af633c Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Fri, 3 Jan 2025 17:26:16 -0300 Subject: [PATCH 09/41] make ForeignAssetCreationDeposit dynamic --- runtime/moonbase/src/runtime_params.rs | 7 +++++++ runtime/moonbase/src/xcm_config.rs | 5 +++-- runtime/moonbeam/src/runtime_params.rs | 7 +++++++ runtime/moonbeam/src/xcm_config.rs | 10 +++------- runtime/moonriver/src/runtime_params.rs | 7 +++++++ runtime/moonriver/src/xcm_config.rs | 10 +++------- 6 files changed, 30 insertions(+), 16 deletions(-) diff --git a/runtime/moonbase/src/runtime_params.rs b/runtime/moonbase/src/runtime_params.rs index 2ac2a86141..b9739ae160 100644 --- a/runtime/moonbase/src/runtime_params.rs +++ b/runtime/moonbase/src/runtime_params.rs @@ -42,6 +42,13 @@ pub mod dynamic_params { { 1_000 * currency::UNIT * currency::SUPPLY_FACTOR }, > = BoundedU128::const_new::<{ 1 * currency::UNIT * currency::SUPPLY_FACTOR }>(); } + + #[dynamic_pallet_params] + #[codec(index = 2)] + pub mod xcm_config { + #[codec(index = 0)] + pub static ForeignAssetCreationDeposit: u64 = 100; + } } expose_u128_get!( diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index 801686e521..db98c00223 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -17,7 +17,7 @@ //! XCM configuration for Moonbase. //! -use super::moonbase_weights; +use super::{moonbase_weights, runtime_params}; use super::{ governance, AccountId, AssetId, AssetManager, Balance, Balances, EmergencyParaXcm, Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, ParachainInfo, @@ -699,7 +699,8 @@ impl frame_support::traits::Contains for EvmForeignAssetIdFilter { parameter_types! { /// Balance in the native currency that will be reserved from the user /// to create a new foreign asset - pub ForeignAssetCreationDeposit: u64 = 100; + pub ForeignAssetCreationDeposit: u64 = + runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } pub type ForeignAssetManagerOrigin = frame_system::EnsureSigned; diff --git a/runtime/moonbeam/src/runtime_params.rs b/runtime/moonbeam/src/runtime_params.rs index 7c37dbaf81..60eb625d6e 100644 --- a/runtime/moonbeam/src/runtime_params.rs +++ b/runtime/moonbeam/src/runtime_params.rs @@ -42,6 +42,13 @@ pub mod dynamic_params { { 1_000 * currency::GLMR * currency::SUPPLY_FACTOR }, > = BoundedU128::const_new::<{ 1 * currency::GLMR * currency::SUPPLY_FACTOR }>(); } + + #[dynamic_pallet_params] + #[codec(index = 2)] + pub mod xcm_config { + #[codec(index = 0)] + pub static ForeignAssetCreationDeposit: u64 = 10_000; + } } expose_u128_get!( diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index 12e14c2fd6..22a391f71c 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -17,12 +17,7 @@ //! XCM configuration for Moonbase. //! -use super::{ - governance, AccountId, AssetId, AssetManager, Balance, Balances, EmergencyParaXcm, - Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, OpenTechCommitteeInstance, - ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime, RuntimeBlockWeights, - RuntimeCall, RuntimeEvent, RuntimeOrigin, Treasury, XcmpQueue, -}; +use super::{governance, runtime_params, AccountId, AssetId, AssetManager, Balance, Balances, EmergencyParaXcm, Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, OpenTechCommitteeInstance, ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, Treasury, XcmpQueue}; use super::moonbeam_weights; use frame_support::{ @@ -692,7 +687,8 @@ pub type ForeignAssetManagerOrigin = EitherOfDiverse< parameter_types! { /// Balance in the native currency that will be reserved from the user /// to create a new foreign asset - pub ForeignAssetCreationDeposit: u64 = 100; + pub ForeignAssetCreationDeposit: u64 = + runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } impl pallet_moonbeam_foreign_assets::Config for Runtime { diff --git a/runtime/moonriver/src/runtime_params.rs b/runtime/moonriver/src/runtime_params.rs index 054a89ed26..e4ce48c77e 100644 --- a/runtime/moonriver/src/runtime_params.rs +++ b/runtime/moonriver/src/runtime_params.rs @@ -42,6 +42,13 @@ pub mod dynamic_params { { 1_000 * currency::MOVR * currency::SUPPLY_FACTOR }, > = BoundedU128::const_new::<{ 1 * currency::MOVR * currency::SUPPLY_FACTOR }>(); } + + #[dynamic_pallet_params] + #[codec(index = 2)] + pub mod xcm_config { + #[codec(index = 0)] + pub static ForeignAssetCreationDeposit: u64 = 1_000; + } } expose_u128_get!( diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index 9751fde73f..d2301afb29 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -17,12 +17,7 @@ //! XCM configuration for Moonbase. //! -use super::{ - governance, AccountId, AssetId, AssetManager, Balance, Balances, EmergencyParaXcm, - Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, OpenTechCommitteeInstance, - ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime, RuntimeBlockWeights, - RuntimeCall, RuntimeEvent, RuntimeOrigin, Treasury, XcmpQueue, -}; +use super::{governance, runtime_params, AccountId, AssetId, AssetManager, Balance, Balances, EmergencyParaXcm, Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, OpenTechCommitteeInstance, ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, Treasury, XcmpQueue}; use super::moonriver_weights; use frame_support::{ @@ -697,7 +692,8 @@ impl frame_support::traits::Contains for EvmForeignAssetIdFilter { parameter_types! { /// Balance in the native currency that will be reserved from the user /// to create a new foreign asset - pub ForeignAssetCreationDeposit: u64 = 100; + pub ForeignAssetCreationDeposit: u64 = + runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } pub type ForeignAssetManagerOrigin = frame_system::EnsureSigned; From a75ef407eb3619206e9f8903497bd7ca3c1411ae Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Mon, 6 Jan 2025 23:12:35 -0300 Subject: [PATCH 10/41] remove unused block number --- pallets/moonbeam-foreign-assets/src/lib.rs | 5 +---- pallets/moonbeam-foreign-assets/src/mock.rs | 1 - runtime/moonbase/src/xcm_config.rs | 2 -- runtime/moonbeam/src/xcm_config.rs | 4 +--- runtime/moonriver/src/xcm_config.rs | 2 -- 5 files changed, 2 insertions(+), 12 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index 9502ec9d14..abc5d5d38c 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -109,7 +109,7 @@ pub mod pallet { use super::*; use frame_support::traits::{Currency, ReservableCurrency}; use pallet_evm::{GasWeightMapping, Runner}; - use sp_runtime::traits::{AccountIdConversion, AtLeast32BitUnsigned, BlockNumber, Convert}; + use sp_runtime::traits::{AccountIdConversion, AtLeast32BitUnsigned, Convert}; use xcm_executor::traits::ConvertLocation; use xcm_executor::traits::Error as MatchError; use xcm_executor::AssetsInHolding; @@ -163,9 +163,6 @@ pub mod pallet { /// Amount of tokens required to lock for creating a new foreign asset type ForeignAssetCreationDeposit: Get>; - /// The block number type for the pallet - type BlockNumber: BlockNumber; - /// The balance type for locking funds type Balance: Member + Parameter diff --git a/pallets/moonbeam-foreign-assets/src/mock.rs b/pallets/moonbeam-foreign-assets/src/mock.rs index ccf2518183..b7c27a2500 100644 --- a/pallets/moonbeam-foreign-assets/src/mock.rs +++ b/pallets/moonbeam-foreign-assets/src/mock.rs @@ -195,7 +195,6 @@ impl crate::Config for Test { type WeightInfo = (); type XcmLocationToH160 = (); type ForeignAssetCreationDeposit = (); - type BlockNumber = BlockNumber; type Balance = Balance; type Currency = Balances; diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index db98c00223..24c4ea42b6 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -58,7 +58,6 @@ use xcm::latest::prelude::{ use xcm_executor::traits::{CallDispatcher, ConvertLocation, JustTry}; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; -use parachains_common::BlockNumber; use xcm_primitives::{ AbsoluteAndRelativeReserve, AccountIdToCurrencyId, AccountIdToLocation, AsAssetType, IsBridgedConcreteAssetFrom, MultiNativeAsset, SignedToAccountId20, UtilityAvailableCalls, @@ -719,7 +718,6 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type WeightInfo = moonbase_weights::pallet_moonbeam_foreign_assets::WeightInfo; type XcmLocationToH160 = LocationToH160; type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit; - type BlockNumber = BlockNumber; type Currency = Balances; type Balance = Balance; } diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index 22a391f71c..6996f5861c 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -62,7 +62,6 @@ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; -use moonbeam_core_primitives::BlockNumber; use sp_core::Get; use sp_std::{ convert::{From, Into, TryFrom}, @@ -705,9 +704,8 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type WeightInfo = moonbeam_weights::pallet_moonbeam_foreign_assets::WeightInfo; type XcmLocationToH160 = LocationToH160; type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit; - type BlockNumber = BlockNumber; - type Currency = Balances; type Balance = Balance; + type Currency = Balances; } pub struct AssetFeesFilter; diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index d2301afb29..9a527616b8 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -62,7 +62,6 @@ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; -use moonbeam_core_primitives::BlockNumber; use sp_core::Get; use sp_std::{ convert::{From, Into, TryFrom}, @@ -712,7 +711,6 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type WeightInfo = moonriver_weights::pallet_moonbeam_foreign_assets::WeightInfo; type XcmLocationToH160 = LocationToH160; type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit; - type BlockNumber = BlockNumber; type Currency = Balances; type Balance = Balance; } From c3650930b3bdd1dfebbc142d5a3d4b5453abc7a0 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Mon, 6 Jan 2025 23:13:23 -0300 Subject: [PATCH 11/41] fix rust tests --- pallets/moonbeam-foreign-assets/src/mock.rs | 8 +- pallets/moonbeam-foreign-assets/src/tests.rs | 12 +-- pallets/moonbeam-lazy-migrations/src/mock.rs | 7 +- runtime/moonbase/tests/common/mod.rs | 2 +- runtime/moonbase/tests/integration_test.rs | 84 +++++++++++--------- 5 files changed, 61 insertions(+), 52 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/mock.rs b/pallets/moonbeam-foreign-assets/src/mock.rs index b7c27a2500..5461ecb8c0 100644 --- a/pallets/moonbeam-foreign-assets/src/mock.rs +++ b/pallets/moonbeam-foreign-assets/src/mock.rs @@ -19,7 +19,7 @@ use crate as pallet_moonbeam_foreign_assets; use frame_support::traits::Everything; use frame_support::{construct_runtime, pallet_prelude::*, parameter_types}; -use frame_system::EnsureRoot; +use frame_system::{EnsureRoot, EnsureSigned}; use pallet_evm::{FrameSystemAccountProvider, SubstrateBlockHashMapping}; use precompile_utils::testing::MockAccount; use sp_core::{H256, U256}; @@ -178,14 +178,14 @@ impl sp_runtime::traits::Convert for AccountIdToH160 { } parameter_types! { - pub const ForeignAssetCreationDeposit: u64 = 1; + pub const ForeignAssetCreationDeposit: u128 = 0; } impl crate::Config for Test { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = Everything; type EvmRunner = pallet_evm::runner::stack::Runner; - type ForeignAssetCreatorOrigin = EnsureRoot; + type ForeignAssetCreatorOrigin = EnsureSigned; type ForeignAssetFreezerOrigin = EnsureRoot; type ForeignAssetModifierOrigin = EnsureRoot; type ForeignAssetUnfreezerOrigin = EnsureRoot; @@ -194,7 +194,7 @@ impl crate::Config for Test { type RuntimeEvent = RuntimeEvent; type WeightInfo = (); type XcmLocationToH160 = (); - type ForeignAssetCreationDeposit = (); + type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit; type Balance = Balance; type Currency = Balances; diff --git a/pallets/moonbeam-foreign-assets/src/tests.rs b/pallets/moonbeam-foreign-assets/src/tests.rs index 43d507e094..ebd3654128 100644 --- a/pallets/moonbeam-foreign-assets/src/tests.rs +++ b/pallets/moonbeam-foreign-assets/src/tests.rs @@ -54,8 +54,8 @@ fn create_foreign_and_freeze_unfreeze() { assert_eq!( EvmForeignAssets::assets_creation_details(&1), Some(AssetCreationDetails { - creator: Alice.into(), - deposit: 1 + owner: AssetOwner::Account(Alice.into()), + deposit: Some(ForeignAssetCreationDeposit::get()) }) ); @@ -65,7 +65,7 @@ fn create_foreign_and_freeze_unfreeze() { ]), asset_id: 1, xcm_location: Location::parent(), - deposit: 1, + deposit: Some(ForeignAssetCreationDeposit::get()), }]); let (xcm_location, asset_id): (Location, u128) = get_asset_created_hook_invocation() @@ -82,8 +82,8 @@ fn create_foreign_and_freeze_unfreeze() { assert_eq!( EvmForeignAssets::assets_creation_details(&1), Some(AssetCreationDetails { - creator: Alice.into(), - deposit: 1 + owner: AssetOwner::Account(Alice.into()), + deposit: Some(1) }) ); @@ -212,7 +212,7 @@ fn test_root_can_change_foreign_asset_for_asset_id() { ]), asset_id: 1, xcm_location: Location::parent(), - deposit: 1, + deposit: Some(ForeignAssetCreationDeposit::get()), }, crate::Event::ForeignAssetXcmLocationChanged { asset_id: 1, diff --git a/pallets/moonbeam-lazy-migrations/src/mock.rs b/pallets/moonbeam-lazy-migrations/src/mock.rs index 6aecf8164c..fea4aabe36 100644 --- a/pallets/moonbeam-lazy-migrations/src/mock.rs +++ b/pallets/moonbeam-lazy-migrations/src/mock.rs @@ -18,7 +18,7 @@ use super::*; use crate as pallet_moonbeam_lazy_migrations; -use frame_support::traits::AsEnsureOriginWithArg; +use frame_support::traits::{AsEnsureOriginWithArg, ConstU128}; use frame_support::weights::constants::RocksDbWeight; use frame_support::{construct_runtime, parameter_types, traits::Everything, weights::Weight}; use frame_system::{EnsureRoot, EnsureSigned}; @@ -292,7 +292,7 @@ impl pallet_moonbeam_foreign_assets::Config for Test { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = Everything; type EvmRunner = pallet_evm::runner::stack::Runner; - type ForeignAssetCreatorOrigin = EnsureRoot; + type ForeignAssetCreatorOrigin = EnsureSigned; type ForeignAssetFreezerOrigin = EnsureRoot; type ForeignAssetModifierOrigin = EnsureRoot; type ForeignAssetUnfreezerOrigin = EnsureRoot; @@ -301,6 +301,9 @@ impl pallet_moonbeam_foreign_assets::Config for Test { type RuntimeEvent = RuntimeEvent; type WeightInfo = (); type XcmLocationToH160 = (); + type ForeignAssetCreationDeposit = ConstU128<1>; + type Balance = Balance; + type Currency = Balances; } impl Config for Test { diff --git a/runtime/moonbase/tests/common/mod.rs b/runtime/moonbase/tests/common/mod.rs index 19df108ab7..5897b73fc7 100644 --- a/runtime/moonbase/tests/common/mod.rs +++ b/runtime/moonbase/tests/common/mod.rs @@ -294,7 +294,7 @@ impl ExtBuilder { for xcm_asset_initialization in xcm_assets { let asset_id = xcm_asset_initialization.asset_id; EvmForeignAssets::create_foreign_asset( - root_origin(), + moonbase_runtime::RuntimeOrigin::signed(AccountId::from(ALICE)), asset_id, xcm_asset_initialization.xcm_location, xcm_asset_initialization.decimals, diff --git a/runtime/moonbase/tests/integration_test.rs b/runtime/moonbase/tests/integration_test.rs index 9cc5ef1a25..64320af46e 100644 --- a/runtime/moonbase/tests/integration_test.rs +++ b/runtime/moonbase/tests/integration_test.rs @@ -1266,48 +1266,54 @@ fn update_reward_address_via_precompile() { #[test] fn create_and_manipulate_foreign_asset() { - ExtBuilder::default().build().execute_with(|| { - let source_location = xcm::v4::Location::parent(); + let alice = AccountId::from(ALICE); + ExtBuilder::default() + .with_balances(vec![ + (alice, 1_000 * UNIT), + ]) + .build() + .execute_with(|| { + let source_location = xcm::v4::Location::parent(); - // Create foreign asset - assert_ok!(EvmForeignAssets::create_foreign_asset( - moonbase_runtime::RuntimeOrigin::root(), - 1, - source_location.clone(), - 12, - bounded_vec![b'M', b'T'], - bounded_vec![b'M', b'y', b'T', b'o', b'k'], - )); - assert_eq!( - EvmForeignAssets::assets_by_id(1), - Some(source_location.clone()) - ); - assert_eq!( - EvmForeignAssets::assets_by_location(&source_location), - Some((1, AssetStatus::Active)) - ); + // Create foreign asset + assert_ok!(EvmForeignAssets::create_foreign_asset( + moonbase_runtime::RuntimeOrigin::signed(alice), + 1, + source_location.clone(), + 12, + bounded_vec![b'M', b'T'], + bounded_vec![b'M', b'y', b'T', b'o', b'k'], + )); + assert_eq!( + EvmForeignAssets::assets_by_id(1), + Some(source_location.clone()) + ); + assert_eq!( + EvmForeignAssets::assets_by_location(&source_location), + Some((1, AssetStatus::Active)) + ); - // Freeze foreign asset - assert_ok!(EvmForeignAssets::freeze_foreign_asset( - moonbase_runtime::RuntimeOrigin::root(), - 1, - true - )); - assert_eq!( - EvmForeignAssets::assets_by_location(&source_location), - Some((1, AssetStatus::FrozenXcmDepositAllowed)) - ); + // Freeze foreign asset + assert_ok!(EvmForeignAssets::freeze_foreign_asset( + root_origin(), + 1, + true + )); + assert_eq!( + EvmForeignAssets::assets_by_location(&source_location), + Some((1, AssetStatus::FrozenXcmDepositAllowed)) + ); - // Unfreeze foreign asset - assert_ok!(EvmForeignAssets::unfreeze_foreign_asset( - moonbase_runtime::RuntimeOrigin::root(), - 1, - )); - assert_eq!( - EvmForeignAssets::assets_by_location(&source_location), - Some((1, AssetStatus::Active)) - ); - }); + // Unfreeze foreign asset + assert_ok!(EvmForeignAssets::unfreeze_foreign_asset( + root_origin(), + 1, + )); + assert_eq!( + EvmForeignAssets::assets_by_location(&source_location), + Some((1, AssetStatus::Active)) + ); + }); } // The precoompile asset-erc20 is deprecated and not used anymore for new evm foreign assets From 2e396b4db32c22fb6e2ba93c79a251b030fabaf5 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Tue, 7 Jan 2025 09:46:46 -0300 Subject: [PATCH 12/41] fix moonbase xcm config --- runtime/moonbase/src/xcm_config.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index 24c4ea42b6..a0fef2e0e1 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -702,7 +702,13 @@ parameter_types! { runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } -pub type ForeignAssetManagerOrigin = frame_system::EnsureSigned; +pub type ForeignAssetManagerOrigin = EitherOfDiverse< + EnsureRoot, + EitherOfDiverse< + pallet_collective::EnsureProportionMoreThan, + governance::custom_origins::FastGeneralAdmin, + >, +>; impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; From 0f5c5d1638b17c0024f3f4aa87b94e130c5e3139 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Tue, 7 Jan 2025 09:46:53 -0300 Subject: [PATCH 13/41] fmt --- pallets/moonbeam-foreign-assets/src/lib.rs | 10 ++++++++-- pallets/moonbeam-foreign-assets/src/mock.rs | 1 - runtime/moonbase/src/xcm_config.rs | 4 ++-- runtime/moonbeam/src/xcm_config.rs | 7 ++++++- runtime/moonriver/src/xcm_config.rs | 7 ++++++- 5 files changed, 22 insertions(+), 7 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index abc5d5d38c..d2758aef3f 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -330,7 +330,10 @@ pub mod pallet { AssetsByLocation::::insert(&xcm_location, (asset_id, AssetStatus::Active)); AssetsCreationDetails::::insert( &asset_id, - AssetCreationDetails { owner, deposit: None } + AssetCreationDetails { + owner, + deposit: None, + }, ); Self::deposit_event(Event::ForeignAssetCreated { @@ -448,7 +451,10 @@ pub mod pallet { // Insert the amount that is reserved from the user AssetsCreationDetails::::insert( &asset_id, - AssetCreationDetails { owner, deposit: Some(deposit) } + AssetCreationDetails { + owner, + deposit: Some(deposit), + }, ); T::OnForeignAssetCreated::on_asset_created(&xcm_location, &asset_id); diff --git a/pallets/moonbeam-foreign-assets/src/mock.rs b/pallets/moonbeam-foreign-assets/src/mock.rs index 5461ecb8c0..2558c27218 100644 --- a/pallets/moonbeam-foreign-assets/src/mock.rs +++ b/pallets/moonbeam-foreign-assets/src/mock.rs @@ -198,7 +198,6 @@ impl crate::Config for Test { type Balance = Balance; type Currency = Balances; - } pub(crate) struct ExtBuilder { diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index a0fef2e0e1..ee6a5c5acc 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -17,13 +17,13 @@ //! XCM configuration for Moonbase. //! -use super::{moonbase_weights, runtime_params}; use super::{ governance, AccountId, AssetId, AssetManager, Balance, Balances, EmergencyParaXcm, Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, Treasury, XcmpQueue, }; +use super::{moonbase_weights, runtime_params}; use crate::OpenTechCommitteeInstance; use moonkit_xcm_primitives::AccountIdAssetIdConversion; use sp_runtime::{ @@ -724,8 +724,8 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type WeightInfo = moonbase_weights::pallet_moonbeam_foreign_assets::WeightInfo; type XcmLocationToH160 = LocationToH160; type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit; - type Currency = Balances; type Balance = Balance; + type Currency = Balances; } pub struct AssetFeesFilter; diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index 6996f5861c..dd91706485 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -17,7 +17,12 @@ //! XCM configuration for Moonbase. //! -use super::{governance, runtime_params, AccountId, AssetId, AssetManager, Balance, Balances, EmergencyParaXcm, Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, OpenTechCommitteeInstance, ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, Treasury, XcmpQueue}; +use super::{ + governance, runtime_params, AccountId, AssetId, AssetManager, Balance, Balances, + EmergencyParaXcm, Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, + OpenTechCommitteeInstance, ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime, + RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, Treasury, XcmpQueue, +}; use super::moonbeam_weights; use frame_support::{ diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index 9a527616b8..5d6a7ef733 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -17,7 +17,12 @@ //! XCM configuration for Moonbase. //! -use super::{governance, runtime_params, AccountId, AssetId, AssetManager, Balance, Balances, EmergencyParaXcm, Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, OpenTechCommitteeInstance, ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, Treasury, XcmpQueue}; +use super::{ + governance, runtime_params, AccountId, AssetId, AssetManager, Balance, Balances, + EmergencyParaXcm, Erc20XcmBridge, EvmForeignAssets, MaintenanceMode, MessageQueue, + OpenTechCommitteeInstance, ParachainInfo, ParachainSystem, Perbill, PolkadotXcm, Runtime, + RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, Treasury, XcmpQueue, +}; use super::moonriver_weights; use frame_support::{ From a79f5d7ca242ff6ab44e67086607a373fae989c6 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Tue, 7 Jan 2025 13:25:51 -0300 Subject: [PATCH 14/41] fix manager origin for moonriver --- runtime/moonriver/src/xcm_config.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index 6a0f9906e3..0bb0d88790 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -700,7 +700,13 @@ parameter_types! { runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } -pub type ForeignAssetManagerOrigin = frame_system::EnsureSigned; +pub type ForeignAssetManagerOrigin = EitherOfDiverse< + EnsureRoot, + EitherOfDiverse< + pallet_collective::EnsureProportionMoreThan, + governance::custom_origins::FastGeneralAdmin, + >, +>; impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; From dd6e3f672819d206c9e0bc00e879294c1b190d27 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Tue, 7 Jan 2025 13:26:07 -0300 Subject: [PATCH 15/41] tidy --- runtime/moonbase/tests/integration_test.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/runtime/moonbase/tests/integration_test.rs b/runtime/moonbase/tests/integration_test.rs index 15bc4acef2..7f4bc25cb1 100644 --- a/runtime/moonbase/tests/integration_test.rs +++ b/runtime/moonbase/tests/integration_test.rs @@ -1268,9 +1268,7 @@ fn update_reward_address_via_precompile() { fn create_and_manipulate_foreign_asset() { let alice = AccountId::from(ALICE); ExtBuilder::default() - .with_balances(vec![ - (alice, 1_000 * UNIT), - ]) + .with_balances(vec![(alice, 1_000 * UNIT)]) .build() .execute_with(|| { let source_location = xcm::v4::Location::parent(); @@ -1305,10 +1303,7 @@ fn create_and_manipulate_foreign_asset() { ); // Unfreeze foreign asset - assert_ok!(EvmForeignAssets::unfreeze_foreign_asset( - root_origin(), - 1, - )); + assert_ok!(EvmForeignAssets::unfreeze_foreign_asset(root_origin(), 1,)); assert_eq!( EvmForeignAssets::assets_by_location(&source_location), Some((1, AssetStatus::Active)) From 8cf4b8af651d0b2d012e41016b8865cfc1624a24 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Tue, 7 Jan 2025 13:32:31 -0300 Subject: [PATCH 16/41] change back MaxFreezes to 0 as not needed anymore --- runtime/moonriver/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/moonriver/src/lib.rs b/runtime/moonriver/src/lib.rs index 79221fbb34..47e564ea5a 100644 --- a/runtime/moonriver/src/lib.rs +++ b/runtime/moonriver/src/lib.rs @@ -328,7 +328,7 @@ impl pallet_balances::Config for Runtime { type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type FreezeIdentifier = (); - type MaxFreezes = ConstU32<50>; + type MaxFreezes = ConstU32<0>; type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type WeightInfo = moonriver_weights::pallet_balances::WeightInfo; From 07c6cab33ea0bc4f952f08e6afced3ac33803525 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Tue, 7 Jan 2025 15:14:57 -0300 Subject: [PATCH 17/41] fix foreign assets rust tests --- pallets/moonbeam-foreign-assets/src/mock.rs | 7 +++- pallets/moonbeam-foreign-assets/src/tests.rs | 44 +++++++++++++------- 2 files changed, 35 insertions(+), 16 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/mock.rs b/pallets/moonbeam-foreign-assets/src/mock.rs index 2558c27218..c16b6980e5 100644 --- a/pallets/moonbeam-foreign-assets/src/mock.rs +++ b/pallets/moonbeam-foreign-assets/src/mock.rs @@ -178,7 +178,7 @@ impl sp_runtime::traits::Convert for AccountIdToH160 { } parameter_types! { - pub const ForeignAssetCreationDeposit: u128 = 0; + pub const ForeignAssetCreationDeposit: u128 = 1; } impl crate::Config for Test { @@ -226,6 +226,11 @@ impl ExtBuilder { ext.execute_with(|| System::set_block_number(1)); ext } + + pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self { + self.balances = balances; + self + } } pub(crate) fn events() -> Vec> { diff --git a/pallets/moonbeam-foreign-assets/src/tests.rs b/pallets/moonbeam-foreign-assets/src/tests.rs index ebd3654128..0a84b1ce54 100644 --- a/pallets/moonbeam-foreign-assets/src/tests.rs +++ b/pallets/moonbeam-foreign-assets/src/tests.rs @@ -31,7 +31,9 @@ fn encode_token_name(str_: &str) -> BoundedVec> { #[test] fn create_foreign_and_freeze_unfreeze() { - ExtBuilder::default().build().execute_with(|| { + ExtBuilder::default() + .with_balances(vec![(Alice.into(), 1_000)]) + .build().execute_with(|| { // create foreign asset assert_ok!(EvmForeignAssets::create_foreign_asset( RuntimeOrigin::from(Some(Alice.into())), @@ -124,9 +126,11 @@ fn create_foreign_and_freeze_unfreeze() { #[test] fn test_asset_exists_error() { - ExtBuilder::default().build().execute_with(|| { + ExtBuilder::default() + .with_balances(vec![(Alice.into(), 1_000)]) + .build().execute_with(|| { assert_ok!(EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::root(), + RuntimeOrigin::signed(Alice.into()), 1, Location::parent(), 18, @@ -139,7 +143,7 @@ fn test_asset_exists_error() { ); assert_noop!( EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::root(), + RuntimeOrigin::signed(Alice.into()), 1, Location::parent(), 18, @@ -152,36 +156,44 @@ fn test_asset_exists_error() { } #[test] -fn test_regular_user_cannot_call_extrinsics() { +fn test_regular_user_cannot_call_some_extrinsics() { ExtBuilder::default().build().execute_with(|| { assert_noop!( - EvmForeignAssets::create_foreign_asset( + EvmForeignAssets::change_xcm_location( RuntimeOrigin::signed(Bob.into()), 1, - Location::parent(), - 18, - encode_ticker("MTT"), - encode_token_name("Mytoken"), + Location::parent() ), sp_runtime::DispatchError::BadOrigin ); assert_noop!( - EvmForeignAssets::change_xcm_location( + EvmForeignAssets::freeze_foreign_asset( RuntimeOrigin::signed(Bob.into()), 1, - Location::parent() + false ), sp_runtime::DispatchError::BadOrigin ); + + assert_noop!( + EvmForeignAssets::unfreeze_foreign_asset( + RuntimeOrigin::signed(Bob.into()), + 1, + ), + sp_runtime::DispatchError::BadOrigin + ); + }); } #[test] fn test_root_can_change_foreign_asset_for_asset_id() { - ExtBuilder::default().build().execute_with(|| { + ExtBuilder::default() + .with_balances(vec![(Alice.into(), 1_000)]) + .build().execute_with(|| { assert_ok!(EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::root(), + RuntimeOrigin::signed(Alice.into()), 1, Location::parent(), 18, @@ -234,7 +246,9 @@ fn test_asset_id_non_existent_error() { #[test] fn test_location_already_exist_error() { - ExtBuilder::default().build().execute_with(|| { + ExtBuilder::default() + .with_balances(vec![(Alice.into(), 1_000)]) + .build().execute_with(|| { // Setup: create a first foreign asset taht we will try to override assert_ok!(EvmForeignAssets::create_foreign_asset( RuntimeOrigin::from(Some(Alice.into())), From ef4856ced6e5ca34734a156a524e52a6aa29760a Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Tue, 7 Jan 2025 15:34:55 -0300 Subject: [PATCH 18/41] make helper use correct call for creating foreign assets --- test/helpers/assets.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/helpers/assets.ts b/test/helpers/assets.ts index 4ca79762a1..c46d1c3c7b 100644 --- a/test/helpers/assets.ts +++ b/test/helpers/assets.ts @@ -403,10 +403,11 @@ export async function registerForeignAsset( const { result } = await context.createBlock( context .polkadotJs() - .tx.sudo.sudo( - context - .polkadotJs() - .tx.evmForeignAssets.createForeignAsset(assetId, xcmLoc, decimals, symbol, name) + .tx.sudo.sudoAs( + alith.address, + context + .polkadotJs() + .tx.evmForeignAssets.createForeignAsset(assetId, xcmLoc, decimals, symbol, name) ) ); From 9bafa10fbfa0f5a9964320693fd81d9e04eaf546 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Tue, 7 Jan 2025 18:22:05 -0300 Subject: [PATCH 19/41] reformat test --- pallets/moonbeam-foreign-assets/src/tests.rs | 352 +++++++++---------- 1 file changed, 174 insertions(+), 178 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/tests.rs b/pallets/moonbeam-foreign-assets/src/tests.rs index 0a84b1ce54..026351fae5 100644 --- a/pallets/moonbeam-foreign-assets/src/tests.rs +++ b/pallets/moonbeam-foreign-assets/src/tests.rs @@ -33,126 +33,128 @@ fn encode_token_name(str_: &str) -> BoundedVec> { fn create_foreign_and_freeze_unfreeze() { ExtBuilder::default() .with_balances(vec![(Alice.into(), 1_000)]) - .build().execute_with(|| { - // create foreign asset - assert_ok!(EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::from(Some(Alice.into())), - 1, - Location::parent(), - 18, - encode_ticker("MTT"), - encode_token_name("Mytoken"), - )); + .build() + .execute_with(|| { + // create foreign asset + assert_ok!(EvmForeignAssets::create_foreign_asset( + RuntimeOrigin::from(Some(Alice.into())), + 1, + Location::parent(), + 18, + encode_ticker("MTT"), + encode_token_name("Mytoken"), + )); - assert_eq!(EvmForeignAssets::assets_by_id(1), Some(Location::parent())); - assert_eq!( - EvmForeignAssets::assets_by_location(Location::parent()), - Some((1, AssetStatus::Active)), - ); - assert_eq!( - EvmForeignAssets::assets_by_location(Location::parent()), - Some((1, AssetStatus::Active)), - ); - assert_eq!( - EvmForeignAssets::assets_creation_details(&1), - Some(AssetCreationDetails { - owner: AssetOwner::Account(Alice.into()), - deposit: Some(ForeignAssetCreationDeposit::get()) - }) - ); + assert_eq!(EvmForeignAssets::assets_by_id(1), Some(Location::parent())); + assert_eq!( + EvmForeignAssets::assets_by_location(Location::parent()), + Some((1, AssetStatus::Active)), + ); + assert_eq!( + EvmForeignAssets::assets_by_location(Location::parent()), + Some((1, AssetStatus::Active)), + ); + assert_eq!( + EvmForeignAssets::assets_creation_details(&1), + Some(AssetCreationDetails { + owner: AssetOwner::Account(Alice.into()), + deposit: Some(ForeignAssetCreationDeposit::get()) + }) + ); - expect_events(vec![crate::Event::ForeignAssetCreated { - contract_address: H160([ - 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, - ]), - asset_id: 1, - xcm_location: Location::parent(), - deposit: Some(ForeignAssetCreationDeposit::get()), - }]); + expect_events(vec![crate::Event::ForeignAssetCreated { + contract_address: H160([ + 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + ]), + asset_id: 1, + xcm_location: Location::parent(), + deposit: Some(ForeignAssetCreationDeposit::get()), + }]); - let (xcm_location, asset_id): (Location, u128) = get_asset_created_hook_invocation() - .expect("Decoding of invocation data should not fail"); - assert_eq!(xcm_location, Location::parent()); - assert_eq!(asset_id, 1u128); + let (xcm_location, asset_id): (Location, u128) = get_asset_created_hook_invocation() + .expect("Decoding of invocation data should not fail"); + assert_eq!(xcm_location, Location::parent()); + assert_eq!(asset_id, 1u128); - // Check storage - assert_eq!(EvmForeignAssets::assets_by_id(&1), Some(Location::parent())); - assert_eq!( - EvmForeignAssets::assets_by_location(&Location::parent()), - Some((1, AssetStatus::Active)) - ); - assert_eq!( - EvmForeignAssets::assets_creation_details(&1), - Some(AssetCreationDetails { - owner: AssetOwner::Account(Alice.into()), - deposit: Some(1) - }) - ); + // Check storage + assert_eq!(EvmForeignAssets::assets_by_id(&1), Some(Location::parent())); + assert_eq!( + EvmForeignAssets::assets_by_location(&Location::parent()), + Some((1, AssetStatus::Active)) + ); + assert_eq!( + EvmForeignAssets::assets_creation_details(&1), + Some(AssetCreationDetails { + owner: AssetOwner::Account(Alice.into()), + deposit: Some(1) + }) + ); - // Unfreeze should return AssetNotFrozen error - assert_noop!( - EvmForeignAssets::unfreeze_foreign_asset(RuntimeOrigin::root(), 1), - Error::::AssetNotFrozen - ); + // Unfreeze should return AssetNotFrozen error + assert_noop!( + EvmForeignAssets::unfreeze_foreign_asset(RuntimeOrigin::root(), 1), + Error::::AssetNotFrozen + ); - // Freeze should work - assert_ok!(EvmForeignAssets::freeze_foreign_asset( - RuntimeOrigin::root(), - 1, - true - ),); - assert_eq!( - EvmForeignAssets::assets_by_location(&Location::parent()), - Some((1, AssetStatus::FrozenXcmDepositAllowed)) - ); + // Freeze should work + assert_ok!(EvmForeignAssets::freeze_foreign_asset( + RuntimeOrigin::root(), + 1, + true + ),); + assert_eq!( + EvmForeignAssets::assets_by_location(&Location::parent()), + Some((1, AssetStatus::FrozenXcmDepositAllowed)) + ); - // Should not be able to freeze an asset already frozen - assert_noop!( - EvmForeignAssets::freeze_foreign_asset(RuntimeOrigin::root(), 1, true), - Error::::AssetAlreadyFrozen - ); + // Should not be able to freeze an asset already frozen + assert_noop!( + EvmForeignAssets::freeze_foreign_asset(RuntimeOrigin::root(), 1, true), + Error::::AssetAlreadyFrozen + ); - // Unfreeze should work - assert_ok!(EvmForeignAssets::unfreeze_foreign_asset( - RuntimeOrigin::root(), - 1 - ),); - assert_eq!( - EvmForeignAssets::assets_by_location(&Location::parent()), - Some((1, AssetStatus::Active)) - ); - }); + // Unfreeze should work + assert_ok!(EvmForeignAssets::unfreeze_foreign_asset( + RuntimeOrigin::root(), + 1 + ),); + assert_eq!( + EvmForeignAssets::assets_by_location(&Location::parent()), + Some((1, AssetStatus::Active)) + ); + }); } #[test] fn test_asset_exists_error() { ExtBuilder::default() .with_balances(vec![(Alice.into(), 1_000)]) - .build().execute_with(|| { - assert_ok!(EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::signed(Alice.into()), - 1, - Location::parent(), - 18, - encode_ticker("MTT"), - encode_token_name("Mytoken"), - )); - assert_eq!( - EvmForeignAssets::assets_by_id(1).unwrap(), - Location::parent() - ); - assert_noop!( - EvmForeignAssets::create_foreign_asset( + .build() + .execute_with(|| { + assert_ok!(EvmForeignAssets::create_foreign_asset( RuntimeOrigin::signed(Alice.into()), 1, Location::parent(), 18, encode_ticker("MTT"), encode_token_name("Mytoken"), - ), - Error::::AssetAlreadyExists - ); - }); + )); + assert_eq!( + EvmForeignAssets::assets_by_id(1).unwrap(), + Location::parent() + ); + assert_noop!( + EvmForeignAssets::create_foreign_asset( + RuntimeOrigin::signed(Alice.into()), + 1, + Location::parent(), + 18, + encode_ticker("MTT"), + encode_token_name("Mytoken"), + ), + Error::::AssetAlreadyExists + ); + }); } #[test] @@ -168,22 +170,14 @@ fn test_regular_user_cannot_call_some_extrinsics() { ); assert_noop!( - EvmForeignAssets::freeze_foreign_asset( - RuntimeOrigin::signed(Bob.into()), - 1, - false - ), + EvmForeignAssets::freeze_foreign_asset(RuntimeOrigin::signed(Bob.into()), 1, false), sp_runtime::DispatchError::BadOrigin ); assert_noop!( - EvmForeignAssets::unfreeze_foreign_asset( - RuntimeOrigin::signed(Bob.into()), - 1, - ), + EvmForeignAssets::unfreeze_foreign_asset(RuntimeOrigin::signed(Bob.into()), 1,), sp_runtime::DispatchError::BadOrigin ); - }); } @@ -191,47 +185,48 @@ fn test_regular_user_cannot_call_some_extrinsics() { fn test_root_can_change_foreign_asset_for_asset_id() { ExtBuilder::default() .with_balances(vec![(Alice.into(), 1_000)]) - .build().execute_with(|| { - assert_ok!(EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::signed(Alice.into()), - 1, - Location::parent(), - 18, - encode_ticker("MTT"), - encode_token_name("Mytoken"), - )); + .build() + .execute_with(|| { + assert_ok!(EvmForeignAssets::create_foreign_asset( + RuntimeOrigin::signed(Alice.into()), + 1, + Location::parent(), + 18, + encode_ticker("MTT"), + encode_token_name("Mytoken"), + )); - assert_ok!(EvmForeignAssets::change_xcm_location( - RuntimeOrigin::root(), - 1, - Location::here() - )); + assert_ok!(EvmForeignAssets::change_xcm_location( + RuntimeOrigin::root(), + 1, + Location::here() + )); - // New associations are stablished - assert_eq!(EvmForeignAssets::assets_by_id(1).unwrap(), Location::here()); - assert_eq!( - EvmForeignAssets::assets_by_location(Location::here()).unwrap(), - (1, AssetStatus::Active), - ); + // New associations are stablished + assert_eq!(EvmForeignAssets::assets_by_id(1).unwrap(), Location::here()); + assert_eq!( + EvmForeignAssets::assets_by_location(Location::here()).unwrap(), + (1, AssetStatus::Active), + ); - // Old ones are deleted - assert!(EvmForeignAssets::assets_by_location(Location::parent()).is_none()); + // Old ones are deleted + assert!(EvmForeignAssets::assets_by_location(Location::parent()).is_none()); - expect_events(vec![ - crate::Event::ForeignAssetCreated { - contract_address: H160([ - 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, - ]), - asset_id: 1, - xcm_location: Location::parent(), - deposit: Some(ForeignAssetCreationDeposit::get()), - }, - crate::Event::ForeignAssetXcmLocationChanged { - asset_id: 1, - new_xcm_location: Location::here(), - }, - ]) - }); + expect_events(vec![ + crate::Event::ForeignAssetCreated { + contract_address: H160([ + 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + ]), + asset_id: 1, + xcm_location: Location::parent(), + deposit: Some(ForeignAssetCreationDeposit::get()), + }, + crate::Event::ForeignAssetXcmLocationChanged { + asset_id: 1, + new_xcm_location: Location::here(), + }, + ]) + }); } #[test] @@ -248,42 +243,43 @@ fn test_asset_id_non_existent_error() { fn test_location_already_exist_error() { ExtBuilder::default() .with_balances(vec![(Alice.into(), 1_000)]) - .build().execute_with(|| { - // Setup: create a first foreign asset taht we will try to override - assert_ok!(EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::from(Some(Alice.into())), - 1, - Location::parent(), - 18, - encode_ticker("MTT"), - encode_token_name("Mytoken"), - )); - - assert_noop!( - EvmForeignAssets::create_foreign_asset( + .build() + .execute_with(|| { + // Setup: create a first foreign asset taht we will try to override + assert_ok!(EvmForeignAssets::create_foreign_asset( RuntimeOrigin::from(Some(Alice.into())), - 2, + 1, Location::parent(), 18, encode_ticker("MTT"), encode_token_name("Mytoken"), - ), - Error::::LocationAlreadyExists - ); + )); - // Setup: create a second foreign asset that will try to override the first one - assert_ok!(EvmForeignAssets::create_foreign_asset( - RuntimeOrigin::from(Some(Alice.into())), - 2, - Location::new(2, *&[]), - 18, - encode_ticker("MTT"), - encode_token_name("Mytoken"), - )); + assert_noop!( + EvmForeignAssets::create_foreign_asset( + RuntimeOrigin::from(Some(Alice.into())), + 2, + Location::parent(), + 18, + encode_ticker("MTT"), + encode_token_name("Mytoken"), + ), + Error::::LocationAlreadyExists + ); - assert_noop!( - EvmForeignAssets::change_xcm_location(RuntimeOrigin::root(), 2, Location::parent()), - Error::::LocationAlreadyExists - ); - }); + // Setup: create a second foreign asset that will try to override the first one + assert_ok!(EvmForeignAssets::create_foreign_asset( + RuntimeOrigin::from(Some(Alice.into())), + 2, + Location::new(2, *&[]), + 18, + encode_ticker("MTT"), + encode_token_name("Mytoken"), + )); + + assert_noop!( + EvmForeignAssets::change_xcm_location(RuntimeOrigin::root(), 2, Location::parent()), + Error::::LocationAlreadyExists + ); + }); } From 80d5ecb22a8505eef2c4a68dc6a9b83b3fc55229 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Wed, 8 Jan 2025 00:41:35 -0300 Subject: [PATCH 20/41] fix benchmarks --- .../moonbeam-foreign-assets/src/benchmarks.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/benchmarks.rs b/pallets/moonbeam-foreign-assets/src/benchmarks.rs index fa4dd3601d..b6bdcfe910 100644 --- a/pallets/moonbeam-foreign-assets/src/benchmarks.rs +++ b/pallets/moonbeam-foreign-assets/src/benchmarks.rs @@ -16,18 +16,27 @@ #![cfg(feature = "runtime-benchmarks")] -use crate::{AssetStatus, Call, Config, Pallet}; -use frame_benchmarking::{benchmarks, impl_benchmark_test_suite}; +use crate::{pallet, AssetStatus, Call, Config, Pallet}; +use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite}; use frame_support::pallet_prelude::*; +use frame_support::traits::Currency; use frame_system::RawOrigin; use sp_runtime::traits::ConstU32; use sp_runtime::BoundedVec; use xcm::latest::prelude::*; +fn create_funded_user(string: &'static str, n: u32, balance: u32) -> T::AccountId { + const SEED: u32 = 0; + let user = account(string, n, SEED); + let _ = ::Currency::make_free_balance_be(&user, balance.into()); + let _ = ::Currency::issue(balance.into()); + user +} fn create_n_foreign_asset(n: u32) -> DispatchResult { + let user: T::AccountId = create_funded_user::("user", n, 100); for i in 1..=n { Pallet::::create_foreign_asset( - RawOrigin::Root.into(), + RawOrigin::Signed(user.clone()).into(), i as u128, location_of(i), 18, @@ -53,7 +62,7 @@ benchmarks! { create_foreign_asset { create_n_foreign_asset::(T::MaxForeignAssets::get().saturating_sub(1))?; let asset_id = T::MaxForeignAssets::get() as u128; - }: _(RawOrigin::Root, asset_id, Location::parent(), 18, str_to_bv("MT"), str_to_bv("Mytoken")) + }: _(RawOrigin::Signed(create_funded_user::("user", 1, 100)), asset_id, Location::parent(), 18, str_to_bv("MT"), str_to_bv("Mytoken")) verify { assert_eq!( Pallet::::assets_by_id(asset_id), From a9216fc64af2fa3a7c8dbcd2474269e84dba2359 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Wed, 8 Jan 2025 01:04:34 -0300 Subject: [PATCH 21/41] format --- pallets/moonbeam-foreign-assets/src/benchmarks.rs | 4 ++-- test/helpers/assets.ts | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/benchmarks.rs b/pallets/moonbeam-foreign-assets/src/benchmarks.rs index b6bdcfe910..92d8d1f894 100644 --- a/pallets/moonbeam-foreign-assets/src/benchmarks.rs +++ b/pallets/moonbeam-foreign-assets/src/benchmarks.rs @@ -28,8 +28,8 @@ use xcm::latest::prelude::*; fn create_funded_user(string: &'static str, n: u32, balance: u32) -> T::AccountId { const SEED: u32 = 0; let user = account(string, n, SEED); - let _ = ::Currency::make_free_balance_be(&user, balance.into()); - let _ = ::Currency::issue(balance.into()); + let _ = ::Currency::make_free_balance_be(&user, balance.into()); + let _ = ::Currency::issue(balance.into()); user } fn create_n_foreign_asset(n: u32) -> DispatchResult { diff --git a/test/helpers/assets.ts b/test/helpers/assets.ts index c46d1c3c7b..109abeb6ae 100644 --- a/test/helpers/assets.ts +++ b/test/helpers/assets.ts @@ -404,10 +404,10 @@ export async function registerForeignAsset( context .polkadotJs() .tx.sudo.sudoAs( - alith.address, - context - .polkadotJs() - .tx.evmForeignAssets.createForeignAsset(assetId, xcmLoc, decimals, symbol, name) + alith.address, + context + .polkadotJs() + .tx.evmForeignAssets.createForeignAsset(assetId, xcmLoc, decimals, symbol, name) ) ); From 2ae2dd48c11489e0384ef3ce3493a6746c789974 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Wed, 8 Jan 2025 09:43:00 -0300 Subject: [PATCH 22/41] Update test/helpers/assets.ts Co-authored-by: Rodrigo Quelhas <22591718+RomarQ@users.noreply.github.com> --- test/helpers/assets.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/test/helpers/assets.ts b/test/helpers/assets.ts index 109abeb6ae..67e7263784 100644 --- a/test/helpers/assets.ts +++ b/test/helpers/assets.ts @@ -403,11 +403,7 @@ export async function registerForeignAsset( const { result } = await context.createBlock( context .polkadotJs() - .tx.sudo.sudoAs( - alith.address, - context - .polkadotJs() - .tx.evmForeignAssets.createForeignAsset(assetId, xcmLoc, decimals, symbol, name) + .tx.evmForeignAssets.createForeignAsset(assetId, xcmLoc, decimals, symbol, name) ) ); From 77ecd67ef2eaf5ec0d6e5823063fc59e72793cf1 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Wed, 8 Jan 2025 10:19:32 -0300 Subject: [PATCH 23/41] fix call --- test/helpers/assets.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/test/helpers/assets.ts b/test/helpers/assets.ts index 67e7263784..2c05897458 100644 --- a/test/helpers/assets.ts +++ b/test/helpers/assets.ts @@ -404,7 +404,6 @@ export async function registerForeignAsset( context .polkadotJs() .tx.evmForeignAssets.createForeignAsset(assetId, xcmLoc, decimals, symbol, name) - ) ); // Fetch the relevant event From aaab2553c91a5206f00cb6be8f8329738fd63e40 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Wed, 8 Jan 2025 12:37:41 -0300 Subject: [PATCH 24/41] add UNITS multiplier --- runtime/moonbase/src/runtime_params.rs | 2 +- runtime/moonbase/src/xcm_config.rs | 2 +- runtime/moonbeam/src/runtime_params.rs | 2 +- runtime/moonbeam/src/xcm_config.rs | 2 +- runtime/moonriver/src/runtime_params.rs | 2 +- runtime/moonriver/src/xcm_config.rs | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/runtime/moonbase/src/runtime_params.rs b/runtime/moonbase/src/runtime_params.rs index b9739ae160..8d4dfc36af 100644 --- a/runtime/moonbase/src/runtime_params.rs +++ b/runtime/moonbase/src/runtime_params.rs @@ -47,7 +47,7 @@ pub mod dynamic_params { #[codec(index = 2)] pub mod xcm_config { #[codec(index = 0)] - pub static ForeignAssetCreationDeposit: u64 = 100; + pub static ForeignAssetCreationDeposit: u128 = 100 * currency::UNIT; } } diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index 5c2e03b30b..5dc0f08a5f 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -698,7 +698,7 @@ impl frame_support::traits::Contains for EvmForeignAssetIdFilter { parameter_types! { /// Balance in the native currency that will be reserved from the user /// to create a new foreign asset - pub ForeignAssetCreationDeposit: u64 = + pub ForeignAssetCreationDeposit: u128 = runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } diff --git a/runtime/moonbeam/src/runtime_params.rs b/runtime/moonbeam/src/runtime_params.rs index 60eb625d6e..75cae97bb8 100644 --- a/runtime/moonbeam/src/runtime_params.rs +++ b/runtime/moonbeam/src/runtime_params.rs @@ -47,7 +47,7 @@ pub mod dynamic_params { #[codec(index = 2)] pub mod xcm_config { #[codec(index = 0)] - pub static ForeignAssetCreationDeposit: u64 = 10_000; + pub static ForeignAssetCreationDeposit: u128 = 10_000 * currency::GLMR; } } diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index fc705d51b7..eec71dfd24 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -691,7 +691,7 @@ pub type ForeignAssetManagerOrigin = EitherOfDiverse< parameter_types! { /// Balance in the native currency that will be reserved from the user /// to create a new foreign asset - pub ForeignAssetCreationDeposit: u64 = + pub ForeignAssetCreationDeposit: u128 = runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } diff --git a/runtime/moonriver/src/runtime_params.rs b/runtime/moonriver/src/runtime_params.rs index e4ce48c77e..e57f5f9cc6 100644 --- a/runtime/moonriver/src/runtime_params.rs +++ b/runtime/moonriver/src/runtime_params.rs @@ -47,7 +47,7 @@ pub mod dynamic_params { #[codec(index = 2)] pub mod xcm_config { #[codec(index = 0)] - pub static ForeignAssetCreationDeposit: u64 = 1_000; + pub static ForeignAssetCreationDeposit: u128 = 100 * currency::MOVR; } } diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index 0bb0d88790..d5d3eaad7b 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -696,7 +696,7 @@ impl frame_support::traits::Contains for EvmForeignAssetIdFilter { parameter_types! { /// Balance in the native currency that will be reserved from the user /// to create a new foreign asset - pub ForeignAssetCreationDeposit: u64 = + pub ForeignAssetCreationDeposit: u128 = runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } From 1424ca36cd4064a94bae288d9152e0f70b561ec5 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Wed, 8 Jan 2025 16:02:53 -0300 Subject: [PATCH 25/41] rollback sudo --- test/helpers/assets.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/helpers/assets.ts b/test/helpers/assets.ts index 2c05897458..c1bff9be8c 100644 --- a/test/helpers/assets.ts +++ b/test/helpers/assets.ts @@ -399,11 +399,12 @@ export async function registerForeignAsset( // Sanitize Xcm Location const xcmLoc = patchLocationV4recursively(xcmLocation); - + const api = context.polkadotJs(); const { result } = await context.createBlock( - context - .polkadotJs() - .tx.evmForeignAssets.createForeignAsset(assetId, xcmLoc, decimals, symbol, name) + api.tx.sudo.sudoAs( + alith.address, + api.tx.evmForeignAssets.createForeignAsset(assetId, xcmLoc, decimals, symbol, name) + ) ); // Fetch the relevant event From 2dfd940db2dbc52425cb6ba2571aa1b482c456d4 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Wed, 8 Jan 2025 16:03:41 -0300 Subject: [PATCH 26/41] expect balance diff --- .../test-assets/test-foreign-assets-change-xcm-location.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/suites/dev/moonbase/test-assets/test-foreign-assets-change-xcm-location.ts b/test/suites/dev/moonbase/test-assets/test-foreign-assets-change-xcm-location.ts index 0fa325ce36..e2ea2ed280 100644 --- a/test/suites/dev/moonbase/test-assets/test-foreign-assets-change-xcm-location.ts +++ b/test/suites/dev/moonbase/test-assets/test-foreign-assets-change-xcm-location.ts @@ -26,7 +26,9 @@ describeSuite({ ); assetId = registeredAssetId; - await verifyLatestBlockFees(context); + // Expect a balance diff after creating an asset due to the deposit + let assetCreationDeposit = 100; + await verifyLatestBlockFees(context, BigInt(assetCreationDeposit)); }); it({ From c5432156794c39bf1ad8b6da074eaf49c125c2ca Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Wed, 8 Jan 2025 16:26:55 -0300 Subject: [PATCH 27/41] remove unused weights --- pallets/moonbeam-foreign-assets/src/weights.rs | 8 -------- .../src/weights/pallet_moonbeam_foreign_assets.rs | 4 ---- .../src/weights/pallet_moonbeam_foreign_assets.rs | 4 ---- .../src/weights/pallet_moonbeam_foreign_assets.rs | 4 ---- 4 files changed, 20 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/weights.rs b/pallets/moonbeam-foreign-assets/src/weights.rs index b627c14f75..c2797d494b 100644 --- a/pallets/moonbeam-foreign-assets/src/weights.rs +++ b/pallets/moonbeam-foreign-assets/src/weights.rs @@ -52,7 +52,6 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_foreign_asset_creator. pub trait WeightInfo { fn create_foreign_asset() -> Weight; - fn create_foreign_asset_reserve() -> Weight; fn change_xcm_location() -> Weight; fn freeze_foreign_asset() -> Weight; fn unfreeze_foreign_asset() -> Weight; @@ -77,9 +76,6 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().writes(3_u64)) } - fn create_foreign_asset_reserve() -> Weight { - Weight::default() - } /// Storage: `ForeignAssetsCreator::AssetIdToForeignAsset` (r:1 w:1) /// Proof: `ForeignAssetsCreator::AssetIdToForeignAsset` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -182,8 +178,4 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } - - fn create_foreign_asset_reserve() -> Weight { - Weight::default() - } } diff --git a/runtime/moonbase/src/weights/pallet_moonbeam_foreign_assets.rs b/runtime/moonbase/src/weights/pallet_moonbeam_foreign_assets.rs index b061b649a1..a164942619 100644 --- a/runtime/moonbase/src/weights/pallet_moonbeam_foreign_assets.rs +++ b/runtime/moonbase/src/weights/pallet_moonbeam_foreign_assets.rs @@ -170,8 +170,4 @@ impl pallet_moonbeam_foreign_assets::WeightInfo for Wei .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } - - fn create_foreign_asset_reserve() -> Weight { - Weight::default() - } } diff --git a/runtime/moonbeam/src/weights/pallet_moonbeam_foreign_assets.rs b/runtime/moonbeam/src/weights/pallet_moonbeam_foreign_assets.rs index ff039f3e1b..2daa581cd4 100644 --- a/runtime/moonbeam/src/weights/pallet_moonbeam_foreign_assets.rs +++ b/runtime/moonbeam/src/weights/pallet_moonbeam_foreign_assets.rs @@ -170,8 +170,4 @@ impl pallet_moonbeam_foreign_assets::WeightInfo for Wei .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } - - fn create_foreign_asset_reserve() -> Weight { - Weight::default() - } } diff --git a/runtime/moonriver/src/weights/pallet_moonbeam_foreign_assets.rs b/runtime/moonriver/src/weights/pallet_moonbeam_foreign_assets.rs index ff039f3e1b..2daa581cd4 100644 --- a/runtime/moonriver/src/weights/pallet_moonbeam_foreign_assets.rs +++ b/runtime/moonriver/src/weights/pallet_moonbeam_foreign_assets.rs @@ -170,8 +170,4 @@ impl pallet_moonbeam_foreign_assets::WeightInfo for Wei .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } - - fn create_foreign_asset_reserve() -> Weight { - Weight::default() - } } From f1dba45af15c4259ed281d705ff09cc32401dc1b Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Wed, 8 Jan 2025 17:28:59 -0300 Subject: [PATCH 28/41] lint --- .../test-assets/test-foreign-assets-change-xcm-location.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/suites/dev/moonbase/test-assets/test-foreign-assets-change-xcm-location.ts b/test/suites/dev/moonbase/test-assets/test-foreign-assets-change-xcm-location.ts index e2ea2ed280..e083f4a120 100644 --- a/test/suites/dev/moonbase/test-assets/test-foreign-assets-change-xcm-location.ts +++ b/test/suites/dev/moonbase/test-assets/test-foreign-assets-change-xcm-location.ts @@ -27,7 +27,7 @@ describeSuite({ assetId = registeredAssetId; // Expect a balance diff after creating an asset due to the deposit - let assetCreationDeposit = 100; + const assetCreationDeposit = 100; await verifyLatestBlockFees(context, BigInt(assetCreationDeposit)); }); From a68bb12814f73dde5f7da7ff03f3e0a8177d4f50 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Fri, 10 Jan 2025 10:18:41 -0300 Subject: [PATCH 29/41] remove typeinfo bound as already computed --- pallets/moonbeam-foreign-assets/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index d2758aef3f..f5e1d77e75 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -260,13 +260,13 @@ pub mod pallet { StorageMap<_, Blake2_128Concat, AssetId, AssetCreationDetails>; #[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] - pub enum AssetOwner { + pub enum AssetOwner { Governance, Account(T::AccountId), } #[derive(Clone, Decode, Encode, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)] - pub struct AssetCreationDetails { + pub struct AssetCreationDetails { pub owner: AssetOwner, pub deposit: Option>, } From 251497f0009828edb3f8643ae8323e2c6f28bea1 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Mon, 13 Jan 2025 18:57:06 -0300 Subject: [PATCH 30/41] Add custom origin that ensures only XCM origins, which contain a certain location --- runtime/moonbase/src/foreign_origin.rs | 29 +++++++++++++++++++++++++ runtime/moonbase/src/lib.rs | 2 ++ runtime/moonbeam/src/foreign_origin.rs | 29 +++++++++++++++++++++++++ runtime/moonbeam/src/lib.rs | 1 + runtime/moonriver/src/foreign_origin.rs | 29 +++++++++++++++++++++++++ runtime/moonriver/src/lib.rs | 1 + 6 files changed, 91 insertions(+) create mode 100644 runtime/moonbase/src/foreign_origin.rs create mode 100644 runtime/moonbeam/src/foreign_origin.rs create mode 100644 runtime/moonriver/src/foreign_origin.rs diff --git a/runtime/moonbase/src/foreign_origin.rs b/runtime/moonbase/src/foreign_origin.rs new file mode 100644 index 0000000000..473ff53254 --- /dev/null +++ b/runtime/moonbase/src/foreign_origin.rs @@ -0,0 +1,29 @@ +use crate::xcm_config::LocationToAccountId; +use crate::RuntimeOrigin; +use frame_support::traits::{EnsureOrigin, EnsureOriginWithArg, Everything}; +use moonbeam_core_primitives::AccountId; +use xcm::latest::Location; +use xcm_executor::traits::ConvertLocation; + +// `EnsureOriginWithArg` impl for `ForeignAssetOwnerOrigin` which allows only XCM origins +// which are locations containing the class location. +pub struct ForeignAssetOwnerOrigin; +impl EnsureOriginWithArg for ForeignAssetOwnerOrigin { + type Success = AccountId; + + fn try_origin( + o: RuntimeOrigin, + a: &Location, + ) -> core::result::Result { + let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone())?; + if !a.starts_with(&origin_location) { + return Err(o); + } + LocationToAccountId::convert_location(&origin_location).ok_or(o) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin(a: &Location) -> Result { + Ok(pallet_xcm::Origin::Xcm(a.clone()).into()) + } +} diff --git a/runtime/moonbase/src/lib.rs b/runtime/moonbase/src/lib.rs index 073da4d764..ebd6ded9dd 100644 --- a/runtime/moonbase/src/lib.rs +++ b/runtime/moonbase/src/lib.rs @@ -130,7 +130,9 @@ pub use sp_runtime::BuildStorage; pub type Precompiles = MoonbasePrecompiles; +pub mod foreign_origin; mod weights; + pub(crate) use weights as moonbase_weights; /// UNIT, the native token, uses 18 decimals of precision. diff --git a/runtime/moonbeam/src/foreign_origin.rs b/runtime/moonbeam/src/foreign_origin.rs new file mode 100644 index 0000000000..473ff53254 --- /dev/null +++ b/runtime/moonbeam/src/foreign_origin.rs @@ -0,0 +1,29 @@ +use crate::xcm_config::LocationToAccountId; +use crate::RuntimeOrigin; +use frame_support::traits::{EnsureOrigin, EnsureOriginWithArg, Everything}; +use moonbeam_core_primitives::AccountId; +use xcm::latest::Location; +use xcm_executor::traits::ConvertLocation; + +// `EnsureOriginWithArg` impl for `ForeignAssetOwnerOrigin` which allows only XCM origins +// which are locations containing the class location. +pub struct ForeignAssetOwnerOrigin; +impl EnsureOriginWithArg for ForeignAssetOwnerOrigin { + type Success = AccountId; + + fn try_origin( + o: RuntimeOrigin, + a: &Location, + ) -> core::result::Result { + let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone())?; + if !a.starts_with(&origin_location) { + return Err(o); + } + LocationToAccountId::convert_location(&origin_location).ok_or(o) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin(a: &Location) -> Result { + Ok(pallet_xcm::Origin::Xcm(a.clone()).into()) + } +} diff --git a/runtime/moonbeam/src/lib.rs b/runtime/moonbeam/src/lib.rs index b5816bede2..41e7aa63ed 100644 --- a/runtime/moonbeam/src/lib.rs +++ b/runtime/moonbeam/src/lib.rs @@ -122,6 +122,7 @@ pub use sp_runtime::BuildStorage; pub type Precompiles = MoonbeamPrecompiles; pub mod asset_config; +mod foreign_origin; pub mod governance; pub mod runtime_params; mod weights; diff --git a/runtime/moonriver/src/foreign_origin.rs b/runtime/moonriver/src/foreign_origin.rs new file mode 100644 index 0000000000..473ff53254 --- /dev/null +++ b/runtime/moonriver/src/foreign_origin.rs @@ -0,0 +1,29 @@ +use crate::xcm_config::LocationToAccountId; +use crate::RuntimeOrigin; +use frame_support::traits::{EnsureOrigin, EnsureOriginWithArg, Everything}; +use moonbeam_core_primitives::AccountId; +use xcm::latest::Location; +use xcm_executor::traits::ConvertLocation; + +// `EnsureOriginWithArg` impl for `ForeignAssetOwnerOrigin` which allows only XCM origins +// which are locations containing the class location. +pub struct ForeignAssetOwnerOrigin; +impl EnsureOriginWithArg for ForeignAssetOwnerOrigin { + type Success = AccountId; + + fn try_origin( + o: RuntimeOrigin, + a: &Location, + ) -> core::result::Result { + let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone())?; + if !a.starts_with(&origin_location) { + return Err(o); + } + LocationToAccountId::convert_location(&origin_location).ok_or(o) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin(a: &Location) -> Result { + Ok(pallet_xcm::Origin::Xcm(a.clone()).into()) + } +} diff --git a/runtime/moonriver/src/lib.rs b/runtime/moonriver/src/lib.rs index 47e564ea5a..693e91daf4 100644 --- a/runtime/moonriver/src/lib.rs +++ b/runtime/moonriver/src/lib.rs @@ -125,6 +125,7 @@ pub mod governance; pub mod runtime_params; pub mod xcm_config; +mod foreign_origin; mod migrations; mod precompiles; mod weights; From 5e62ad1aaf5360a474280f63b1c2cf4d74ade824 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Mon, 13 Jan 2025 18:57:37 -0300 Subject: [PATCH 31/41] modify foreign assets origin to use ForeignAssetOwnerOrigin --- pallets/moonbeam-foreign-assets/src/lib.rs | 25 ++++++++++++++-------- runtime/moonbase/src/xcm_config.rs | 22 ++++++++----------- runtime/moonbeam/src/xcm_config.rs | 10 +++------ runtime/moonriver/src/xcm_config.rs | 14 +++++------- 4 files changed, 33 insertions(+), 38 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index f5e1d77e75..4566ef9d1e 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -107,7 +107,7 @@ pub enum AssetStatus { #[pallet] pub mod pallet { use super::*; - use frame_support::traits::{Currency, ReservableCurrency}; + use frame_support::traits::{Currency, EnsureOriginWithArg, ReservableCurrency}; use pallet_evm::{GasWeightMapping, Runner}; use sp_runtime::traits::{AccountIdConversion, AtLeast32BitUnsigned, Convert}; use xcm_executor::traits::ConvertLocation; @@ -133,17 +133,17 @@ pub mod pallet { type EvmRunner: Runner; /// Origin that is allowed to create a new foreign assets - type ForeignAssetCreatorOrigin: EnsureOrigin; + type ForeignAssetCreatorOrigin: EnsureOriginWithArg; /// Origin that is allowed to freeze all tokens of a foreign asset - type ForeignAssetFreezerOrigin: EnsureOrigin; + type ForeignAssetFreezerOrigin: EnsureOriginWithArg; /// Origin that is allowed to modify asset information for foreign assets - type ForeignAssetModifierOrigin: EnsureOrigin; + type ForeignAssetModifierOrigin: EnsureOriginWithArg; /// Origin that is allowed to unfreeze all tokens of a foreign asset that was previously /// frozen - type ForeignAssetUnfreezerOrigin: EnsureOrigin; + type ForeignAssetUnfreezerOrigin: EnsureOriginWithArg; /// Hook to be called when new foreign asset is registered. type OnForeignAssetCreated: ForeignAssetCreatedHook; @@ -410,7 +410,7 @@ pub mod pallet { symbol: BoundedVec>, name: BoundedVec>, ) -> DispatchResult { - T::ForeignAssetCreatorOrigin::ensure_origin(origin.clone())?; + T::ForeignAssetCreatorOrigin::ensure_origin(origin.clone(), &xcm_location)?; // Ensure such an assetId does not exist ensure!( @@ -478,7 +478,8 @@ pub mod pallet { asset_id: AssetId, new_xcm_location: Location, ) -> DispatchResult { - T::ForeignAssetModifierOrigin::ensure_origin(origin)?; + // Ensures that the origin is an XCM location that contains the asset + T::ForeignAssetModifierOrigin::ensure_origin(origin, &new_xcm_location)?; let previous_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; @@ -511,11 +512,15 @@ pub mod pallet { asset_id: AssetId, allow_xcm_deposit: bool, ) -> DispatchResult { - T::ForeignAssetFreezerOrigin::ensure_origin(origin)?; + ensure_signed(origin.clone())?; let xcm_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; + // Ensures that the origin is an XCM location that owns the asset + // represented by the assets xcm location + T::ForeignAssetFreezerOrigin::ensure_origin(origin, &xcm_location)?; + let (_asset_id, asset_status) = AssetsByLocation::::get(&xcm_location) .ok_or(Error::::CorruptedStorageOrphanLocation)?; @@ -545,10 +550,12 @@ pub mod pallet { #[pallet::call_index(3)] #[pallet::weight(::WeightInfo::unfreeze_foreign_asset())] pub fn unfreeze_foreign_asset(origin: OriginFor, asset_id: AssetId) -> DispatchResult { - T::ForeignAssetUnfreezerOrigin::ensure_origin(origin)?; + ensure_signed(origin.clone())?; let xcm_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; + // Ensures that the origin is an XCM location that contains the asset + T::ForeignAssetUnfreezerOrigin::ensure_origin(origin, &xcm_location)?; let (_asset_id, asset_status) = AssetsByLocation::::get(&xcm_location) .ok_or(Error::::CorruptedStorageOrphanLocation)?; diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index 5dc0f08a5f..a6fd8dc22e 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -36,7 +36,7 @@ use frame_support::{ traits::{EitherOfDiverse, Everything, Nothing, PalletInfoAccess, TransformOrigin}, }; -use frame_system::{EnsureRoot, EnsureSigned, RawOrigin}; +use frame_system::{EnsureRoot, RawOrigin}; use sp_core::{ConstU32, H160, H256}; use sp_weights::Weight; use xcm_builder::{ @@ -67,14 +67,14 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; +use crate::foreign_origin::ForeignAssetOwnerOrigin; +use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; use sp_core::Get; use sp_std::{ convert::{From, Into, TryFrom}, prelude::*, }; -use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; - parameter_types! { // The network Id of the relay pub const RelayNetwork: NetworkId = NetworkId::Westend; @@ -98,8 +98,9 @@ parameter_types! { } /// Type for specifying how a `Location` can be converted into an `AccountId`. This is used -/// when determining ownership of accounts for asset transacting and when attempting to use XCM -/// `Transact` in order to determine the dispatch Origin. +/// when determining ownership of accounts for asset transacting, when attempting to use XCM +/// `Transact` in order to determine the dispatch Origin, and when validating foreign assets +/// creation and ownership through the moonbeam_foreign_assets pallet. pub type LocationToAccountId = ( // The parent (Relay-chain) origin converts to the default `AccountId`. ParentIsPreset, @@ -702,19 +703,14 @@ parameter_types! { runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } -pub type ForeignAssetManagerOrigin = EitherOfDiverse< - EnsureRoot, - EitherOfDiverse< - pallet_collective::EnsureProportionMoreThan, - governance::custom_origins::FastGeneralAdmin, - >, ->; +pub type ForeignAssetManagerOrigin = + EitherOfDiverse, ForeignAssetOwnerOrigin>; impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = EnsureSigned; + type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin; type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin; type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin; type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin; diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index eec71dfd24..b9c5641481 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -66,6 +66,7 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; +use crate::foreign_origin::ForeignAssetOwnerOrigin; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; use sp_core::Get; use sp_std::{ @@ -680,13 +681,8 @@ impl frame_support::traits::Contains for EvmForeignAssetIdFilter { } } -pub type ForeignAssetManagerOrigin = EitherOfDiverse< - EnsureRoot, - EitherOfDiverse< - pallet_collective::EnsureProportionMoreThan, - governance::custom_origins::FastGeneralAdmin, - >, ->; +pub type ForeignAssetManagerOrigin = + EitherOfDiverse, ForeignAssetOwnerOrigin>; parameter_types! { /// Balance in the native currency that will be reserved from the user diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index d5d3eaad7b..502799a8b2 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -36,7 +36,7 @@ use sp_runtime::{ }; use sp_weights::Weight; -use frame_system::{EnsureRoot, EnsureSigned, RawOrigin}; +use frame_system::{EnsureRoot, RawOrigin}; use sp_core::{ConstU32, H160, H256}; use xcm_builder::{ @@ -66,6 +66,7 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; +use crate::foreign_origin::ForeignAssetOwnerOrigin; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; use sp_core::Get; use sp_std::{ @@ -700,19 +701,14 @@ parameter_types! { runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } -pub type ForeignAssetManagerOrigin = EitherOfDiverse< - EnsureRoot, - EitherOfDiverse< - pallet_collective::EnsureProportionMoreThan, - governance::custom_origins::FastGeneralAdmin, - >, ->; +pub type ForeignAssetManagerOrigin = + EitherOfDiverse, ForeignAssetOwnerOrigin>; impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = EnsureSigned; + type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin; type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin; type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin; type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin; From 8709f571a566446f8d6337f26d955e3be693d97f Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Mon, 13 Jan 2025 22:34:30 -0300 Subject: [PATCH 32/41] remove Root as possible origin --- runtime/moonbase/src/xcm_config.rs | 11 ++++------- runtime/moonbeam/src/xcm_config.rs | 19 ++++++++----------- runtime/moonriver/src/xcm_config.rs | 11 ++++------- 3 files changed, 16 insertions(+), 25 deletions(-) diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index a6fd8dc22e..ffd7fe1cb6 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -703,17 +703,14 @@ parameter_types! { runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } -pub type ForeignAssetManagerOrigin = - EitherOfDiverse, ForeignAssetOwnerOrigin>; - impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin; - type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin; - type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin; - type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin; + type ForeignAssetCreatorOrigin = ForeignAssetOwnerOrigin; + type ForeignAssetFreezerOrigin = ForeignAssetOwnerOrigin; + type ForeignAssetModifierOrigin = ForeignAssetOwnerOrigin; + type ForeignAssetUnfreezerOrigin = ForeignAssetOwnerOrigin; type OnForeignAssetCreated = (); type MaxForeignAssets = ConstU32<256>; type RuntimeEvent = RuntimeEvent; diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index b9c5641481..5eeb736915 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -36,7 +36,7 @@ use sp_runtime::{ }; use sp_weights::Weight; -use frame_system::{EnsureRoot, EnsureSigned, RawOrigin}; +use frame_system::{EnsureRoot, RawOrigin}; use sp_core::{ConstU32, H160, H256}; use xcm_builder::{ @@ -427,7 +427,7 @@ pub type ResumeXcmOrigin = EitherOfDiverse< impl pallet_emergency_para_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type CheckAssociatedRelayNumber = - cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; + cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; type QueuePausedQuery = (MaintenanceMode, NarrowOriginToSibling); type PausedThreshold = ConstU32<300>; type FastAuthorizeUpgradeOrigin = FastAuthorizeUpgradeOrigin; @@ -525,7 +525,7 @@ impl AccountIdToCurrencyId for Runtime { // How to convert from CurrencyId to Location pub struct CurrencyIdToLocation(sp_std::marker::PhantomData); impl sp_runtime::traits::Convert> - for CurrencyIdToLocation +for CurrencyIdToLocation where AssetXConverter: sp_runtime::traits::MaybeEquivalence, { @@ -618,7 +618,7 @@ impl XcmTransact for Transactors { } pub type DerivativeAddressRegistrationOrigin = - EitherOfDiverse, governance::custom_origins::GeneralAdmin>; +EitherOfDiverse, governance::custom_origins::GeneralAdmin>; impl pallet_xcm_transactor::Config for Runtime { type RuntimeEvent = RuntimeEvent; @@ -681,9 +681,6 @@ impl frame_support::traits::Contains for EvmForeignAssetIdFilter { } } -pub type ForeignAssetManagerOrigin = - EitherOfDiverse, ForeignAssetOwnerOrigin>; - parameter_types! { /// Balance in the native currency that will be reserved from the user /// to create a new foreign asset @@ -695,10 +692,10 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = EnsureSigned; - type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin; - type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin; - type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin; + type ForeignAssetCreatorOrigin = ForeignAssetOwnerOrigin; + type ForeignAssetFreezerOrigin = ForeignAssetOwnerOrigin; + type ForeignAssetModifierOrigin = ForeignAssetOwnerOrigin; + type ForeignAssetUnfreezerOrigin = ForeignAssetOwnerOrigin; type OnForeignAssetCreated = (); type MaxForeignAssets = ConstU32<256>; type RuntimeEvent = RuntimeEvent; diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index 502799a8b2..f0255d171e 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -701,17 +701,14 @@ parameter_types! { runtime_params::dynamic_params::xcm_config::ForeignAssetCreationDeposit::get(); } -pub type ForeignAssetManagerOrigin = - EitherOfDiverse, ForeignAssetOwnerOrigin>; - impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin; - type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin; - type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin; - type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin; + type ForeignAssetCreatorOrigin = ForeignAssetOwnerOrigin; + type ForeignAssetFreezerOrigin = ForeignAssetOwnerOrigin; + type ForeignAssetModifierOrigin = ForeignAssetOwnerOrigin; + type ForeignAssetUnfreezerOrigin = ForeignAssetOwnerOrigin; type OnForeignAssetCreated = (); type MaxForeignAssets = ConstU32<256>; type RuntimeEvent = RuntimeEvent; From 75d0acbb13132d006fc47013f9cd9c2c5a36e9a4 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Mon, 13 Jan 2025 22:34:49 -0300 Subject: [PATCH 33/41] get account from ensure_origin --- pallets/moonbeam-foreign-assets/src/lib.rs | 28 +++++++++++++++++----- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index 4566ef9d1e..ee15a6b5d9 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -133,17 +133,33 @@ pub mod pallet { type EvmRunner: Runner; /// Origin that is allowed to create a new foreign assets - type ForeignAssetCreatorOrigin: EnsureOriginWithArg; + type ForeignAssetCreatorOrigin: EnsureOriginWithArg< + Self::RuntimeOrigin, + Location, + Success = Self::AccountId, + >; /// Origin that is allowed to freeze all tokens of a foreign asset - type ForeignAssetFreezerOrigin: EnsureOriginWithArg; + type ForeignAssetFreezerOrigin: EnsureOriginWithArg< + Self::RuntimeOrigin, + Location, + Success = Self::AccountId, + >; /// Origin that is allowed to modify asset information for foreign assets - type ForeignAssetModifierOrigin: EnsureOriginWithArg; + type ForeignAssetModifierOrigin: EnsureOriginWithArg< + Self::RuntimeOrigin, + Location, + Success = Self::AccountId, + >; /// Origin that is allowed to unfreeze all tokens of a foreign asset that was previously /// frozen - type ForeignAssetUnfreezerOrigin: EnsureOriginWithArg; + type ForeignAssetUnfreezerOrigin: EnsureOriginWithArg< + Self::RuntimeOrigin, + Location, + Success = Self::AccountId, + >; /// Hook to be called when new foreign asset is registered. type OnForeignAssetCreated: ForeignAssetCreatedHook; @@ -410,7 +426,8 @@ pub mod pallet { symbol: BoundedVec>, name: BoundedVec>, ) -> DispatchResult { - T::ForeignAssetCreatorOrigin::ensure_origin(origin.clone(), &xcm_location)?; + let owner_account = + T::ForeignAssetCreatorOrigin::ensure_origin(origin.clone(), &xcm_location)?; // Ensure such an assetId does not exist ensure!( @@ -435,7 +452,6 @@ pub mod pallet { let symbol = core::str::from_utf8(&symbol).map_err(|_| Error::::InvalidSymbol)?; let name = core::str::from_utf8(&name).map_err(|_| Error::::InvalidTokenName)?; - let owner_account = ensure_signed(origin)?; let contract_address = EvmCaller::::erc20_create(asset_id, decimals, symbol, name)?; let deposit = T::ForeignAssetCreationDeposit::get(); let owner = AssetOwner::::Account(owner_account.clone()); From c24aa6713efd3cc76cdf20e19e737b8f191b6f2b Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Mon, 13 Jan 2025 22:36:57 -0300 Subject: [PATCH 34/41] format --- runtime/moonbeam/src/xcm_config.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index 5eeb736915..65214638d1 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -427,7 +427,7 @@ pub type ResumeXcmOrigin = EitherOfDiverse< impl pallet_emergency_para_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type CheckAssociatedRelayNumber = - cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; + cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; type QueuePausedQuery = (MaintenanceMode, NarrowOriginToSibling); type PausedThreshold = ConstU32<300>; type FastAuthorizeUpgradeOrigin = FastAuthorizeUpgradeOrigin; @@ -525,7 +525,7 @@ impl AccountIdToCurrencyId for Runtime { // How to convert from CurrencyId to Location pub struct CurrencyIdToLocation(sp_std::marker::PhantomData); impl sp_runtime::traits::Convert> -for CurrencyIdToLocation + for CurrencyIdToLocation where AssetXConverter: sp_runtime::traits::MaybeEquivalence, { @@ -618,7 +618,7 @@ impl XcmTransact for Transactors { } pub type DerivativeAddressRegistrationOrigin = -EitherOfDiverse, governance::custom_origins::GeneralAdmin>; + EitherOfDiverse, governance::custom_origins::GeneralAdmin>; impl pallet_xcm_transactor::Config for Runtime { type RuntimeEvent = RuntimeEvent; From 9a07cf71e905776f14ca44d89ecc3dc91295b941 Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Mon, 13 Jan 2025 22:46:06 -0300 Subject: [PATCH 35/41] copy --- runtime/moonbase/src/foreign_origin.rs | 16 ++++++++++++++++ runtime/moonbeam/src/foreign_origin.rs | 16 ++++++++++++++++ runtime/moonriver/src/foreign_origin.rs | 16 ++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/runtime/moonbase/src/foreign_origin.rs b/runtime/moonbase/src/foreign_origin.rs index 473ff53254..cdbade22d3 100644 --- a/runtime/moonbase/src/foreign_origin.rs +++ b/runtime/moonbase/src/foreign_origin.rs @@ -1,3 +1,19 @@ +// Copyright 2019-2022 PureStake Inc. +// This file is part of Moonbeam. + +// Moonbeam 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. + +// Moonbeam 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 Moonbeam. If not, see . + use crate::xcm_config::LocationToAccountId; use crate::RuntimeOrigin; use frame_support::traits::{EnsureOrigin, EnsureOriginWithArg, Everything}; diff --git a/runtime/moonbeam/src/foreign_origin.rs b/runtime/moonbeam/src/foreign_origin.rs index 473ff53254..cdbade22d3 100644 --- a/runtime/moonbeam/src/foreign_origin.rs +++ b/runtime/moonbeam/src/foreign_origin.rs @@ -1,3 +1,19 @@ +// Copyright 2019-2022 PureStake Inc. +// This file is part of Moonbeam. + +// Moonbeam 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. + +// Moonbeam 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 Moonbeam. If not, see . + use crate::xcm_config::LocationToAccountId; use crate::RuntimeOrigin; use frame_support::traits::{EnsureOrigin, EnsureOriginWithArg, Everything}; diff --git a/runtime/moonriver/src/foreign_origin.rs b/runtime/moonriver/src/foreign_origin.rs index 473ff53254..cdbade22d3 100644 --- a/runtime/moonriver/src/foreign_origin.rs +++ b/runtime/moonriver/src/foreign_origin.rs @@ -1,3 +1,19 @@ +// Copyright 2019-2022 PureStake Inc. +// This file is part of Moonbeam. + +// Moonbeam 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. + +// Moonbeam 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 Moonbeam. If not, see . + use crate::xcm_config::LocationToAccountId; use crate::RuntimeOrigin; use frame_support::traits::{EnsureOrigin, EnsureOriginWithArg, Everything}; From 4fd2e86c995ee499dc936349c092368ced238dfe Mon Sep 17 00:00:00 2001 From: Gonza Montiel Date: Mon, 13 Jan 2025 22:57:33 -0300 Subject: [PATCH 36/41] update mock --- pallets/moonbeam-foreign-assets/src/mock.rs | 24 +++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/mock.rs b/pallets/moonbeam-foreign-assets/src/mock.rs index c16b6980e5..08967b3e52 100644 --- a/pallets/moonbeam-foreign-assets/src/mock.rs +++ b/pallets/moonbeam-foreign-assets/src/mock.rs @@ -17,11 +17,11 @@ use super::*; use crate as pallet_moonbeam_foreign_assets; -use frame_support::traits::Everything; +use frame_support::traits::{EnsureOriginWithArg, Everything}; use frame_support::{construct_runtime, pallet_prelude::*, parameter_types}; -use frame_system::{EnsureRoot, EnsureSigned}; +use frame_system::EnsureSigned; use pallet_evm::{FrameSystemAccountProvider, SubstrateBlockHashMapping}; -use precompile_utils::testing::MockAccount; +use precompile_utils::testing::{Alice, MockAccount}; use sp_core::{H256, U256}; use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; use sp_runtime::BuildStorage; @@ -177,6 +177,18 @@ impl sp_runtime::traits::Convert for AccountIdToH160 { } } +pub struct ForeignAssetMockOrigin; +impl EnsureOriginWithArg for ForeignAssetMockOrigin { + type Success = AccountId; + + fn try_origin( + _: RuntimeOrigin, + _: &Location, + ) -> core::result::Result { + Ok(Alice.into()) + } +} + parameter_types! { pub const ForeignAssetCreationDeposit: u128 = 1; } @@ -186,9 +198,9 @@ impl crate::Config for Test { type AssetIdFilter = Everything; type EvmRunner = pallet_evm::runner::stack::Runner; type ForeignAssetCreatorOrigin = EnsureSigned; - type ForeignAssetFreezerOrigin = EnsureRoot; - type ForeignAssetModifierOrigin = EnsureRoot; - type ForeignAssetUnfreezerOrigin = EnsureRoot; + type ForeignAssetFreezerOrigin = EnsureSigned; + type ForeignAssetModifierOrigin = EnsureSigned; + type ForeignAssetUnfreezerOrigin = EnsureSigned; type OnForeignAssetCreated = NoteDownHook; type MaxForeignAssets = ConstU32<3>; type RuntimeEvent = RuntimeEvent; From cf918bfebc12581dd797656c7ad9e51ce1bb21fc Mon Sep 17 00:00:00 2001 From: Tarek Mohamed Abdalla Date: Wed, 22 Jan 2025 13:10:53 +0200 Subject: [PATCH 37/41] remove governance asset owner --- pallets/moonbeam-foreign-assets/src/lib.rs | 61 +++++++------------- pallets/moonbeam-foreign-assets/src/mock.rs | 17 ++++-- pallets/moonbeam-foreign-assets/src/tests.rs | 4 +- pallets/moonbeam-lazy-migrations/src/mock.rs | 20 +++++-- runtime/moonbase/src/foreign_origin.rs | 37 +++++++----- runtime/moonbase/src/xcm_config.rs | 7 +-- runtime/moonbeam/src/foreign_origin.rs | 37 +++++++----- runtime/moonbeam/src/xcm_config.rs | 7 +-- runtime/moonriver/src/foreign_origin.rs | 37 +++++++----- runtime/moonriver/src/xcm_config.rs | 8 +-- 10 files changed, 120 insertions(+), 115 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index ee15a6b5d9..29b69a525d 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -132,34 +132,8 @@ pub mod pallet { /// EVM runner type EvmRunner: Runner; - /// Origin that is allowed to create a new foreign assets - type ForeignAssetCreatorOrigin: EnsureOriginWithArg< - Self::RuntimeOrigin, - Location, - Success = Self::AccountId, - >; - - /// Origin that is allowed to freeze all tokens of a foreign asset - type ForeignAssetFreezerOrigin: EnsureOriginWithArg< - Self::RuntimeOrigin, - Location, - Success = Self::AccountId, - >; - - /// Origin that is allowed to modify asset information for foreign assets - type ForeignAssetModifierOrigin: EnsureOriginWithArg< - Self::RuntimeOrigin, - Location, - Success = Self::AccountId, - >; - - /// Origin that is allowed to unfreeze all tokens of a foreign asset that was previously - /// frozen - type ForeignAssetUnfreezerOrigin: EnsureOriginWithArg< - Self::RuntimeOrigin, - Location, - Success = Self::AccountId, - >; + /// Origin that is allowed to create new foreign assets + type EnsureXcmLocation: EnsureXcmLocation; /// Hook to be called when new foreign asset is registered. type OnForeignAssetCreated: ForeignAssetCreatedHook; @@ -216,6 +190,7 @@ pub mod pallet { /// Account has insufficient balance for locking InsufficientBalance, OriginIsNotAssetCreator, + CannotConvertLocationToAccount, InvalidSymbol, InvalidTokenName, LocationAlreadyExists, @@ -275,15 +250,9 @@ pub mod pallet { pub type AssetsCreationDetails = StorageMap<_, Blake2_128Concat, AssetId, AssetCreationDetails>; - #[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] - pub enum AssetOwner { - Governance, - Account(T::AccountId), - } - #[derive(Clone, Decode, Encode, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)] pub struct AssetCreationDetails { - pub owner: AssetOwner, + pub owner: T::AccountId, pub deposit: Option>, } @@ -338,7 +307,8 @@ pub mod pallet { let name = core::str::from_utf8(&name).map_err(|_| Error::::InvalidTokenName)?; let contract_address = EvmCaller::::erc20_create(asset_id, decimals, symbol, name)?; - let owner = AssetOwner::::Governance; + let owner = T::EnsureXcmLocation::account_for_location(&xcm_location) + .ok_or(Error::::CannotConvertLocationToAccount)?; // Insert the association assetId->foreigAsset // Insert the association foreigAsset->assetId @@ -427,7 +397,7 @@ pub mod pallet { name: BoundedVec>, ) -> DispatchResult { let owner_account = - T::ForeignAssetCreatorOrigin::ensure_origin(origin.clone(), &xcm_location)?; + T::EnsureXcmLocation::ensure_xcm_origin(origin.clone(), &xcm_location)?; // Ensure such an assetId does not exist ensure!( @@ -454,7 +424,7 @@ pub mod pallet { let name = core::str::from_utf8(&name).map_err(|_| Error::::InvalidTokenName)?; let contract_address = EvmCaller::::erc20_create(asset_id, decimals, symbol, name)?; let deposit = T::ForeignAssetCreationDeposit::get(); - let owner = AssetOwner::::Account(owner_account.clone()); + let owner = owner_account.clone(); // Insert the association assetId->foreigAsset // Insert the association foreigAsset->assetId @@ -495,7 +465,7 @@ pub mod pallet { new_xcm_location: Location, ) -> DispatchResult { // Ensures that the origin is an XCM location that contains the asset - T::ForeignAssetModifierOrigin::ensure_origin(origin, &new_xcm_location)?; + T::EnsureXcmLocation::ensure_xcm_origin(origin, &new_xcm_location)?; let previous_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; @@ -535,7 +505,7 @@ pub mod pallet { // Ensures that the origin is an XCM location that owns the asset // represented by the assets xcm location - T::ForeignAssetFreezerOrigin::ensure_origin(origin, &xcm_location)?; + T::EnsureXcmLocation::ensure_xcm_origin(origin, &xcm_location)?; let (_asset_id, asset_status) = AssetsByLocation::::get(&xcm_location) .ok_or(Error::::CorruptedStorageOrphanLocation)?; @@ -571,7 +541,7 @@ pub mod pallet { let xcm_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; // Ensures that the origin is an XCM location that contains the asset - T::ForeignAssetUnfreezerOrigin::ensure_origin(origin, &xcm_location)?; + T::EnsureXcmLocation::ensure_xcm_origin(origin, &xcm_location)?; let (_asset_id, asset_status) = AssetsByLocation::::get(&xcm_location) .ok_or(Error::::CorruptedStorageOrphanLocation)?; @@ -689,4 +659,13 @@ pub mod pallet { AssetsById::::get(asset_id) } } + + /// A trait to ensure that the origin is an XCM location that contains the asset + pub trait EnsureXcmLocation { + fn ensure_xcm_origin( + origin: T::RuntimeOrigin, + location: &Location, + ) -> Result; + fn account_for_location(location: &Location) -> Option; + } } diff --git a/pallets/moonbeam-foreign-assets/src/mock.rs b/pallets/moonbeam-foreign-assets/src/mock.rs index 08967b3e52..781775a3c6 100644 --- a/pallets/moonbeam-foreign-assets/src/mock.rs +++ b/pallets/moonbeam-foreign-assets/src/mock.rs @@ -193,14 +193,23 @@ parameter_types! { pub const ForeignAssetCreationDeposit: u128 = 1; } +pub struct ForeignAssetsEnsureXCM; + +impl EnsureXcmLocation for ForeignAssetsEnsureXCM { + fn ensure_xcm_origin(origin: RuntimeOrigin, location: &Location) -> Result { + ensure_signed(origin).map_err(|_| DispatchError::BadOrigin) + } + + fn account_for_location(location: &Location) -> Option { + Some(Alice.into()) + } +} + impl crate::Config for Test { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = Everything; type EvmRunner = pallet_evm::runner::stack::Runner; - type ForeignAssetCreatorOrigin = EnsureSigned; - type ForeignAssetFreezerOrigin = EnsureSigned; - type ForeignAssetModifierOrigin = EnsureSigned; - type ForeignAssetUnfreezerOrigin = EnsureSigned; + type EnsureXcmLocation = ForeignAssetsEnsureXCM; type OnForeignAssetCreated = NoteDownHook; type MaxForeignAssets = ConstU32<3>; type RuntimeEvent = RuntimeEvent; diff --git a/pallets/moonbeam-foreign-assets/src/tests.rs b/pallets/moonbeam-foreign-assets/src/tests.rs index 026351fae5..7c54e02e70 100644 --- a/pallets/moonbeam-foreign-assets/src/tests.rs +++ b/pallets/moonbeam-foreign-assets/src/tests.rs @@ -57,7 +57,7 @@ fn create_foreign_and_freeze_unfreeze() { assert_eq!( EvmForeignAssets::assets_creation_details(&1), Some(AssetCreationDetails { - owner: AssetOwner::Account(Alice.into()), + owner: Alice.into(), deposit: Some(ForeignAssetCreationDeposit::get()) }) ); @@ -85,7 +85,7 @@ fn create_foreign_and_freeze_unfreeze() { assert_eq!( EvmForeignAssets::assets_creation_details(&1), Some(AssetCreationDetails { - owner: AssetOwner::Account(Alice.into()), + owner: Alice.into(), deposit: Some(1) }) ); diff --git a/pallets/moonbeam-lazy-migrations/src/mock.rs b/pallets/moonbeam-lazy-migrations/src/mock.rs index fea4aabe36..4bd752bcdc 100644 --- a/pallets/moonbeam-lazy-migrations/src/mock.rs +++ b/pallets/moonbeam-lazy-migrations/src/mock.rs @@ -24,12 +24,13 @@ use frame_support::{construct_runtime, parameter_types, traits::Everything, weig use frame_system::{EnsureRoot, EnsureSigned}; use pallet_asset_manager::AssetRegistrar; use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider}; -use precompile_utils::testing::MockAccount; +use precompile_utils::testing::{Alice, MockAccount}; use sp_core::{ConstU32, H160, H256, U256}; use sp_runtime::{ traits::{BlakeTwo256, Hash, IdentityLookup}, BuildStorage, Perbill, }; +use pallet_moonbeam_foreign_assets::EnsureXcmLocation; pub type AssetId = u128; pub type Balance = u128; @@ -288,14 +289,23 @@ impl sp_runtime::traits::Convert for AccountIdToH160 { } } +pub struct ForeignAssetsEnsureXCM; + +impl EnsureXcmLocation for ForeignAssetsEnsureXCM { + fn ensure_xcm_origin(origin: RuntimeOrigin, location: &Location) -> Result { + ensure_signed(origin).map_err(|_| DispatchError::BadOrigin) + } + + fn account_for_location(location: &Location) -> Option { + Some(Alice.into()) + } +} + impl pallet_moonbeam_foreign_assets::Config for Test { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = Everything; type EvmRunner = pallet_evm::runner::stack::Runner; - type ForeignAssetCreatorOrigin = EnsureSigned; - type ForeignAssetFreezerOrigin = EnsureRoot; - type ForeignAssetModifierOrigin = EnsureRoot; - type ForeignAssetUnfreezerOrigin = EnsureRoot; + type EnsureXcmLocation = ForeignAssetsEnsureXCM; type OnForeignAssetCreated = (); type MaxForeignAssets = ConstU32<3>; type RuntimeEvent = RuntimeEvent; diff --git a/runtime/moonbase/src/foreign_origin.rs b/runtime/moonbase/src/foreign_origin.rs index cdbade22d3..0d5ba61493 100644 --- a/runtime/moonbase/src/foreign_origin.rs +++ b/runtime/moonbase/src/foreign_origin.rs @@ -15,31 +15,36 @@ // along with Moonbeam. If not, see . use crate::xcm_config::LocationToAccountId; -use crate::RuntimeOrigin; -use frame_support::traits::{EnsureOrigin, EnsureOriginWithArg, Everything}; +use crate::{Runtime, RuntimeOrigin}; +use frame_support::ensure; +use frame_support::traits::{EnsureOrigin, Everything}; +use frame_system::ensure_signed; use moonbeam_core_primitives::AccountId; +use pallet_moonbeam_foreign_assets::EnsureXcmLocation; +use sp_runtime::DispatchError; use xcm::latest::Location; use xcm_executor::traits::ConvertLocation; // `EnsureOriginWithArg` impl for `ForeignAssetOwnerOrigin` which allows only XCM origins // which are locations containing the class location. -pub struct ForeignAssetOwnerOrigin; -impl EnsureOriginWithArg for ForeignAssetOwnerOrigin { - type Success = AccountId; +pub struct ForeignAssetsEnsureXcmLocation; - fn try_origin( +impl EnsureXcmLocation for ForeignAssetsEnsureXcmLocation { + fn ensure_xcm_origin( o: RuntimeOrigin, - a: &Location, - ) -> core::result::Result { - let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone())?; - if !a.starts_with(&origin_location) { - return Err(o); - } - LocationToAccountId::convert_location(&origin_location).ok_or(o) + location: &Location, + ) -> Result { + let origin_account = ensure_signed(o.clone())?; + let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone()) + .map_err(|_| DispatchError::BadOrigin)?; + ensure!( + location.starts_with(&origin_location), + DispatchError::BadOrigin + ); + Ok(Self::account_for_location(location).unwrap_or(origin_account)) } - #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin(a: &Location) -> Result { - Ok(pallet_xcm::Origin::Xcm(a.clone()).into()) + fn account_for_location(location: &Location) -> Option { + LocationToAccountId::convert_location(location) } } diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index ffd7fe1cb6..1d2be03fba 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -67,7 +67,7 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use crate::foreign_origin::ForeignAssetOwnerOrigin; +use crate::foreign_origin::{ForeignAssetsEnsureXcmLocation}; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; use sp_core::Get; use sp_std::{ @@ -707,10 +707,7 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = ForeignAssetOwnerOrigin; - type ForeignAssetFreezerOrigin = ForeignAssetOwnerOrigin; - type ForeignAssetModifierOrigin = ForeignAssetOwnerOrigin; - type ForeignAssetUnfreezerOrigin = ForeignAssetOwnerOrigin; + type EnsureXcmLocation = ForeignAssetsEnsureXcmLocation; type OnForeignAssetCreated = (); type MaxForeignAssets = ConstU32<256>; type RuntimeEvent = RuntimeEvent; diff --git a/runtime/moonbeam/src/foreign_origin.rs b/runtime/moonbeam/src/foreign_origin.rs index cdbade22d3..0d5ba61493 100644 --- a/runtime/moonbeam/src/foreign_origin.rs +++ b/runtime/moonbeam/src/foreign_origin.rs @@ -15,31 +15,36 @@ // along with Moonbeam. If not, see . use crate::xcm_config::LocationToAccountId; -use crate::RuntimeOrigin; -use frame_support::traits::{EnsureOrigin, EnsureOriginWithArg, Everything}; +use crate::{Runtime, RuntimeOrigin}; +use frame_support::ensure; +use frame_support::traits::{EnsureOrigin, Everything}; +use frame_system::ensure_signed; use moonbeam_core_primitives::AccountId; +use pallet_moonbeam_foreign_assets::EnsureXcmLocation; +use sp_runtime::DispatchError; use xcm::latest::Location; use xcm_executor::traits::ConvertLocation; // `EnsureOriginWithArg` impl for `ForeignAssetOwnerOrigin` which allows only XCM origins // which are locations containing the class location. -pub struct ForeignAssetOwnerOrigin; -impl EnsureOriginWithArg for ForeignAssetOwnerOrigin { - type Success = AccountId; +pub struct ForeignAssetsEnsureXcmLocation; - fn try_origin( +impl EnsureXcmLocation for ForeignAssetsEnsureXcmLocation { + fn ensure_xcm_origin( o: RuntimeOrigin, - a: &Location, - ) -> core::result::Result { - let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone())?; - if !a.starts_with(&origin_location) { - return Err(o); - } - LocationToAccountId::convert_location(&origin_location).ok_or(o) + location: &Location, + ) -> Result { + let origin_account = ensure_signed(o.clone())?; + let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone()) + .map_err(|_| DispatchError::BadOrigin)?; + ensure!( + location.starts_with(&origin_location), + DispatchError::BadOrigin + ); + Ok(Self::account_for_location(location).unwrap_or(origin_account)) } - #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin(a: &Location) -> Result { - Ok(pallet_xcm::Origin::Xcm(a.clone()).into()) + fn account_for_location(location: &Location) -> Option { + LocationToAccountId::convert_location(location) } } diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index 65214638d1..c29a80c35d 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -66,7 +66,7 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use crate::foreign_origin::ForeignAssetOwnerOrigin; +use crate::foreign_origin::{ForeignAssetsEnsureXcmLocation}; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; use sp_core::Get; use sp_std::{ @@ -692,10 +692,7 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = ForeignAssetOwnerOrigin; - type ForeignAssetFreezerOrigin = ForeignAssetOwnerOrigin; - type ForeignAssetModifierOrigin = ForeignAssetOwnerOrigin; - type ForeignAssetUnfreezerOrigin = ForeignAssetOwnerOrigin; + type EnsureXcmLocation = ForeignAssetsEnsureXcmLocation; type OnForeignAssetCreated = (); type MaxForeignAssets = ConstU32<256>; type RuntimeEvent = RuntimeEvent; diff --git a/runtime/moonriver/src/foreign_origin.rs b/runtime/moonriver/src/foreign_origin.rs index cdbade22d3..0d5ba61493 100644 --- a/runtime/moonriver/src/foreign_origin.rs +++ b/runtime/moonriver/src/foreign_origin.rs @@ -15,31 +15,36 @@ // along with Moonbeam. If not, see . use crate::xcm_config::LocationToAccountId; -use crate::RuntimeOrigin; -use frame_support::traits::{EnsureOrigin, EnsureOriginWithArg, Everything}; +use crate::{Runtime, RuntimeOrigin}; +use frame_support::ensure; +use frame_support::traits::{EnsureOrigin, Everything}; +use frame_system::ensure_signed; use moonbeam_core_primitives::AccountId; +use pallet_moonbeam_foreign_assets::EnsureXcmLocation; +use sp_runtime::DispatchError; use xcm::latest::Location; use xcm_executor::traits::ConvertLocation; // `EnsureOriginWithArg` impl for `ForeignAssetOwnerOrigin` which allows only XCM origins // which are locations containing the class location. -pub struct ForeignAssetOwnerOrigin; -impl EnsureOriginWithArg for ForeignAssetOwnerOrigin { - type Success = AccountId; +pub struct ForeignAssetsEnsureXcmLocation; - fn try_origin( +impl EnsureXcmLocation for ForeignAssetsEnsureXcmLocation { + fn ensure_xcm_origin( o: RuntimeOrigin, - a: &Location, - ) -> core::result::Result { - let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone())?; - if !a.starts_with(&origin_location) { - return Err(o); - } - LocationToAccountId::convert_location(&origin_location).ok_or(o) + location: &Location, + ) -> Result { + let origin_account = ensure_signed(o.clone())?; + let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone()) + .map_err(|_| DispatchError::BadOrigin)?; + ensure!( + location.starts_with(&origin_location), + DispatchError::BadOrigin + ); + Ok(Self::account_for_location(location).unwrap_or(origin_account)) } - #[cfg(feature = "runtime-benchmarks")] - fn try_successful_origin(a: &Location) -> Result { - Ok(pallet_xcm::Origin::Xcm(a.clone()).into()) + fn account_for_location(location: &Location) -> Option { + LocationToAccountId::convert_location(location) } } diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index f0255d171e..f1bf4f48af 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -66,13 +66,14 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use crate::foreign_origin::ForeignAssetOwnerOrigin; +use crate::foreign_origin::{ForeignAssetsEnsureXcmLocation}; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; use sp_core::Get; use sp_std::{ convert::{From, Into, TryFrom}, prelude::*, }; +use pallet_moonbeam_foreign_assets::EnsureXcmLocation; parameter_types! { // The network Id of the relay @@ -705,10 +706,7 @@ impl pallet_moonbeam_foreign_assets::Config for Runtime { type AccountIdToH160 = AccountIdToH160; type AssetIdFilter = EvmForeignAssetIdFilter; type EvmRunner = EvmRunnerPrecompileOrEthXcm; - type ForeignAssetCreatorOrigin = ForeignAssetOwnerOrigin; - type ForeignAssetFreezerOrigin = ForeignAssetOwnerOrigin; - type ForeignAssetModifierOrigin = ForeignAssetOwnerOrigin; - type ForeignAssetUnfreezerOrigin = ForeignAssetOwnerOrigin; + type EnsureXcmLocation = ForeignAssetsEnsureXcmLocation; type OnForeignAssetCreated = (); type MaxForeignAssets = ConstU32<256>; type RuntimeEvent = RuntimeEvent; From ebc7469b3cdeb01e323862bd5b360ec8a4df915a Mon Sep 17 00:00:00 2001 From: Tarek Mohamed Abdalla Date: Wed, 22 Jan 2025 21:35:30 +0200 Subject: [PATCH 38/41] fix tests --- pallets/moonbeam-foreign-assets/src/lib.rs | 17 ++++---- pallets/moonbeam-foreign-assets/src/mock.rs | 5 ++- pallets/moonbeam-foreign-assets/src/tests.rs | 26 ++++++++---- pallets/moonbeam-lazy-migrations/src/mock.rs | 7 +++- runtime/moonbase/src/foreign_origin.rs | 21 ++++++---- runtime/moonbase/src/xcm_config.rs | 2 +- runtime/moonbase/tests/common/mod.rs | 24 ++++++++--- runtime/moonbase/tests/integration_test.rs | 44 +++++++------------- runtime/moonbeam/src/foreign_origin.rs | 15 +++---- runtime/moonbeam/src/xcm_config.rs | 2 +- runtime/moonriver/src/foreign_origin.rs | 15 +++---- runtime/moonriver/src/xcm_config.rs | 4 +- 12 files changed, 102 insertions(+), 80 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index 29b69a525d..38434b1b80 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -397,7 +397,7 @@ pub mod pallet { name: BoundedVec>, ) -> DispatchResult { let owner_account = - T::EnsureXcmLocation::ensure_xcm_origin(origin.clone(), &xcm_location)?; + T::EnsureXcmLocation::ensure_xcm_origin(origin.clone(), Some(&xcm_location))?; // Ensure such an assetId does not exist ensure!( @@ -465,11 +465,13 @@ pub mod pallet { new_xcm_location: Location, ) -> DispatchResult { // Ensures that the origin is an XCM location that contains the asset - T::EnsureXcmLocation::ensure_xcm_origin(origin, &new_xcm_location)?; + T::EnsureXcmLocation::ensure_xcm_origin(origin.clone(), Some(&new_xcm_location))?; let previous_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; + T::EnsureXcmLocation::ensure_xcm_origin(origin, Some(&previous_location))?; + ensure!( !AssetsByLocation::::contains_key(&new_xcm_location), Error::::LocationAlreadyExists @@ -498,14 +500,15 @@ pub mod pallet { asset_id: AssetId, allow_xcm_deposit: bool, ) -> DispatchResult { - ensure_signed(origin.clone())?; + // Ensure that the origin is coming from an XCM. + T::EnsureXcmLocation::ensure_xcm_origin(origin.clone(), None)?; let xcm_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; // Ensures that the origin is an XCM location that owns the asset // represented by the assets xcm location - T::EnsureXcmLocation::ensure_xcm_origin(origin, &xcm_location)?; + T::EnsureXcmLocation::ensure_xcm_origin(origin, Some(&xcm_location))?; let (_asset_id, asset_status) = AssetsByLocation::::get(&xcm_location) .ok_or(Error::::CorruptedStorageOrphanLocation)?; @@ -536,12 +539,12 @@ pub mod pallet { #[pallet::call_index(3)] #[pallet::weight(::WeightInfo::unfreeze_foreign_asset())] pub fn unfreeze_foreign_asset(origin: OriginFor, asset_id: AssetId) -> DispatchResult { - ensure_signed(origin.clone())?; + T::EnsureXcmLocation::ensure_xcm_origin(origin.clone(), None)?; let xcm_location = AssetsById::::get(&asset_id).ok_or(Error::::AssetDoesNotExist)?; // Ensures that the origin is an XCM location that contains the asset - T::EnsureXcmLocation::ensure_xcm_origin(origin, &xcm_location)?; + T::EnsureXcmLocation::ensure_xcm_origin(origin, Some(&xcm_location))?; let (_asset_id, asset_status) = AssetsByLocation::::get(&xcm_location) .ok_or(Error::::CorruptedStorageOrphanLocation)?; @@ -664,7 +667,7 @@ pub mod pallet { pub trait EnsureXcmLocation { fn ensure_xcm_origin( origin: T::RuntimeOrigin, - location: &Location, + location: Option<&Location>, ) -> Result; fn account_for_location(location: &Location) -> Option; } diff --git a/pallets/moonbeam-foreign-assets/src/mock.rs b/pallets/moonbeam-foreign-assets/src/mock.rs index 781775a3c6..7a82cb57fb 100644 --- a/pallets/moonbeam-foreign-assets/src/mock.rs +++ b/pallets/moonbeam-foreign-assets/src/mock.rs @@ -196,7 +196,10 @@ parameter_types! { pub struct ForeignAssetsEnsureXCM; impl EnsureXcmLocation for ForeignAssetsEnsureXCM { - fn ensure_xcm_origin(origin: RuntimeOrigin, location: &Location) -> Result { + fn ensure_xcm_origin( + origin: RuntimeOrigin, + location: Option<&Location>, + ) -> Result { ensure_signed(origin).map_err(|_| DispatchError::BadOrigin) } diff --git a/pallets/moonbeam-foreign-assets/src/tests.rs b/pallets/moonbeam-foreign-assets/src/tests.rs index 7c54e02e70..0786d75c27 100644 --- a/pallets/moonbeam-foreign-assets/src/tests.rs +++ b/pallets/moonbeam-foreign-assets/src/tests.rs @@ -92,13 +92,13 @@ fn create_foreign_and_freeze_unfreeze() { // Unfreeze should return AssetNotFrozen error assert_noop!( - EvmForeignAssets::unfreeze_foreign_asset(RuntimeOrigin::root(), 1), + EvmForeignAssets::unfreeze_foreign_asset(RuntimeOrigin::signed(Alice.into()), 1), Error::::AssetNotFrozen ); // Freeze should work assert_ok!(EvmForeignAssets::freeze_foreign_asset( - RuntimeOrigin::root(), + RuntimeOrigin::signed(Alice.into()), 1, true ),); @@ -109,13 +109,17 @@ fn create_foreign_and_freeze_unfreeze() { // Should not be able to freeze an asset already frozen assert_noop!( - EvmForeignAssets::freeze_foreign_asset(RuntimeOrigin::root(), 1, true), + EvmForeignAssets::freeze_foreign_asset( + RuntimeOrigin::signed(Alice.into()), + 1, + true + ), Error::::AssetAlreadyFrozen ); // Unfreeze should work assert_ok!(EvmForeignAssets::unfreeze_foreign_asset( - RuntimeOrigin::root(), + RuntimeOrigin::signed(Alice.into()), 1 ),); assert_eq!( @@ -197,7 +201,7 @@ fn test_root_can_change_foreign_asset_for_asset_id() { )); assert_ok!(EvmForeignAssets::change_xcm_location( - RuntimeOrigin::root(), + RuntimeOrigin::signed(Alice.into()), 1, Location::here() )); @@ -233,7 +237,11 @@ fn test_root_can_change_foreign_asset_for_asset_id() { fn test_asset_id_non_existent_error() { ExtBuilder::default().build().execute_with(|| { assert_noop!( - EvmForeignAssets::change_xcm_location(RuntimeOrigin::root(), 1, Location::parent()), + EvmForeignAssets::change_xcm_location( + RuntimeOrigin::from(Some(Alice.into())), + 1, + Location::parent() + ), Error::::AssetDoesNotExist ); }); @@ -278,7 +286,11 @@ fn test_location_already_exist_error() { )); assert_noop!( - EvmForeignAssets::change_xcm_location(RuntimeOrigin::root(), 2, Location::parent()), + EvmForeignAssets::change_xcm_location( + RuntimeOrigin::from(Some(Alice.into())), + 2, + Location::parent() + ), Error::::LocationAlreadyExists ); }); diff --git a/pallets/moonbeam-lazy-migrations/src/mock.rs b/pallets/moonbeam-lazy-migrations/src/mock.rs index 4bd752bcdc..29a4711625 100644 --- a/pallets/moonbeam-lazy-migrations/src/mock.rs +++ b/pallets/moonbeam-lazy-migrations/src/mock.rs @@ -24,13 +24,13 @@ use frame_support::{construct_runtime, parameter_types, traits::Everything, weig use frame_system::{EnsureRoot, EnsureSigned}; use pallet_asset_manager::AssetRegistrar; use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider}; +use pallet_moonbeam_foreign_assets::EnsureXcmLocation; use precompile_utils::testing::{Alice, MockAccount}; use sp_core::{ConstU32, H160, H256, U256}; use sp_runtime::{ traits::{BlakeTwo256, Hash, IdentityLookup}, BuildStorage, Perbill, }; -use pallet_moonbeam_foreign_assets::EnsureXcmLocation; pub type AssetId = u128; pub type Balance = u128; @@ -292,7 +292,10 @@ impl sp_runtime::traits::Convert for AccountIdToH160 { pub struct ForeignAssetsEnsureXCM; impl EnsureXcmLocation for ForeignAssetsEnsureXCM { - fn ensure_xcm_origin(origin: RuntimeOrigin, location: &Location) -> Result { + fn ensure_xcm_origin( + origin: RuntimeOrigin, + location: Option<&Location>, + ) -> Result { ensure_signed(origin).map_err(|_| DispatchError::BadOrigin) } diff --git a/runtime/moonbase/src/foreign_origin.rs b/runtime/moonbase/src/foreign_origin.rs index 0d5ba61493..5dd3dc8afc 100644 --- a/runtime/moonbase/src/foreign_origin.rs +++ b/runtime/moonbase/src/foreign_origin.rs @@ -22,26 +22,29 @@ use frame_system::ensure_signed; use moonbeam_core_primitives::AccountId; use pallet_moonbeam_foreign_assets::EnsureXcmLocation; use sp_runtime::DispatchError; +use sp_std::if_std; use xcm::latest::Location; +use xcm_builder::SiblingParachainAsNative; use xcm_executor::traits::ConvertLocation; -// `EnsureOriginWithArg` impl for `ForeignAssetOwnerOrigin` which allows only XCM origins -// which are locations containing the class location. +type Converter = SiblingParachainAsNative; + pub struct ForeignAssetsEnsureXcmLocation; impl EnsureXcmLocation for ForeignAssetsEnsureXcmLocation { fn ensure_xcm_origin( o: RuntimeOrigin, - location: &Location, + location: Option<&Location>, ) -> Result { - let origin_account = ensure_signed(o.clone())?; let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone()) .map_err(|_| DispatchError::BadOrigin)?; - ensure!( - location.starts_with(&origin_location), - DispatchError::BadOrigin - ); - Ok(Self::account_for_location(location).unwrap_or(origin_account)) + if let Some(location) = location { + ensure!( + location.starts_with(&origin_location), + DispatchError::BadOrigin + ); + } + Self::account_for_location(&origin_location).ok_or(DispatchError::BadOrigin) } fn account_for_location(location: &Location) -> Option { diff --git a/runtime/moonbase/src/xcm_config.rs b/runtime/moonbase/src/xcm_config.rs index 1d2be03fba..46106b5cee 100644 --- a/runtime/moonbase/src/xcm_config.rs +++ b/runtime/moonbase/src/xcm_config.rs @@ -67,7 +67,7 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use crate::foreign_origin::{ForeignAssetsEnsureXcmLocation}; +use crate::foreign_origin::ForeignAssetsEnsureXcmLocation; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; use sp_core::Get; use sp_std::{ diff --git a/runtime/moonbase/tests/common/mod.rs b/runtime/moonbase/tests/common/mod.rs index 5897b73fc7..08b4968a7b 100644 --- a/runtime/moonbase/tests/common/mod.rs +++ b/runtime/moonbase/tests/common/mod.rs @@ -32,10 +32,13 @@ use polkadot_parachain::primitives::HeadData; use sp_consensus_slots::Slot; use sp_core::{Encode, H160}; use sp_runtime::{traits::Dispatchable, BuildStorage, Digest, DigestItem, Perbill, Percent}; +use xcm_executor::traits::ConvertLocation; use std::collections::BTreeMap; use fp_rpc::ConvertTransaction; +use moonbase_runtime::xcm_config::LocationToAccountId; +use moonbase_runtime::{currency, RuntimeOrigin}; use pallet_transaction_payment::Multiplier; pub fn existential_deposit() -> u128 { @@ -226,8 +229,16 @@ impl ExtBuilder { .build_storage() .unwrap(); + let mut balances_with_xcm_accounts = self.balances.clone(); + for xcm_asset_initialization in self.xcm_assets.iter() { + let account = + LocationToAccountId::convert_location(&xcm_asset_initialization.xcm_location) + .expect("Could not convert location to account id"); + let balance = 200 * UNIT; + balances_with_xcm_accounts.push((account, balance)); + } pallet_balances::GenesisConfig:: { - balances: self.balances, + balances: balances_with_xcm_accounts, } .assimilate_storage(&mut t) .unwrap(); @@ -293,10 +304,12 @@ impl ExtBuilder { // If any xcm assets specified, we register them here for xcm_asset_initialization in xcm_assets { let asset_id = xcm_asset_initialization.asset_id; - EvmForeignAssets::create_foreign_asset( - moonbase_runtime::RuntimeOrigin::signed(AccountId::from(ALICE)), + let asset_location = xcm_asset_initialization.xcm_location; + let origin: RuntimeOrigin = pallet_xcm::Origin::Xcm(asset_location.clone()).into(); + assert_ok!(EvmForeignAssets::create_foreign_asset( + origin, asset_id, - xcm_asset_initialization.xcm_location, + asset_location, xcm_asset_initialization.decimals, xcm_asset_initialization .symbol @@ -310,8 +323,7 @@ impl ExtBuilder { .to_vec() .try_into() .expect("too long"), - ) - .expect("fail to create foreign asset"); + ),); for (account, balance) in xcm_asset_initialization.balances { if EvmForeignAssets::mint_into(asset_id, account, balance.into()).is_err() { diff --git a/runtime/moonbase/tests/integration_test.rs b/runtime/moonbase/tests/integration_test.rs index 7f4bc25cb1..49f4f67bec 100644 --- a/runtime/moonbase/tests/integration_test.rs +++ b/runtime/moonbase/tests/integration_test.rs @@ -37,29 +37,11 @@ use frame_support::{ StorageHasher, Twox128, }; use moonbase_runtime::{ - //asset_config::ForeignAssetInstance, - xcm_config::SelfReserve, - AccountId, - AssetId, - Balances, - CrowdloanRewards, - EvmForeignAssets, - Executive, - OpenTechCommitteeCollective, - ParachainStaking, - PolkadotXcm, - Precompiles, - Runtime, - RuntimeBlockWeights, - RuntimeCall, - RuntimeEvent, - System, - TransactionPayment, - TransactionPaymentAsGasPrice, - TreasuryCouncilCollective, - XcmTransactor, - FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX, - WEEKS, + xcm_config::SelfReserve, AccountId, AssetId, Balances, CrowdloanRewards, EvmForeignAssets, + Executive, OpenTechCommitteeCollective, ParachainStaking, PolkadotXcm, Precompiles, Runtime, + RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, System, TransactionPayment, + TransactionPaymentAsGasPrice, TreasuryCouncilCollective, XcmTransactor, + FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX, WEEKS, }; use polkadot_parachain::primitives::Sibling; use precompile_utils::testing::MockHandle; @@ -77,6 +59,7 @@ use moonkit_xcm_primitives::AccountIdAssetIdConversion; use nimbus_primitives::NimbusId; use pallet_evm::PrecompileSet; //use pallet_evm_precompileset_assets_erc20::{SELECTOR_LOG_APPROVAL, SELECTOR_LOG_TRANSFER}; +use moonbase_runtime::xcm_config::LocationToAccountId; use pallet_moonbeam_foreign_assets::AssetStatus; use pallet_transaction_payment::Multiplier; use pallet_xcm_transactor::{Currency, CurrencyPayment, HrmpOperation, TransactWeights}; @@ -1266,16 +1249,17 @@ fn update_reward_address_via_precompile() { #[test] fn create_and_manipulate_foreign_asset() { - let alice = AccountId::from(ALICE); + let source_location = xcm::v4::Location::parent(); + let account = + LocationToAccountId::convert_location(&source_location).expect("Cannot get account"); + let origin: RuntimeOrigin = pallet_xcm::Origin::Xcm(source_location.clone()).into(); ExtBuilder::default() - .with_balances(vec![(alice, 1_000 * UNIT)]) + .with_balances(vec![(account, 1_000 * UNIT)]) .build() .execute_with(|| { - let source_location = xcm::v4::Location::parent(); - // Create foreign asset assert_ok!(EvmForeignAssets::create_foreign_asset( - moonbase_runtime::RuntimeOrigin::signed(alice), + origin.clone(), 1, source_location.clone(), 12, @@ -1293,7 +1277,7 @@ fn create_and_manipulate_foreign_asset() { // Freeze foreign asset assert_ok!(EvmForeignAssets::freeze_foreign_asset( - root_origin(), + origin.clone(), 1, true )); @@ -1303,7 +1287,7 @@ fn create_and_manipulate_foreign_asset() { ); // Unfreeze foreign asset - assert_ok!(EvmForeignAssets::unfreeze_foreign_asset(root_origin(), 1,)); + assert_ok!(EvmForeignAssets::unfreeze_foreign_asset(origin, 1,)); assert_eq!( EvmForeignAssets::assets_by_location(&source_location), Some((1, AssetStatus::Active)) diff --git a/runtime/moonbeam/src/foreign_origin.rs b/runtime/moonbeam/src/foreign_origin.rs index 0d5ba61493..535551acd0 100644 --- a/runtime/moonbeam/src/foreign_origin.rs +++ b/runtime/moonbeam/src/foreign_origin.rs @@ -32,16 +32,17 @@ pub struct ForeignAssetsEnsureXcmLocation; impl EnsureXcmLocation for ForeignAssetsEnsureXcmLocation { fn ensure_xcm_origin( o: RuntimeOrigin, - location: &Location, + location: Option<&Location>, ) -> Result { - let origin_account = ensure_signed(o.clone())?; let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone()) .map_err(|_| DispatchError::BadOrigin)?; - ensure!( - location.starts_with(&origin_location), - DispatchError::BadOrigin - ); - Ok(Self::account_for_location(location).unwrap_or(origin_account)) + if let Some(location) = location { + ensure!( + location.starts_with(&origin_location), + DispatchError::BadOrigin + ); + } + Self::account_for_location(&origin_location).ok_or(DispatchError::BadOrigin) } fn account_for_location(location: &Location) -> Option { diff --git a/runtime/moonbeam/src/xcm_config.rs b/runtime/moonbeam/src/xcm_config.rs index c29a80c35d..5bcf9c7543 100644 --- a/runtime/moonbeam/src/xcm_config.rs +++ b/runtime/moonbeam/src/xcm_config.rs @@ -66,7 +66,7 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use crate::foreign_origin::{ForeignAssetsEnsureXcmLocation}; +use crate::foreign_origin::ForeignAssetsEnsureXcmLocation; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; use sp_core::Get; use sp_std::{ diff --git a/runtime/moonriver/src/foreign_origin.rs b/runtime/moonriver/src/foreign_origin.rs index 0d5ba61493..535551acd0 100644 --- a/runtime/moonriver/src/foreign_origin.rs +++ b/runtime/moonriver/src/foreign_origin.rs @@ -32,16 +32,17 @@ pub struct ForeignAssetsEnsureXcmLocation; impl EnsureXcmLocation for ForeignAssetsEnsureXcmLocation { fn ensure_xcm_origin( o: RuntimeOrigin, - location: &Location, + location: Option<&Location>, ) -> Result { - let origin_account = ensure_signed(o.clone())?; let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone()) .map_err(|_| DispatchError::BadOrigin)?; - ensure!( - location.starts_with(&origin_location), - DispatchError::BadOrigin - ); - Ok(Self::account_for_location(location).unwrap_or(origin_account)) + if let Some(location) = location { + ensure!( + location.starts_with(&origin_location), + DispatchError::BadOrigin + ); + } + Self::account_for_location(&origin_location).ok_or(DispatchError::BadOrigin) } fn account_for_location(location: &Location) -> Option { diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index f1bf4f48af..9b54442173 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -66,14 +66,14 @@ use xcm_primitives::{ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use crate::foreign_origin::{ForeignAssetsEnsureXcmLocation}; +use crate::foreign_origin::ForeignAssetsEnsureXcmLocation; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; +use pallet_moonbeam_foreign_assets::EnsureXcmLocation; use sp_core::Get; use sp_std::{ convert::{From, Into, TryFrom}, prelude::*, }; -use pallet_moonbeam_foreign_assets::EnsureXcmLocation; parameter_types! { // The network Id of the relay From 1541ea4ac80fbce6ad1b514ab73a64382e6341af Mon Sep 17 00:00:00 2001 From: Tarek Mohamed Abdalla Date: Wed, 22 Jan 2025 21:43:48 +0200 Subject: [PATCH 39/41] fix tests --- pallets/moonbeam-foreign-assets/src/tests.rs | 24 -------------------- 1 file changed, 24 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/tests.rs b/pallets/moonbeam-foreign-assets/src/tests.rs index 0786d75c27..68f9a6d62b 100644 --- a/pallets/moonbeam-foreign-assets/src/tests.rs +++ b/pallets/moonbeam-foreign-assets/src/tests.rs @@ -161,30 +161,6 @@ fn test_asset_exists_error() { }); } -#[test] -fn test_regular_user_cannot_call_some_extrinsics() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - EvmForeignAssets::change_xcm_location( - RuntimeOrigin::signed(Bob.into()), - 1, - Location::parent() - ), - sp_runtime::DispatchError::BadOrigin - ); - - assert_noop!( - EvmForeignAssets::freeze_foreign_asset(RuntimeOrigin::signed(Bob.into()), 1, false), - sp_runtime::DispatchError::BadOrigin - ); - - assert_noop!( - EvmForeignAssets::unfreeze_foreign_asset(RuntimeOrigin::signed(Bob.into()), 1,), - sp_runtime::DispatchError::BadOrigin - ); - }); -} - #[test] fn test_root_can_change_foreign_asset_for_asset_id() { ExtBuilder::default() From 82a711e3f1ad9b28824a38ccd35838f8a4f1f58c Mon Sep 17 00:00:00 2001 From: Tarek Mohamed Abdalla Date: Thu, 23 Jan 2025 12:29:30 +0200 Subject: [PATCH 40/41] fix formatting --- pallets/moonbeam-foreign-assets/src/lib.rs | 2 +- runtime/moonbase/src/foreign_origin.rs | 5 ----- runtime/moonbeam/src/foreign_origin.rs | 1 - runtime/moonriver/src/foreign_origin.rs | 1 - runtime/moonriver/src/xcm_config.rs | 1 - 5 files changed, 1 insertion(+), 9 deletions(-) diff --git a/pallets/moonbeam-foreign-assets/src/lib.rs b/pallets/moonbeam-foreign-assets/src/lib.rs index 38434b1b80..c54cbc00bd 100644 --- a/pallets/moonbeam-foreign-assets/src/lib.rs +++ b/pallets/moonbeam-foreign-assets/src/lib.rs @@ -107,7 +107,7 @@ pub enum AssetStatus { #[pallet] pub mod pallet { use super::*; - use frame_support::traits::{Currency, EnsureOriginWithArg, ReservableCurrency}; + use frame_support::traits::{Currency, ReservableCurrency}; use pallet_evm::{GasWeightMapping, Runner}; use sp_runtime::traits::{AccountIdConversion, AtLeast32BitUnsigned, Convert}; use xcm_executor::traits::ConvertLocation; diff --git a/runtime/moonbase/src/foreign_origin.rs b/runtime/moonbase/src/foreign_origin.rs index 5dd3dc8afc..562b879f10 100644 --- a/runtime/moonbase/src/foreign_origin.rs +++ b/runtime/moonbase/src/foreign_origin.rs @@ -18,17 +18,12 @@ use crate::xcm_config::LocationToAccountId; use crate::{Runtime, RuntimeOrigin}; use frame_support::ensure; use frame_support::traits::{EnsureOrigin, Everything}; -use frame_system::ensure_signed; use moonbeam_core_primitives::AccountId; use pallet_moonbeam_foreign_assets::EnsureXcmLocation; use sp_runtime::DispatchError; -use sp_std::if_std; use xcm::latest::Location; -use xcm_builder::SiblingParachainAsNative; use xcm_executor::traits::ConvertLocation; -type Converter = SiblingParachainAsNative; - pub struct ForeignAssetsEnsureXcmLocation; impl EnsureXcmLocation for ForeignAssetsEnsureXcmLocation { diff --git a/runtime/moonbeam/src/foreign_origin.rs b/runtime/moonbeam/src/foreign_origin.rs index 535551acd0..55df40de12 100644 --- a/runtime/moonbeam/src/foreign_origin.rs +++ b/runtime/moonbeam/src/foreign_origin.rs @@ -18,7 +18,6 @@ use crate::xcm_config::LocationToAccountId; use crate::{Runtime, RuntimeOrigin}; use frame_support::ensure; use frame_support::traits::{EnsureOrigin, Everything}; -use frame_system::ensure_signed; use moonbeam_core_primitives::AccountId; use pallet_moonbeam_foreign_assets::EnsureXcmLocation; use sp_runtime::DispatchError; diff --git a/runtime/moonriver/src/foreign_origin.rs b/runtime/moonriver/src/foreign_origin.rs index 535551acd0..55df40de12 100644 --- a/runtime/moonriver/src/foreign_origin.rs +++ b/runtime/moonriver/src/foreign_origin.rs @@ -18,7 +18,6 @@ use crate::xcm_config::LocationToAccountId; use crate::{Runtime, RuntimeOrigin}; use frame_support::ensure; use frame_support::traits::{EnsureOrigin, Everything}; -use frame_system::ensure_signed; use moonbeam_core_primitives::AccountId; use pallet_moonbeam_foreign_assets::EnsureXcmLocation; use sp_runtime::DispatchError; diff --git a/runtime/moonriver/src/xcm_config.rs b/runtime/moonriver/src/xcm_config.rs index 9b54442173..75e13b48d7 100644 --- a/runtime/moonriver/src/xcm_config.rs +++ b/runtime/moonriver/src/xcm_config.rs @@ -68,7 +68,6 @@ use scale_info::TypeInfo; use crate::foreign_origin::ForeignAssetsEnsureXcmLocation; use crate::governance::referenda::{FastGeneralAdminOrRoot, GeneralAdminOrRoot}; -use pallet_moonbeam_foreign_assets::EnsureXcmLocation; use sp_core::Get; use sp_std::{ convert::{From, Into, TryFrom}, From ac7ada3941372b3343aa531884a8b556ed8fccb0 Mon Sep 17 00:00:00 2001 From: Tarek Mohamed Abdalla Date: Thu, 23 Jan 2025 14:30:41 +0200 Subject: [PATCH 41/41] fmt --- runtime/moonbase/tests/integration_test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/moonbase/tests/integration_test.rs b/runtime/moonbase/tests/integration_test.rs index 08a66be449..366bb5b4dd 100644 --- a/runtime/moonbase/tests/integration_test.rs +++ b/runtime/moonbase/tests/integration_test.rs @@ -40,7 +40,7 @@ use moonbase_runtime::{ xcm_config::SelfReserve, AccountId, AssetId, Balances, CrowdloanRewards, EvmForeignAssets, Executive, OpenTechCommitteeCollective, ParachainStaking, PolkadotXcm, Precompiles, Runtime, RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, System, TransactionPayment, - TransactionPaymentAsGasPrice, Treasury,TreasuryCouncilCollective, XcmTransactor, + TransactionPaymentAsGasPrice, Treasury, TreasuryCouncilCollective, XcmTransactor, FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX, WEEKS, }; use polkadot_parachain::primitives::Sibling;