difftreelog
Foreign assets pallet fixes
in: master
4 files changed
pallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -26,9 +26,20 @@
use up_data_structs::budget::Unlimited;
use sp_runtime::traits::{CheckedAdd, CheckedSub};
+// type BalanceSelf<T> =
+// <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
+type BalanceRelay<T> =
+ <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
+
impl<T: Config> fungibles::Inspect<<T as SystemConfig>::AccountId> for Pallet<T>
where
T: orml_tokens::Config<CurrencyId = AssetIds>,
+ BalanceRelay<T>: From<BalanceOf<T>>,
+ BalanceOf<T>: From<BalanceRelay<T>>,
+ BalanceRelay<T>: From<<T as pallet_balances::Config>::Balance>,
+ BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
+ <T as pallet_balances::Config>::Balance: From<BalanceRelay<T>>,
+ <T as orml_tokens::Config>::Balance: From<BalanceRelay<T>>,
{
type AssetId = AssetIds;
type Balance = BalanceOf<T>;
@@ -38,39 +49,14 @@
match asset {
AssetIds::NativeAssetId(NativeCurrency::Here) => {
- let parent_amount = <pallet_balances::Pallet<T> as fungible::Inspect<
- T::AccountId,
- >>::total_issuance();
-
- let value: u128 = match parent_amount.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- let ti: Self::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- ti
+ <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::total_issuance()
+ .into()
}
AssetIds::NativeAssetId(NativeCurrency::Parent) => {
- let amount =
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::total_issuance(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
- );
-
- let value: u128 = match amount.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- let ti: Self::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- ti
+ <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::total_issuance(
+ AssetIds::NativeAssetId(NativeCurrency::Parent),
+ )
+ .into()
}
AssetIds::ForeignAssetId(fid) => {
let target_collection_id = match <AssetBinding<T>>::get(fid) {
@@ -91,39 +77,14 @@
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible minimum_balance");
match asset {
AssetIds::NativeAssetId(NativeCurrency::Here) => {
- let parent_amount = <pallet_balances::Pallet<T> as fungible::Inspect<
- T::AccountId,
- >>::minimum_balance();
-
- let value: u128 = match parent_amount.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- let ti: Self::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- ti
+ <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::minimum_balance()
+ .into()
}
AssetIds::NativeAssetId(NativeCurrency::Parent) => {
- let amount =
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::minimum_balance(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
- );
-
- let value: u128 = match amount.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- let ti: Self::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- ti
+ <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::minimum_balance(
+ AssetIds::NativeAssetId(NativeCurrency::Parent),
+ )
+ .into()
}
AssetIds::ForeignAssetId(fid) => {
AssetMetadatas::<T>::get(AssetIds::ForeignAssetId(fid))
@@ -137,38 +98,14 @@
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible balance");
match asset {
AssetIds::NativeAssetId(NativeCurrency::Here) => {
- let parent_amount =
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::balance(who);
-
- let value: u128 = match parent_amount.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- let ti: Self::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- ti
+ <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::balance(who).into()
}
AssetIds::NativeAssetId(NativeCurrency::Parent) => {
- let amount = <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::balance(
+ <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::balance(
AssetIds::NativeAssetId(NativeCurrency::Parent),
who,
- );
-
- let value: u128 = match amount.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- let ti: Self::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- ti
+ )
+ .into()
}
AssetIds::ForeignAssetId(fid) => {
let target_collection_id = match <AssetBinding<T>>::get(fid) {
@@ -197,41 +134,18 @@
match asset {
AssetIds::NativeAssetId(NativeCurrency::Here) => {
- let parent_amount = <pallet_balances::Pallet<T> as fungible::Inspect<
- T::AccountId,
- >>::reducible_balance(who, keep_alive);
-
- let value: u128 = match parent_amount.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- let ti: Self::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- ti
+ <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::reducible_balance(
+ who, keep_alive,
+ )
+ .into()
}
AssetIds::NativeAssetId(NativeCurrency::Parent) => {
- let amount =
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::reducible_balance(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
- who,
- keep_alive,
- );
-
- let value: u128 = match amount.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- let ti: Self::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => return Zero::zero(),
- };
-
- ti
+ <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::reducible_balance(
+ AssetIds::NativeAssetId(NativeCurrency::Parent),
+ who,
+ keep_alive,
+ )
+ .into()
}
_ => Self::balance(asset, who),
}
@@ -244,37 +158,20 @@
mint: bool,
) -> DepositConsequence {
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_deposit");
-
- let value: u128 = match amount.try_into() {
- Ok(val) => val,
- Err(_) => return DepositConsequence::CannotCreate,
- };
match asset {
AssetIds::NativeAssetId(NativeCurrency::Here) => {
- let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return DepositConsequence::CannotCreate;
- }
- };
<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_deposit(
who,
- this_amount,
+ amount.into(),
mint,
)
}
AssetIds::NativeAssetId(NativeCurrency::Parent) => {
- let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return DepositConsequence::CannotCreate;
- }
- };
<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_deposit(
AssetIds::NativeAssetId(NativeCurrency::Parent),
who,
- parent_amount,
+ amount.into(),
mint,
)
}
@@ -373,6 +270,13 @@
impl<T: Config> fungibles::Mutate<<T as SystemConfig>::AccountId> for Pallet<T>
where
T: orml_tokens::Config<CurrencyId = AssetIds>,
+ BalanceRelay<T>: From<BalanceOf<T>>,
+ BalanceOf<T>: From<BalanceRelay<T>>,
+ BalanceRelay<T>: From<<T as pallet_balances::Config>::Balance>,
+ BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
+ <T as pallet_balances::Config>::Balance: From<BalanceRelay<T>>,
+ <T as orml_tokens::Config>::Balance: From<BalanceRelay<T>>,
+ u128: From<BalanceRelay<T>>,
{
fn mint_into(
asset: Self::AssetId,
@@ -381,43 +285,22 @@
) -> DispatchResult {
//Self::do_mint(asset, who, amount, None)
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible mint_into {:?}", asset);
-
- let value: u128 = match amount.try_into() {
- Ok(val) => val,
- Err(_) => return Err(DispatchError::Other("Bad amount to value conversion")),
- };
match asset {
AssetIds::NativeAssetId(NativeCurrency::Here) => {
- let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return Err(DispatchError::Other(
- "Bad amount to this parachain value conversion",
- ))
- }
- };
-
<pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::mint_into(
who,
- this_amount,
+ amount.into(),
)
+ .into()
}
AssetIds::NativeAssetId(NativeCurrency::Parent) => {
- let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return Err(DispatchError::Other(
- "Bad amount to relay chain value conversion",
- ))
- }
- };
-
<orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::mint_into(
AssetIds::NativeAssetId(NativeCurrency::Parent),
who,
- parent_amount,
+ amount.into(),
)
+ .into()
}
AssetIds::ForeignAssetId(fid) => {
let target_collection_id = match <AssetBinding<T>>::get(fid) {
@@ -432,7 +315,8 @@
FungibleHandle::cast(<CollectionHandle<T>>::try_get(target_collection_id)?);
let account = T::CrossAccountId::from_sub(who.clone());
- let amount_data: pallet_fungible::CreateItemData<T> = (account.clone(), value);
+ let amount_data: pallet_fungible::CreateItemData<T> =
+ (account.clone(), amount.into());
pallet_fungible::Pallet::<T>::create_item_foreign(
&collection,
@@ -453,43 +337,24 @@
) -> Result<Self::Balance, DispatchError> {
// let f = DebitFlags { keep_alive: false, best_effort: false };
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible burn_from");
-
- let value: u128 = match amount.try_into() {
- Ok(val) => val,
- Err(_) => return Err(DispatchError::Other("Bad amount to value conversion")),
- };
match asset {
AssetIds::NativeAssetId(NativeCurrency::Here) => {
- let this_amount: <T as pallet_balances::Config>::Balance =
- value.try_into().map_err(|_| {
- DispatchError::Other("Bad amount to this parachain value conversion")
- })?;
-
match <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::burn_from(
who,
- this_amount,
+ amount.into(),
) {
- Ok(_) => Ok(amount),
+ Ok(v) => Ok(v.into()),
Err(e) => Err(e),
}
}
AssetIds::NativeAssetId(NativeCurrency::Parent) => {
- let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return Err(DispatchError::Other(
- "Bad amount to relay chain value conversion",
- ))
- }
- };
-
match <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::burn_from(
AssetIds::NativeAssetId(NativeCurrency::Parent),
who,
- parent_amount,
+ amount.into(),
) {
- Ok(_) => Ok(amount),
+ Ok(v) => Ok(v.into()),
Err(e) => Err(e),
}
}
@@ -507,7 +372,7 @@
pallet_fungible::Pallet::<T>::burn_foreign(
&collection,
&T::CrossAccountId::from_sub(who.clone()),
- value,
+ amount.into(),
)?;
Ok(amount)
@@ -522,14 +387,20 @@
) -> Result<Self::Balance, DispatchError> {
// let f = DebitFlags { keep_alive: false, best_effort: true };
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible slash");
- Self::burn_from(asset, who, amount)?;
- Ok(amount)
+ Ok(Self::burn_from(asset, who, amount)?)
}
}
impl<T: Config> fungibles::Transfer<T::AccountId> for Pallet<T>
where
T: orml_tokens::Config<CurrencyId = AssetIds>,
+ BalanceRelay<T>: From<BalanceOf<T>>,
+ BalanceOf<T>: From<BalanceRelay<T>>,
+ BalanceRelay<T>: From<<T as pallet_balances::Config>::Balance>,
+ BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
+ <T as pallet_balances::Config>::Balance: From<BalanceRelay<T>>,
+ <T as orml_tokens::Config>::Balance: From<BalanceRelay<T>>,
+ u128: From<BalanceRelay<T>>,
{
fn transfer(
asset: Self::AssetId,
@@ -540,27 +411,13 @@
) -> Result<Self::Balance, DispatchError> {
// let f = TransferFlags { keep_alive, best_effort: false, burn_dust: false };
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible transfer");
-
- let value: u128 = match amount.try_into() {
- Ok(val) => val,
- Err(_) => return Err(DispatchError::Other("Bad amount to value conversion")),
- };
match asset {
AssetIds::NativeAssetId(NativeCurrency::Here) => {
- let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return Err(DispatchError::Other(
- "Bad amount to this parachain value conversion",
- ))
- }
- };
-
match <pallet_balances::Pallet<T> as fungible::Transfer<T::AccountId>>::transfer(
source,
dest,
- this_amount,
+ amount.into(),
keep_alive,
) {
Ok(_) => Ok(amount),
@@ -570,20 +427,11 @@
}
}
AssetIds::NativeAssetId(NativeCurrency::Parent) => {
- let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return Err(DispatchError::Other(
- "Bad amount to relay chain value conversion",
- ))
- }
- };
-
match <orml_tokens::Pallet<T> as fungibles::Transfer<T::AccountId>>::transfer(
AssetIds::NativeAssetId(NativeCurrency::Parent),
source,
dest,
- parent_amount,
+ amount.into(),
keep_alive,
) {
Ok(_) => Ok(amount),
@@ -606,7 +454,7 @@
&collection,
&T::CrossAccountId::from_sub(source.clone()),
&T::CrossAccountId::from_sub(dest.clone()),
- value,
+ amount.into(),
&Unlimited,
)?;
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Foreign assets18//!19//! - [`Config`]20//! - [`Call`]21//! - [`Pallet`]22//!23//! ## Overview24//!25//! The foreign assests pallet provides functions for:26//!27//! - Local and foreign assets management. The foreign assets can be updated without runtime upgrade.28//! - Bounds between asset and target collection for cross chain transfer and inner transfers.29//!30//! ## Overview31//!32//! Under construction3334#![cfg_attr(not(feature = "std"), no_std)]35#![allow(clippy::unused_unit)]3637use frame_support::{38 dispatch::DispatchResult,39 ensure,40 pallet_prelude::*,41 traits::{fungible, fungibles, Currency, EnsureOrigin},42 RuntimeDebug,43};44use frame_system::pallet_prelude::*;45use up_data_structs::{CollectionMode};46use pallet_fungible::{Pallet as PalletFungible};47use scale_info::{TypeInfo};48use sp_runtime::{49 traits::{One, Zero},50 ArithmeticError,51};52use sp_std::{boxed::Box, vec::Vec};53use up_data_structs::{CollectionId, TokenId, CreateCollectionData};5455// NOTE:v1::MultiLocation is used in storages, we would need to do migration if upgrade the56// MultiLocation in the future.57use xcm::opaque::latest::prelude::XcmError;58use xcm::{v1::MultiLocation, VersionedMultiLocation};59use xcm_executor::{traits::WeightTrader, Assets};6061use pallet_common::erc::CrossAccountId;6263#[cfg(feature = "std")]64use serde::{Deserialize, Serialize};6566// TODO: Move to primitives67// Id of native currency.68// 0 - QTZ\UNQ69// 1 - KSM\DOT70#[derive(71 Clone,72 Copy,73 Eq,74 PartialEq,75 PartialOrd,76 Ord,77 MaxEncodedLen,78 RuntimeDebug,79 Encode,80 Decode,81 TypeInfo,82)]83#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]84pub enum NativeCurrency {85 Here = 0,86 Parent = 1,87}8889#[derive(90 Clone,91 Copy,92 Eq,93 PartialEq,94 PartialOrd,95 Ord,96 MaxEncodedLen,97 RuntimeDebug,98 Encode,99 Decode,100 TypeInfo,101)]102#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]103pub enum AssetIds {104 ForeignAssetId(ForeignAssetId),105 NativeAssetId(NativeCurrency),106}107108pub trait TryAsForeign<T, F> {109 fn try_as_foreign(asset: T) -> Option<F>;110}111112impl TryAsForeign<AssetIds, ForeignAssetId> for AssetIds {113 fn try_as_foreign(asset: AssetIds) -> Option<ForeignAssetId> {114 match asset {115 AssetIds::ForeignAssetId(id) => Some(id),116 _ => None,117 }118 }119}120121pub type ForeignAssetId = u32;122pub type CurrencyId = AssetIds;123124mod impl_fungibles;125mod weights;126127#[cfg(feature = "runtime-benchmarks")]128mod benchmarking;129130pub use module::*;131pub use weights::WeightInfo;132133/// Type alias for currency balance.134pub type BalanceOf<T> =135 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;136137/// A mapping between ForeignAssetId and AssetMetadata.138pub trait AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata> {139 /// Returns the AssetMetadata associated with a given ForeignAssetId.140 fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata>;141 /// Returns the MultiLocation associated with a given ForeignAssetId.142 fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation>;143 /// Returns the CurrencyId associated with a given MultiLocation.144 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId>;145}146147pub struct XcmForeignAssetIdMapping<T>(sp_std::marker::PhantomData<T>);148149impl<T: Config> AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata<BalanceOf<T>>>150 for XcmForeignAssetIdMapping<T>151{152 fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {153 log::trace!(target: "fassets::asset_metadatas", "call");154 Pallet::<T>::asset_metadatas(AssetIds::ForeignAssetId(foreign_asset_id))155 }156157 fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {158 log::trace!(target: "fassets::get_multi_location", "call");159 Pallet::<T>::foreign_asset_locations(foreign_asset_id)160 }161162 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {163 log::trace!(target: "fassets::get_currency_id", "call");164 Some(AssetIds::ForeignAssetId(165 Pallet::<T>::location_to_currency_ids(multi_location).unwrap_or(0),166 ))167 }168}169170#[frame_support::pallet]171pub mod module {172 use super::*;173174 #[pallet::config]175 pub trait Config:176 frame_system::Config177 + pallet_common::Config178 + pallet_fungible::Config179 + orml_tokens::Config180 + pallet_balances::Config181 {182 /// The overarching event type.183 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;184185 /// Currency type for withdraw and balance storage.186 type Currency: Currency<Self::AccountId>;187188 /// Required origin for registering asset.189 type RegisterOrigin: EnsureOrigin<Self::Origin>;190191 /// Weight information for the extrinsics in this module.192 type WeightInfo: WeightInfo;193 }194195 #[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)]196 pub struct AssetMetadata<Balance> {197 pub name: Vec<u8>,198 pub symbol: Vec<u8>,199 pub decimals: u8,200 pub minimal_balance: Balance,201 }202203 #[pallet::error]204 pub enum Error<T> {205 /// The given location could not be used (e.g. because it cannot be expressed in the206 /// desired version of XCM).207 BadLocation,208 /// MultiLocation existed209 MultiLocationExisted,210 /// AssetId not exists211 AssetIdNotExists,212 /// AssetId exists213 AssetIdExisted,214 }215216 #[pallet::event]217 #[pallet::generate_deposit(fn deposit_event)]218 pub enum Event<T: Config> {219 /// The foreign asset registered.220 ForeignAssetRegistered {221 asset_id: ForeignAssetId,222 asset_address: MultiLocation,223 metadata: AssetMetadata<BalanceOf<T>>,224 },225 /// The foreign asset updated.226 ForeignAssetUpdated {227 asset_id: ForeignAssetId,228 asset_address: MultiLocation,229 metadata: AssetMetadata<BalanceOf<T>>,230 },231 /// The asset registered.232 AssetRegistered {233 asset_id: AssetIds,234 metadata: AssetMetadata<BalanceOf<T>>,235 },236 /// The asset updated.237 AssetUpdated {238 asset_id: AssetIds,239 metadata: AssetMetadata<BalanceOf<T>>,240 },241 }242243 /// Next available Foreign AssetId ID.244 ///245 /// NextForeignAssetId: ForeignAssetId246 #[pallet::storage]247 #[pallet::getter(fn next_foreign_asset_id)]248 pub type NextForeignAssetId<T: Config> = StorageValue<_, ForeignAssetId, ValueQuery>;249 /// The storages for MultiLocations.250 ///251 /// ForeignAssetLocations: map ForeignAssetId => Option<MultiLocation>252 #[pallet::storage]253 #[pallet::getter(fn foreign_asset_locations)]254 pub type ForeignAssetLocations<T: Config> =255 StorageMap<_, Twox64Concat, ForeignAssetId, MultiLocation, OptionQuery>;256257 /// The storages for CurrencyIds.258 ///259 /// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>260 #[pallet::storage]261 #[pallet::getter(fn location_to_currency_ids)]262 pub type LocationToCurrencyIds<T: Config> =263 StorageMap<_, Twox64Concat, MultiLocation, ForeignAssetId, OptionQuery>;264265 /// The storages for AssetMetadatas.266 ///267 /// AssetMetadatas: map AssetIds => Option<AssetMetadata>268 #[pallet::storage]269 #[pallet::getter(fn asset_metadatas)]270 pub type AssetMetadatas<T: Config> =271 StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;272273 /// The storages for assets to fungible collection binding274 ///275 #[pallet::storage]276 #[pallet::getter(fn asset_binding)]277 pub type AssetBinding<T: Config> =278 StorageMap<_, Twox64Concat, ForeignAssetId, CollectionId, OptionQuery>;279280 #[pallet::pallet]281 #[pallet::without_storage_info]282 pub struct Pallet<T>(_);283284 #[pallet::call]285 impl<T: Config> Pallet<T> {286 #[pallet::weight(<T as Config>::WeightInfo::register_foreign_asset())]287 pub fn register_foreign_asset(288 origin: OriginFor<T>,289 owner: T::AccountId,290 location: Box<VersionedMultiLocation>,291 metadata: Box<AssetMetadata<BalanceOf<T>>>,292 ) -> DispatchResult {293 T::RegisterOrigin::ensure_origin(origin.clone())?;294295 let location: MultiLocation = (*location)296 .try_into()297 .map_err(|()| Error::<T>::BadLocation)?;298299 let md = metadata.clone();300 let name: Vec<u16> = md.name.into_iter().map(|x| x as u16).collect::<Vec<u16>>();301 let mut description: Vec<u16> = "Foreign assets collection for "302 .encode_utf16()303 .collect::<Vec<u16>>();304 description.append(&mut name.clone());305306 let data: CreateCollectionData<T::AccountId> = CreateCollectionData {307 name: name.try_into().unwrap(),308 description: description.try_into().unwrap(),309 mode: CollectionMode::Fungible(md.decimals),310 ..Default::default()311 };312313 let bounded_collection_id = <PalletFungible<T>>::init_foreign_collection(314 CrossAccountId::from_sub(owner),315 data,316 )?;317 let foreign_asset_id =318 Self::do_register_foreign_asset(&location, &metadata, bounded_collection_id)?;319320 Self::deposit_event(Event::<T>::ForeignAssetRegistered {321 asset_id: foreign_asset_id,322 asset_address: location,323 metadata: *metadata,324 });325 Ok(())326 }327328 #[pallet::weight(<T as Config>::WeightInfo::update_foreign_asset())]329 pub fn update_foreign_asset(330 origin: OriginFor<T>,331 foreign_asset_id: ForeignAssetId,332 location: Box<VersionedMultiLocation>,333 metadata: Box<AssetMetadata<BalanceOf<T>>>,334 ) -> DispatchResult {335 T::RegisterOrigin::ensure_origin(origin)?;336337 let location: MultiLocation = (*location)338 .try_into()339 .map_err(|()| Error::<T>::BadLocation)?;340 Self::do_update_foreign_asset(foreign_asset_id, &location, &metadata)?;341342 Self::deposit_event(Event::<T>::ForeignAssetUpdated {343 asset_id: foreign_asset_id,344 asset_address: location,345 metadata: *metadata,346 });347 Ok(())348 }349 }350}351352impl<T: Config> Pallet<T> {353 fn get_next_foreign_asset_id() -> Result<ForeignAssetId, DispatchError> {354 NextForeignAssetId::<T>::try_mutate(|current| -> Result<ForeignAssetId, DispatchError> {355 let id = *current;356 *current = current357 .checked_add(One::one())358 .ok_or(ArithmeticError::Overflow)?;359 Ok(id)360 })361 }362363 fn do_register_foreign_asset(364 location: &MultiLocation,365 metadata: &AssetMetadata<BalanceOf<T>>,366 bounded_collection_id: CollectionId,367 ) -> Result<ForeignAssetId, DispatchError> {368 let foreign_asset_id = Self::get_next_foreign_asset_id()?;369 LocationToCurrencyIds::<T>::try_mutate(location, |maybe_currency_ids| -> DispatchResult {370 ensure!(371 maybe_currency_ids.is_none(),372 Error::<T>::MultiLocationExisted373 );374 *maybe_currency_ids = Some(foreign_asset_id);375 // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));376377 ForeignAssetLocations::<T>::try_mutate(378 foreign_asset_id,379 |maybe_location| -> DispatchResult {380 ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);381 *maybe_location = Some(location.clone());382383 AssetMetadatas::<T>::try_mutate(384 AssetIds::ForeignAssetId(foreign_asset_id),385 |maybe_asset_metadatas| -> DispatchResult {386 ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);387 *maybe_asset_metadatas = Some(metadata.clone());388 Ok(())389 },390 )391 },392 )?;393394 AssetBinding::<T>::try_mutate(foreign_asset_id, |collection_id| -> DispatchResult {395 *collection_id = Some(bounded_collection_id);396 Ok(())397 })398 })?;399400 Ok(foreign_asset_id)401 }402403 fn do_update_foreign_asset(404 foreign_asset_id: ForeignAssetId,405 location: &MultiLocation,406 metadata: &AssetMetadata<BalanceOf<T>>,407 ) -> DispatchResult {408 ForeignAssetLocations::<T>::try_mutate(409 foreign_asset_id,410 |maybe_multi_locations| -> DispatchResult {411 let old_multi_locations = maybe_multi_locations412 .as_mut()413 .ok_or(Error::<T>::AssetIdNotExists)?;414415 AssetMetadatas::<T>::try_mutate(416 AssetIds::ForeignAssetId(foreign_asset_id),417 |maybe_asset_metadatas| -> DispatchResult {418 ensure!(419 maybe_asset_metadatas.is_some(),420 Error::<T>::AssetIdNotExists421 );422423 // modify location424 if location != old_multi_locations {425 LocationToCurrencyIds::<T>::remove(old_multi_locations.clone());426 LocationToCurrencyIds::<T>::try_mutate(427 location,428 |maybe_currency_ids| -> DispatchResult {429 ensure!(430 maybe_currency_ids.is_none(),431 Error::<T>::MultiLocationExisted432 );433 // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));434 *maybe_currency_ids = Some(foreign_asset_id);435 Ok(())436 },437 )?;438 }439 *maybe_asset_metadatas = Some(metadata.clone());440 *old_multi_locations = location.clone();441 Ok(())442 },443 )444 },445 )446 }447}448449pub use frame_support::{450 traits::{451 fungibles::{Balanced, CreditOf},452 tokens::currency::Currency as CurrencyT,453 OnUnbalanced as OnUnbalancedT,454 },455 weights::{WeightToFeePolynomial, WeightToFee},456};457458pub struct FreeForAll<459 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,460 AssetId: Get<MultiLocation>,461 AccountId,462 Currency: CurrencyT<AccountId>,463 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,464>(465 Weight,466 Currency::Balance,467 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,468);469470impl<471 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,472 AssetId: Get<MultiLocation>,473 AccountId,474 Currency: CurrencyT<AccountId>,475 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,476 > WeightTrader for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>477{478 fn new() -> Self {479 Self(0, Zero::zero(), PhantomData)480 }481482 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {483 log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);484 Ok(payment)485 }486}487impl<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced> Drop488 for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>489where490 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,491 AssetId: Get<MultiLocation>,492 Currency: CurrencyT<AccountId>,493 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,494{495 fn drop(&mut self) {496 OnUnbalanced::on_unbalanced(Currency::issue(self.1));497 }498}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Foreign assets18//!19//! - [`Config`]20//! - [`Call`]21//! - [`Pallet`]22//!23//! ## Overview24//!25//! The foreign assests pallet provides functions for:26//!27//! - Local and foreign assets management. The foreign assets can be updated without runtime upgrade.28//! - Bounds between asset and target collection for cross chain transfer and inner transfers.29//!30//! ## Overview31//!32//! Under construction3334#![cfg_attr(not(feature = "std"), no_std)]35#![allow(clippy::unused_unit)]3637use frame_support::{38 dispatch::DispatchResult,39 ensure,40 pallet_prelude::*,41 traits::{fungible, fungibles, Currency, EnsureOrigin},42 RuntimeDebug,43};44use frame_system::pallet_prelude::*;45use up_data_structs::{CollectionMode};46use pallet_fungible::{Pallet as PalletFungible};47use scale_info::{TypeInfo};48use sp_runtime::{49 traits::{One, Zero},50 ArithmeticError,51};52use sp_std::{boxed::Box, vec::Vec};53use up_data_structs::{CollectionId, TokenId, CreateCollectionData};5455// NOTE:v1::MultiLocation is used in storages, we would need to do migration if upgrade the56// MultiLocation in the future.57use xcm::opaque::latest::prelude::XcmError;58use xcm::{v1::MultiLocation, VersionedMultiLocation};59use xcm_executor::{traits::WeightTrader, Assets};6061use pallet_common::erc::CrossAccountId;6263#[cfg(feature = "std")]64use serde::{Deserialize, Serialize};6566// TODO: Move to primitives67// Id of native currency.68// 0 - QTZ\UNQ69// 1 - KSM\DOT70#[derive(71 Clone,72 Copy,73 Eq,74 PartialEq,75 PartialOrd,76 Ord,77 MaxEncodedLen,78 RuntimeDebug,79 Encode,80 Decode,81 TypeInfo,82)]83#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]84pub enum NativeCurrency {85 Here = 0,86 Parent = 1,87}8889#[derive(90 Clone,91 Copy,92 Eq,93 PartialEq,94 PartialOrd,95 Ord,96 MaxEncodedLen,97 RuntimeDebug,98 Encode,99 Decode,100 TypeInfo,101)]102#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]103pub enum AssetIds {104 ForeignAssetId(ForeignAssetId),105 NativeAssetId(NativeCurrency),106}107108pub trait TryAsForeign<T, F> {109 fn try_as_foreign(asset: T) -> Option<F>;110}111112impl TryAsForeign<AssetIds, ForeignAssetId> for AssetIds {113 fn try_as_foreign(asset: AssetIds) -> Option<ForeignAssetId> {114 match asset {115 AssetIds::ForeignAssetId(id) => Some(id),116 _ => None,117 }118 }119}120121pub type ForeignAssetId = u32;122pub type CurrencyId = AssetIds;123124mod impl_fungibles;125pub mod weights;126127#[cfg(feature = "runtime-benchmarks")]128mod benchmarking;129130pub use module::*;131pub use weights::WeightInfo;132133/// Type alias for currency balance.134pub type BalanceOf<T> =135 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;136137/// A mapping between ForeignAssetId and AssetMetadata.138pub trait AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata> {139 /// Returns the AssetMetadata associated with a given ForeignAssetId.140 fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata>;141 /// Returns the MultiLocation associated with a given ForeignAssetId.142 fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation>;143 /// Returns the CurrencyId associated with a given MultiLocation.144 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId>;145}146147pub struct XcmForeignAssetIdMapping<T>(sp_std::marker::PhantomData<T>);148149impl<T: Config> AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata<BalanceOf<T>>>150 for XcmForeignAssetIdMapping<T>151{152 fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {153 log::trace!(target: "fassets::asset_metadatas", "call");154 Pallet::<T>::asset_metadatas(AssetIds::ForeignAssetId(foreign_asset_id))155 }156157 fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {158 log::trace!(target: "fassets::get_multi_location", "call");159 Pallet::<T>::foreign_asset_locations(foreign_asset_id)160 }161162 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {163 log::trace!(target: "fassets::get_currency_id", "call");164 Some(AssetIds::ForeignAssetId(165 Pallet::<T>::location_to_currency_ids(multi_location).unwrap_or(0),166 ))167 }168}169170#[frame_support::pallet]171pub mod module {172 use super::*;173174 #[pallet::config]175 pub trait Config:176 frame_system::Config177 + pallet_common::Config178 + pallet_fungible::Config179 + orml_tokens::Config180 + pallet_balances::Config181 {182 /// The overarching event type.183 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;184185 /// Currency type for withdraw and balance storage.186 type Currency: Currency<Self::AccountId>;187188 /// Required origin for registering asset.189 type RegisterOrigin: EnsureOrigin<Self::Origin>;190191 /// Weight information for the extrinsics in this module.192 type WeightInfo: WeightInfo;193 }194195 #[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo)]196 pub struct AssetMetadata<Balance> {197 pub name: Vec<u8>,198 pub symbol: Vec<u8>,199 pub decimals: u8,200 pub minimal_balance: Balance,201 }202203 #[pallet::error]204 pub enum Error<T> {205 /// The given location could not be used (e.g. because it cannot be expressed in the206 /// desired version of XCM).207 BadLocation,208 /// MultiLocation existed209 MultiLocationExisted,210 /// AssetId not exists211 AssetIdNotExists,212 /// AssetId exists213 AssetIdExisted,214 }215216 #[pallet::event]217 #[pallet::generate_deposit(fn deposit_event)]218 pub enum Event<T: Config> {219 /// The foreign asset registered.220 ForeignAssetRegistered {221 asset_id: ForeignAssetId,222 asset_address: MultiLocation,223 metadata: AssetMetadata<BalanceOf<T>>,224 },225 /// The foreign asset updated.226 ForeignAssetUpdated {227 asset_id: ForeignAssetId,228 asset_address: MultiLocation,229 metadata: AssetMetadata<BalanceOf<T>>,230 },231 /// The asset registered.232 AssetRegistered {233 asset_id: AssetIds,234 metadata: AssetMetadata<BalanceOf<T>>,235 },236 /// The asset updated.237 AssetUpdated {238 asset_id: AssetIds,239 metadata: AssetMetadata<BalanceOf<T>>,240 },241 }242243 /// Next available Foreign AssetId ID.244 ///245 /// NextForeignAssetId: ForeignAssetId246 #[pallet::storage]247 #[pallet::getter(fn next_foreign_asset_id)]248 pub type NextForeignAssetId<T: Config> = StorageValue<_, ForeignAssetId, ValueQuery>;249 /// The storages for MultiLocations.250 ///251 /// ForeignAssetLocations: map ForeignAssetId => Option<MultiLocation>252 #[pallet::storage]253 #[pallet::getter(fn foreign_asset_locations)]254 pub type ForeignAssetLocations<T: Config> =255 StorageMap<_, Twox64Concat, ForeignAssetId, MultiLocation, OptionQuery>;256257 /// The storages for CurrencyIds.258 ///259 /// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>260 #[pallet::storage]261 #[pallet::getter(fn location_to_currency_ids)]262 pub type LocationToCurrencyIds<T: Config> =263 StorageMap<_, Twox64Concat, MultiLocation, ForeignAssetId, OptionQuery>;264265 /// The storages for AssetMetadatas.266 ///267 /// AssetMetadatas: map AssetIds => Option<AssetMetadata>268 #[pallet::storage]269 #[pallet::getter(fn asset_metadatas)]270 pub type AssetMetadatas<T: Config> =271 StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;272273 /// The storages for assets to fungible collection binding274 ///275 #[pallet::storage]276 #[pallet::getter(fn asset_binding)]277 pub type AssetBinding<T: Config> =278 StorageMap<_, Twox64Concat, ForeignAssetId, CollectionId, OptionQuery>;279280 #[pallet::pallet]281 #[pallet::without_storage_info]282 pub struct Pallet<T>(_);283284 #[pallet::call]285 impl<T: Config> Pallet<T> {286 #[pallet::weight(<T as Config>::WeightInfo::register_foreign_asset())]287 pub fn register_foreign_asset(288 origin: OriginFor<T>,289 owner: T::AccountId,290 location: Box<VersionedMultiLocation>,291 metadata: Box<AssetMetadata<BalanceOf<T>>>,292 ) -> DispatchResult {293 T::RegisterOrigin::ensure_origin(origin.clone())?;294295 let location: MultiLocation = (*location)296 .try_into()297 .map_err(|()| Error::<T>::BadLocation)?;298299 let md = metadata.clone();300 let name: Vec<u16> = md.name.into_iter().map(|x| x as u16).collect::<Vec<u16>>();301 let mut description: Vec<u16> = "Foreign assets collection for "302 .encode_utf16()303 .collect::<Vec<u16>>();304 description.append(&mut name.clone());305306 let data: CreateCollectionData<T::AccountId> = CreateCollectionData {307 name: name.try_into().unwrap(),308 description: description.try_into().unwrap(),309 mode: CollectionMode::Fungible(md.decimals),310 ..Default::default()311 };312313 let bounded_collection_id = <PalletFungible<T>>::init_foreign_collection(314 CrossAccountId::from_sub(owner),315 data,316 )?;317 let foreign_asset_id =318 Self::do_register_foreign_asset(&location, &metadata, bounded_collection_id)?;319320 Self::deposit_event(Event::<T>::ForeignAssetRegistered {321 asset_id: foreign_asset_id,322 asset_address: location,323 metadata: *metadata,324 });325 Ok(())326 }327328 #[pallet::weight(<T as Config>::WeightInfo::update_foreign_asset())]329 pub fn update_foreign_asset(330 origin: OriginFor<T>,331 foreign_asset_id: ForeignAssetId,332 location: Box<VersionedMultiLocation>,333 metadata: Box<AssetMetadata<BalanceOf<T>>>,334 ) -> DispatchResult {335 T::RegisterOrigin::ensure_origin(origin)?;336337 let location: MultiLocation = (*location)338 .try_into()339 .map_err(|()| Error::<T>::BadLocation)?;340 Self::do_update_foreign_asset(foreign_asset_id, &location, &metadata)?;341342 Self::deposit_event(Event::<T>::ForeignAssetUpdated {343 asset_id: foreign_asset_id,344 asset_address: location,345 metadata: *metadata,346 });347 Ok(())348 }349 }350}351352impl<T: Config> Pallet<T> {353 fn get_next_foreign_asset_id() -> Result<ForeignAssetId, DispatchError> {354 NextForeignAssetId::<T>::try_mutate(|current| -> Result<ForeignAssetId, DispatchError> {355 let id = *current;356 *current = current357 .checked_add(One::one())358 .ok_or(ArithmeticError::Overflow)?;359 Ok(id)360 })361 }362363 fn do_register_foreign_asset(364 location: &MultiLocation,365 metadata: &AssetMetadata<BalanceOf<T>>,366 bounded_collection_id: CollectionId,367 ) -> Result<ForeignAssetId, DispatchError> {368 let foreign_asset_id = Self::get_next_foreign_asset_id()?;369 LocationToCurrencyIds::<T>::try_mutate(location, |maybe_currency_ids| -> DispatchResult {370 ensure!(371 maybe_currency_ids.is_none(),372 Error::<T>::MultiLocationExisted373 );374 *maybe_currency_ids = Some(foreign_asset_id);375 // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));376377 ForeignAssetLocations::<T>::try_mutate(378 foreign_asset_id,379 |maybe_location| -> DispatchResult {380 ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);381 *maybe_location = Some(location.clone());382383 AssetMetadatas::<T>::try_mutate(384 AssetIds::ForeignAssetId(foreign_asset_id),385 |maybe_asset_metadatas| -> DispatchResult {386 ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);387 *maybe_asset_metadatas = Some(metadata.clone());388 Ok(())389 },390 )391 },392 )?;393394 AssetBinding::<T>::try_mutate(foreign_asset_id, |collection_id| -> DispatchResult {395 *collection_id = Some(bounded_collection_id);396 Ok(())397 })398 })?;399400 Ok(foreign_asset_id)401 }402403 fn do_update_foreign_asset(404 foreign_asset_id: ForeignAssetId,405 location: &MultiLocation,406 metadata: &AssetMetadata<BalanceOf<T>>,407 ) -> DispatchResult {408 ForeignAssetLocations::<T>::try_mutate(409 foreign_asset_id,410 |maybe_multi_locations| -> DispatchResult {411 let old_multi_locations = maybe_multi_locations412 .as_mut()413 .ok_or(Error::<T>::AssetIdNotExists)?;414415 AssetMetadatas::<T>::try_mutate(416 AssetIds::ForeignAssetId(foreign_asset_id),417 |maybe_asset_metadatas| -> DispatchResult {418 ensure!(419 maybe_asset_metadatas.is_some(),420 Error::<T>::AssetIdNotExists421 );422423 // modify location424 if location != old_multi_locations {425 LocationToCurrencyIds::<T>::remove(old_multi_locations.clone());426 LocationToCurrencyIds::<T>::try_mutate(427 location,428 |maybe_currency_ids| -> DispatchResult {429 ensure!(430 maybe_currency_ids.is_none(),431 Error::<T>::MultiLocationExisted432 );433 // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));434 *maybe_currency_ids = Some(foreign_asset_id);435 Ok(())436 },437 )?;438 }439 *maybe_asset_metadatas = Some(metadata.clone());440 *old_multi_locations = location.clone();441 Ok(())442 },443 )444 },445 )446 }447}448449pub use frame_support::{450 traits::{451 fungibles::{Balanced, CreditOf},452 tokens::currency::Currency as CurrencyT,453 OnUnbalanced as OnUnbalancedT,454 },455 weights::{WeightToFeePolynomial, WeightToFee},456};457458pub struct FreeForAll<459 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,460 AssetId: Get<MultiLocation>,461 AccountId,462 Currency: CurrencyT<AccountId>,463 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,464>(465 Weight,466 Currency::Balance,467 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,468);469470impl<471 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,472 AssetId: Get<MultiLocation>,473 AccountId,474 Currency: CurrencyT<AccountId>,475 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,476 > WeightTrader for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>477{478 fn new() -> Self {479 Self(0, Zero::zero(), PhantomData)480 }481482 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {483 log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);484 Ok(payment)485 }486}487impl<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced> Drop488 for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>489where490 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,491 AssetId: Get<MultiLocation>,492 Currency: CurrencyT<AccountId>,493 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,494{495 fn drop(&mut self) {496 OnUnbalanced::on_unbalanced(Currency::issue(self.1));497 }498}pallets/foreign-assets/src/weights.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/weights.rs
+++ b/pallets/foreign-assets/src/weights.rs
@@ -13,9 +13,9 @@
fn update_foreign_asset() -> Weight;
}
-/// Weights for module_asset_registry using the Acala node and recommended hardware.
-pub struct AcalaWeight<T>(PhantomData<T>);
-impl<T: frame_system::Config> WeightInfo for AcalaWeight<T> {
+/// Weights for pallet_fungible using the Substrate node and recommended hardware.
+pub struct SubstrateWeight<T>(PhantomData<T>);
+impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
fn register_foreign_asset() -> Weight {
(29_819_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
runtime/common/config/pallets/foreign_asset.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/foreign_asset.rs
+++ b/runtime/common/config/pallets/foreign_asset.rs
@@ -5,5 +5,5 @@
type Event = Event;
type Currency = Balances;
type RegisterOrigin = frame_system::EnsureRoot<AccountId>;
- type WeightInfo = ();
+ type WeightInfo = pallet_foreign_assets::weights::SubstrateWeight<Self>;
}