difftreelog
feat draft xcm deposit_asset
in: master
8 files changed
pallets/balances-adapter/src/common.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/common.rs
+++ b/pallets/balances-adapter/src/common.rs
@@ -1,10 +1,16 @@
use alloc::{vec, vec::Vec};
use core::marker::PhantomData;
-use frame_support::{ensure, fail, weights::Weight};
+use frame_support::{
+ ensure, fail,
+ traits::tokens::{fungible::Mutate, Fortitude, Precision},
+ weights::Weight,
+};
use pallet_balances::{weights::SubstrateWeight as BalancesWeight, WeightInfo};
-use pallet_common::{CommonCollectionOperations, CommonWeightInfo, Error as CommonError};
-use up_data_structs::TokenId;
+use pallet_common::{
+ erc::CrossAccountId, CommonCollectionOperations, CommonWeightInfo, Error as CommonError,
+};
+use up_data_structs::{budget::Budget, TokenId};
use crate::{Config, NativeFungibleHandle, Pallet};
@@ -332,6 +338,10 @@
0
}
+ fn xcm_extensions(&self) -> Option<&dyn pallet_common::XcmExtensions<T>> {
+ Some(self)
+ }
+
fn set_allowance_for_all(
&self,
_owner: <T>::CrossAccountId,
@@ -356,3 +366,76 @@
fail!(<CommonError<T>>::UnsupportedOperation);
}
}
+
+impl<T: Config> pallet_common::XcmExtensions<T> for NativeFungibleHandle<T> {
+ fn is_foreign(&self) -> bool {
+ false
+ }
+
+ fn create_item_internal(
+ &self,
+ _depositor: &<T>::CrossAccountId,
+ to: <T>::CrossAccountId,
+ data: up_data_structs::CreateItemData,
+ _nesting_budget: &dyn Budget,
+ ) -> Result<TokenId, sp_runtime::DispatchError> {
+ match &data {
+ up_data_structs::CreateItemData::Fungible(fungible_data) => {
+ T::Mutate::mint_into(
+ to.as_sub(),
+ fungible_data
+ .value
+ .try_into()
+ .map_err(|_| sp_runtime::ArithmeticError::Overflow)?,
+ )?;
+
+ Ok(TokenId::default())
+ }
+ _ => {
+ fail!(<CommonError<T>>::NotFungibleDataUsedToMintFungibleCollectionToken)
+ }
+ }
+ }
+
+ fn transfer_item_internal(
+ &self,
+ _depositor: &<T>::CrossAccountId,
+ from: &<T>::CrossAccountId,
+ to: &<T>::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ _nesting_budget: &dyn Budget,
+ ) -> sp_runtime::DispatchResult {
+ ensure!(
+ token == TokenId::default(),
+ <CommonError<T>>::FungibleItemsHaveNoId
+ );
+
+ <Pallet<T>>::transfer(from, to, amount)
+ .map(|_| ())
+ .map_err(|post_info| post_info.error)
+ }
+
+ fn burn_item_internal(
+ &self,
+ from: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> sp_runtime::DispatchResult {
+ ensure!(
+ token == TokenId::default(),
+ <CommonError<T>>::FungibleItemsHaveNoId
+ );
+
+ T::Mutate::burn_from(
+ from.as_sub(),
+ amount
+ .try_into()
+ .map_err(|_| sp_runtime::ArithmeticError::Overflow)?,
+ Precision::Exact,
+ Fortitude::Polite,
+ )?;
+
+ Ok(())
+ }
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -80,15 +80,16 @@
use sp_std::vec::Vec;
use sp_weights::Weight;
use up_data_structs::{
- budget::Budget, AccessMode, Collection, CollectionId, CollectionLimits, CollectionMode,
- CollectionPermissions, CollectionProperties as CollectionPropertiesT, CollectionStats,
- CreateCollectionData, CreateItemData, CreateItemExData, PhantomType, PropertiesError,
- PropertiesPermissionMap, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,
- PropertyScope, PropertyValue, RpcCollection, RpcCollectionFlags, SponsoringRateLimit,
- SponsorshipState, TokenChild, TokenData, TokenId, TokenOwnerError, TokenProperties,
- TrySetProperty, COLLECTION_ADMINS_LIMIT, COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT,
- FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP,
- MAX_TOKEN_PREFIX_LENGTH, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+ budget::Budget, mapping::TokenAddressMapping, AccessMode, Collection, CollectionId,
+ CollectionLimits, CollectionMode, CollectionPermissions,
+ CollectionProperties as CollectionPropertiesT, CollectionStats, CreateCollectionData,
+ CreateItemData, CreateItemExData, PhantomType, PropertiesError, PropertiesPermissionMap,
+ Property, PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,
+ RpcCollection, RpcCollectionFlags, SponsoringRateLimit, SponsorshipState, TokenChild,
+ TokenData, TokenId, TokenOwnerError, TokenProperties, TrySetProperty, COLLECTION_ADMINS_LIMIT,
+ COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+ MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_TOKEN_PREFIX_LENGTH,
+ NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
};
use up_pov_estimate_rpc::PovInfo;
@@ -786,6 +787,9 @@
/// Fungible tokens hold no ID, and the default value of TokenId for a fungible collection is 0.
FungibleItemsHaveNoId,
+
+ /// Not Fungible item data used to mint in Fungible collection.
+ NotFungibleDataUsedToMintFungibleCollectionToken,
}
/// Storage of the count of created collections. Essentially contains the last collection ID.
@@ -2347,24 +2351,77 @@
/// Is the collection a foreign one?
fn is_foreign(&self) -> bool;
- /// Create a collection's item.
+ /// Create a collection's item using a transaction.
+ ///
+ /// This function performs additional XCM-related checks before the actual creation.
+ #[transactional]
fn create_item(
&self,
+ depositor: &T::CrossAccountId,
+ to: T::CrossAccountId,
+ data: CreateItemData,
+ nesting_budget: &dyn Budget,
+ ) -> Result<TokenId, DispatchError> {
+ if T::CrossTokenAddressMapping::is_token_address(&to) {
+ return unsupported!(T);
+ }
+
+ self.create_item_internal(depositor, to, data, nesting_budget)
+ }
+
+ /// Create a collection's item.
+ fn create_item_internal(
+ &self,
+ depositor: &T::CrossAccountId,
to: T::CrossAccountId,
data: CreateItemData,
+ nesting_budget: &dyn Budget,
) -> Result<TokenId, DispatchError>;
+ /// Transfer an item from the `from` account to the `to` account using a transaction.
+ ///
+ /// This function performs additional XCM-related checks before the actual transfer.
+ #[transactional]
+ fn transfer_item(
+ &self,
+ depositor: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ nesting_budget: &dyn Budget,
+ ) -> DispatchResult {
+ if T::CrossTokenAddressMapping::is_token_address(&to) {
+ return unsupported!(T);
+ }
+
+ self.transfer_item_internal(depositor, from, to, token, amount, nesting_budget)
+ }
+
/// Transfer an item from the `from` account to the `to` account.
- fn transfer(
+ fn transfer_item_internal(
&self,
- from: T::CrossAccountId,
- to: T::CrossAccountId,
+ depositor: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
token: TokenId,
amount: u128,
+ nesting_budget: &dyn Budget,
) -> DispatchResult;
+ /// Burn a collection's item using a transaction.
+ #[transactional]
+ fn burn_item(&self, from: T::CrossAccountId, token: TokenId, amount: u128) -> DispatchResult {
+ self.burn_item_internal(from, token, amount)
+ }
+
/// Burn a collection's item.
- fn burn(&self, from: T::CrossAccountId, token: TokenId, amount: u128) -> DispatchResult;
+ fn burn_item_internal(
+ &self,
+ from: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResult;
}
/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -22,13 +22,6 @@
//!
//! ## Overview
//!
-//! The foreign assests pallet provides functions for:
-//!
-//! - Local and foreign assets management. The foreign assets can be updated without runtime upgrade.
-//! - Bounds between asset and target collection for cross chain transfer and inner transfers.
-//!
-//! ## Overview
-//!
//! Under construction
#![cfg_attr(not(feature = "std"), no_std)]
@@ -37,22 +30,21 @@
use frame_support::{dispatch::DispatchResult, pallet_prelude::*, traits::EnsureOrigin, PalletId};
use frame_system::pallet_prelude::*;
use pallet_common::{
- dispatch::CollectionDispatch, erc::CrossAccountId, NATIVE_FUNGIBLE_COLLECTION_ID,
+ dispatch::CollectionDispatch, erc::CrossAccountId, XcmExtensions, NATIVE_FUNGIBLE_COLLECTION_ID,
};
use sp_runtime::traits::AccountIdConversion;
use sp_std::{vec, vec::Vec};
-// NOTE: MultiLocation is used in storages, we will need to do migration if upgrade the
-// MultiLocation to the XCM v3.
use staging_xcm::{
opaque::latest::{prelude::XcmError, Weight},
v3::{prelude::*, MultiAsset, XcmContext},
};
use staging_xcm_executor::{
- traits::{TransactAsset, WeightTrader},
+ traits::{ConvertLocation, Error as XcmExecutorError, TransactAsset, WeightTrader},
Assets,
};
use up_data_structs::{
- CollectionId, CollectionMode, CollectionName, CreateCollectionData, PropertyKey, TokenId,
+ budget::ZeroBudget, CollectionId, CollectionMode, CollectionName, CreateCollectionData,
+ CreateFungibleData, CreateItemData, CreateNftData, Property, PropertyKey, TokenId,
};
pub mod weights;
@@ -87,6 +79,12 @@
/// The ID of the foreign assets pallet.
type PalletId: Get<PalletId>;
+ /// Self-location of this parachain.
+ type SelfLocation: Get<MultiLocation>;
+
+ /// The converter from a MultiLocation to a CrossAccountId.
+ type LocationToAccountId: ConvertLocation<Self::CrossAccountId>;
+
/// Weight information for the extrinsics in this module.
type WeightInfo: WeightInfo;
}
@@ -113,6 +111,12 @@
pub type ForeignReserveLocationToCollection<T: Config> =
StorageMap<_, Twox64Concat, staging_xcm::v3::MultiLocation, CollectionId, OptionQuery>;
+ /// The corresponding reserve location of collections.
+ #[pallet::storage]
+ #[pallet::getter(fn collection_to_foreign_reserve_location)]
+ pub type CollectionToForeignReserveLocation<T: Config> =
+ StorageMap<_, Twox64Concat, CollectionId, staging_xcm::v3::MultiLocation, OptionQuery>;
+
/// The correponding NFT token id of reserve NFTs
#[pallet::storage]
#[pallet::getter(fn foreign_reserve_asset_instance_to_token_id)]
@@ -180,6 +184,7 @@
)?;
<ForeignReserveLocationToCollection<T>>::insert(reserve_location, collection_id);
+ <CollectionToForeignReserveLocation<T>>::insert(collection_id, reserve_location);
Self::deposit_event(Event::<T>::ForeignAssetRegistered {
asset_id: collection_id,
@@ -210,6 +215,132 @@
.try_into()
.expect("key length < max property key length; qed")
}
+
+ fn native_asset_location_to_collection(
+ asset_location: &MultiLocation,
+ ) -> Result<Option<CollectionId>, XcmError> {
+ let self_location = T::SelfLocation::get();
+
+ if *asset_location == Here.into() {
+ Ok(Some(NATIVE_FUNGIBLE_COLLECTION_ID))
+ } else if *asset_location == self_location {
+ Ok(Some(NATIVE_FUNGIBLE_COLLECTION_ID))
+ } else if asset_location.parents == self_location.parents {
+ match asset_location
+ .interior
+ .match_and_split(&self_location.interior)
+ {
+ Some(GeneralIndex(collection_id)) => Ok(Some(CollectionId(
+ (*collection_id)
+ .try_into()
+ .map_err(|_| XcmExecutorError::AssetIdConversionFailed)?,
+ ))),
+ _ => Ok(None),
+ }
+ } else {
+ Ok(None)
+ }
+ }
+
+ fn multiasset_to_collection(asset: &MultiAsset) -> Result<CollectionId, XcmError> {
+ let AssetId::Concrete(asset_reserve_location) = asset.id else {
+ return Err(XcmExecutorError::AssetNotHandled.into());
+ };
+
+ Self::native_asset_location_to_collection(&asset_reserve_location)?
+ .or_else(|| Self::foreign_reserve_location_to_collection(asset_reserve_location))
+ .ok_or_else(|| XcmExecutorError::AssetIdConversionFailed.into())
+ }
+
+ fn native_asset_instance_to_token_id(
+ asset_instance: &AssetInstance,
+ ) -> Result<TokenId, XcmError> {
+ match asset_instance {
+ AssetInstance::Index(token_id) => Ok(TokenId(
+ (*token_id)
+ .try_into()
+ .map_err(|_| XcmError::AssetNotFound)?,
+ )),
+ _ => Err(XcmError::AssetNotFound),
+ }
+ }
+
+ /// Obtains the token id of the `asset_instance` in the collection.
+ ///
+ /// Returns `Ok(None)` only if the `asset_instance` points to a foreign item
+ /// and it haven't been created on this blockchain yet.
+ ///
+ /// If the `asset_instance` points to a native item, it cannot return `Ok(None)`.
+ fn asset_instance_to_token_id(
+ xcm_ext: &dyn XcmExtensions<T>,
+ collection_id: CollectionId,
+ asset_instance: &AssetInstance,
+ ) -> Result<Option<TokenId>, XcmError> {
+ if xcm_ext.is_foreign() {
+ Ok(Self::foreign_reserve_asset_instance_to_token_id(
+ collection_id,
+ asset_instance,
+ ))
+ } else {
+ Self::native_asset_instance_to_token_id(asset_instance).map(Some)
+ }
+ }
+
+ fn create_foreign_asset_instance(
+ xcm_ext: &dyn XcmExtensions<T>,
+ collection_id: CollectionId,
+ asset_instance: &AssetInstance,
+ to: T::CrossAccountId,
+ ) -> XcmResult {
+ let asset_instance_encoded = asset_instance.encode();
+
+ let derivative_token_id = xcm_ext
+ .create_item(
+ &Self::pallet_account(),
+ to,
+ CreateItemData::NFT(CreateNftData {
+ properties: vec![Property {
+ key: Self::reserve_asset_instance_property_key(),
+ value: asset_instance_encoded
+ .try_into()
+ .expect("asset instance length <= 32 bytes which is less than value length limit; qed"),
+ }]
+ .try_into()
+ .expect("just one property can always be stored; qed"),
+ }),
+ &ZeroBudget,
+ )
+ .map_err(|_| XcmError::FailedToTransactAsset("non-fungible item deposit failed"))?;
+
+ <ForeignReserveAssetInstanceToTokenId<T>>::insert(
+ collection_id,
+ asset_instance,
+ derivative_token_id,
+ );
+
+ Ok(())
+ }
+
+ fn deposit_asset_instance(
+ xcm_ext: &dyn XcmExtensions<T>,
+ collection_id: CollectionId,
+ to: T::CrossAccountId,
+ asset_instance: &AssetInstance,
+ ) -> XcmResult {
+ if let Some(token_id) =
+ Self::asset_instance_to_token_id(xcm_ext, collection_id, asset_instance)?
+ {
+ let depositor = &Self::pallet_account();
+ let from = depositor;
+ let amount = 1;
+
+ xcm_ext
+ .transfer_item(depositor, from, &to, token_id, amount, &ZeroBudget)
+ .map_err(|_| XcmError::FailedToTransactAsset("non-fungible item deposit failed"))
+ } else {
+ Self::create_foreign_asset_instance(xcm_ext, collection_id, asset_instance, to)
+ }
+ }
}
impl<T: Config> TransactAsset for Pallet<T> {
@@ -234,7 +365,31 @@
fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
fn deposit_asset(what: &MultiAsset, to: &MultiLocation, context: &XcmContext) -> XcmResult {
- Err(XcmError::Unimplemented)
+ let collection_id = Self::multiasset_to_collection(what)?;
+ let dispatch =
+ T::CollectionDispatch::dispatch(collection_id).map_err(|_| XcmError::AssetNotFound)?;
+
+ let collection = dispatch.as_dyn();
+ let xcm_ext = collection.xcm_extensions().ok_or(XcmError::Unimplemented)?;
+
+ let to = T::LocationToAccountId::convert_location(to)
+ .ok_or(XcmExecutorError::AccountIdConversionFailed)?;
+
+ match what.fun {
+ Fungibility::Fungible(amount) => xcm_ext
+ .create_item(
+ &Self::pallet_account(),
+ to,
+ CreateItemData::Fungible(CreateFungibleData { value: amount }),
+ &ZeroBudget,
+ )
+ .map(|_| ())
+ .map_err(|_| XcmError::FailedToTransactAsset("fungible item deposit failed")),
+
+ Fungibility::NonFungible(asset_instance) => {
+ Self::deposit_asset_instance(xcm_ext, collection_id, to, &asset_instance)
+ }
+ }
}
fn withdraw_asset(
@@ -263,20 +418,17 @@
if collection_id == NATIVE_FUNGIBLE_COLLECTION_ID {
Some(Here.into())
} else {
- // let dispatch = T::CollectionDispatch::dispatch(collection_id).ok()?;
- // let collection = dispatch.as_dyn();
- // let xcm_ext = collection.xcm_extensions()?;
+ let dispatch = T::CollectionDispatch::dispatch(collection_id).ok()?;
+ let collection = dispatch.as_dyn();
+ let xcm_ext = collection.xcm_extensions()?;
- // if xcm_ext.is_foreign() {
- // let encoded_location =
- // collection.property(&<Pallet<T>>::reserve_location_property_key())?;
- // MultiLocation::decode(&mut &encoded_location[..]).ok()
- // } else {
- // T::SelfLocation::get()
- // .pushed_with_interior(GeneralIndex(collection_id.0.into()))
- // .ok()
- // }
- todo!()
+ if xcm_ext.is_foreign() {
+ <Pallet<T>>::collection_to_foreign_reserve_location(collection_id)
+ } else {
+ T::SelfLocation::get()
+ .pushed_with_interior(GeneralIndex(collection_id.0.into()))
+ .ok()
+ }
}
}
}
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -19,7 +19,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use pallet_common::{
weights::WeightInfo as _, with_weight, CommonCollectionOperations, CommonWeightInfo,
- Error as CommonError, RefungibleExtensions, SelfWeightOf as PalletCommonWeightOf,
+ Error as CommonError, SelfWeightOf as PalletCommonWeightOf, XcmExtensions,
};
use sp_runtime::{ArithmeticError, DispatchError};
use sp_std::{vec, vec::Vec};
@@ -114,7 +114,7 @@
<Pallet<T>>::create_item(self, &sender, (to, fungible_data.value), nesting_budget),
<CommonWeights<T>>::create_item(&data),
),
- _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ _ => fail!(<CommonError<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
}
}
@@ -133,7 +133,7 @@
.checked_add(data.value)
.ok_or(ArithmeticError::Overflow)?;
}
- _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ _ => fail!(<CommonError<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
}
}
@@ -152,7 +152,7 @@
let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
let data = match data {
up_data_structs::CreateItemExData::Fungible(f) => f,
- _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ _ => fail!(<CommonError<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
};
with_weight(
@@ -435,6 +435,10 @@
<TotalSupply<T>>::try_get(self.id).ok()
}
+ fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {
+ Some(self)
+ }
+
fn set_allowance_for_all(
&self,
_owner: T::CrossAccountId,
@@ -453,3 +457,61 @@
fail!(<Error<T>>::FungibleTokensAreAlwaysValid)
}
}
+
+impl<T: Config> XcmExtensions<T> for FungibleHandle<T> {
+ fn is_foreign(&self) -> bool {
+ self.flags.foreign
+ }
+
+ fn create_item_internal(
+ &self,
+ depositor: &<T>::CrossAccountId,
+ to: <T>::CrossAccountId,
+ data: CreateItemData,
+ nesting_budget: &dyn Budget,
+ ) -> Result<TokenId, sp_runtime::DispatchError> {
+ match &data {
+ up_data_structs::CreateItemData::Fungible(fungible_data) => {
+ <Pallet<T>>::create_multiple_items(
+ self,
+ &depositor,
+ [(to, fungible_data.value)].into_iter().collect(),
+ nesting_budget,
+ )?
+ }
+ _ => fail!(<CommonError<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ }
+
+ Ok(TokenId::default())
+ }
+
+ fn transfer_item_internal(
+ &self,
+ depositor: &<T>::CrossAccountId,
+ from: &<T>::CrossAccountId,
+ to: &<T>::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ nesting_budget: &dyn Budget,
+ ) -> sp_runtime::DispatchResult {
+ ensure!(
+ token == TokenId::default(),
+ <CommonError<T>>::FungibleItemsHaveNoId
+ );
+
+ <Pallet<T>>::transfer_internal(self, &depositor, &from, &to, amount, nesting_budget)
+ .map(|_| ())
+ .map_err(|post_info| post_info.error)
+ }
+
+ fn burn_item_internal(
+ &self,
+ from: <T>::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> sp_runtime::DispatchResult {
+ <Self as CommonCollectionOperations<T>>::burn_item(&self, from, token, amount)
+ .map(|_| ())
+ .map_err(|post_info| post_info.error)
+ }
+}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -95,8 +95,9 @@
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
use sp_std::{collections::btree_map::BTreeMap, vec::Vec};
use up_data_structs::{
- budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId, CreateCollectionData,
- Property, PropertyKey, TokenId,
+ budget::{Budget, ZeroBudget},
+ mapping::TokenAddressMapping,
+ AccessMode, CollectionId, CreateCollectionData, Property, PropertyKey, TokenId,
};
use weights::WeightInfo;
@@ -121,8 +122,6 @@
#[pallet::error]
pub enum Error<T> {
- /// Not Fungible item data used to mint in Fungible collection.
- NotFungibleDataUsedToMintFungibleCollectionToken,
/// Tried to set data for fungible item.
FungibleItemsDontHaveData,
/// Fungible token does not support nesting.
@@ -275,9 +274,6 @@
let balance = <Balance<T>>::get((collection.id, owner))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
-
- // Foreign collection check
- ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);
if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(owner)?;
@@ -309,47 +305,7 @@
));
Ok(())
}
-
- /// Burns the specified amount of the token.
- pub fn burn_foreign(
- collection: &FungibleHandle<T>,
- owner: &T::CrossAccountId,
- amount: u128,
- ) -> DispatchResult {
- let total_supply = <TotalSupply<T>>::get(collection.id)
- .checked_sub(amount)
- .ok_or(<CommonError<T>>::TokenValueTooLow)?;
-
- let balance = <Balance<T>>::get((collection.id, owner))
- .checked_sub(amount)
- .ok_or(<CommonError<T>>::TokenValueTooLow)?;
- // =========
- if balance == 0 {
- <Balance<T>>::remove((collection.id, owner));
- <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());
- } else {
- <Balance<T>>::insert((collection.id, owner), balance);
- }
- <TotalSupply<T>>::insert(collection.id, total_supply);
-
- <PalletEvm<T>>::deposit_log(
- ERC20Events::Transfer {
- from: *owner.as_eth(),
- to: H160::default(),
- value: amount.into(),
- }
- .to_log(collection_id_to_address(collection.id)),
- );
- <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
- collection.id,
- TokenId::default(),
- owner.clone(),
- amount,
- ));
- Ok(())
- }
-
/// Transfers the specified amount of tokens. Will check that
/// the transfer is allowed for the token.
///
@@ -450,14 +406,25 @@
}
/// Minting tokens for multiple IDs.
- /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]
- /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]
- pub fn create_multiple_items_common(
+ /// See [`create_item`][`Pallet::create_item`] for more details.
+ pub fn create_multiple_items(
collection: &FungibleHandle<T>,
- sender: &T::CrossAccountId,
+ depositor: &T::CrossAccountId,
data: BTreeMap<T::CrossAccountId, u128>,
nesting_budget: &dyn Budget,
) -> DispatchResult {
+ if !collection.is_owner_or_admin(depositor) {
+ ensure!(
+ collection.permissions.mint_mode(),
+ <CommonError<T>>::PublicMintingNotAllowed
+ );
+ collection.check_allowlist(depositor)?;
+
+ for (owner, _) in data.iter() {
+ collection.check_allowlist(owner)?;
+ }
+ }
+
let total_supply = data
.values()
.copied()
@@ -468,7 +435,7 @@
for (to, _) in data.iter() {
<PalletStructure<T>>::check_nesting(
- sender,
+ depositor,
to,
collection.id,
TokenId::default(),
@@ -514,44 +481,7 @@
Ok(())
}
-
- /// Minting tokens for multiple IDs.
- /// See [`create_item`][`Pallet::create_item`] for more details.
- pub fn create_multiple_items(
- collection: &FungibleHandle<T>,
- sender: &T::CrossAccountId,
- data: BTreeMap<T::CrossAccountId, u128>,
- nesting_budget: &dyn Budget,
- ) -> DispatchResult {
- // Foreign collection check
- ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);
-
- if !collection.is_owner_or_admin(sender) {
- ensure!(
- collection.permissions.mint_mode(),
- <CommonError<T>>::PublicMintingNotAllowed
- );
- collection.check_allowlist(sender)?;
-
- for (owner, _) in data.iter() {
- collection.check_allowlist(owner)?;
- }
- }
- Self::create_multiple_items_common(collection, sender, data, nesting_budget)
- }
-
- /// Minting tokens for multiple IDs.
- /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.
- pub fn create_multiple_items_foreign(
- collection: &FungibleHandle<T>,
- sender: &T::CrossAccountId,
- data: BTreeMap<T::CrossAccountId, u128>,
- nesting_budget: &dyn Budget,
- ) -> DispatchResult {
- Self::create_multiple_items_common(collection, sender, data, nesting_budget)
- }
-
fn set_allowance_unchecked(
collection: &FungibleHandle<T>,
owner: &T::CrossAccountId,
@@ -777,24 +707,6 @@
nesting_budget: &dyn Budget,
) -> DispatchResult {
Self::create_multiple_items(
- collection,
- sender,
- [(data.0, data.1)].into_iter().collect(),
- nesting_budget,
- )
- }
-
- /// Creates fungible token.
- ///
- /// - `data`: Contains user who will become the owners of the tokens and amount
- /// of tokens he will receive.
- pub fn create_item_foreign(
- collection: &FungibleHandle<T>,
- sender: &T::CrossAccountId,
- data: CreateItemData<T>,
- nesting_budget: &dyn Budget,
- ) -> DispatchResult {
- Self::create_multiple_items_foreign(
collection,
sender,
[(data.0, data.1)].into_iter().collect(),
pallets/nonfungible/src/common.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/>.1617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};20use pallet_common::{21 weights::WeightInfo as _, with_weight, write_token_properties_total_weight,22 CommonCollectionOperations, CommonWeightInfo, SelfWeightOf as PalletCommonWeightOf,23 XcmExtensions,24};25use pallet_structure::Pallet as PalletStructure;26use sp_runtime::DispatchError;27use sp_std::{vec, vec::Vec};28use up_data_structs::{29 budget::Budget, CollectionId, CreateItemExData, Property, PropertyKey, PropertyKeyPermission,30 PropertyValue, TokenId, TokenOwnerError,31};3233use crate::{34 weights::WeightInfo, AccountBalance, Allowance, Config, CreateItemData, Error,35 NonfungibleHandle, Owned, Pallet, SelfWeightOf, TokenData, TokenProperties, TokensMinted,36};3738pub struct CommonWeights<T: Config>(PhantomData<T>);39impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {40 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {41 match data {42 CreateItemExData::NFT(t) => mint_with_props_weight::<T>(43 <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32),44 t.iter().map(|t| t.properties.len() as u32),45 ),46 _ => Weight::zero(),47 }48 }4950 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {51 mint_with_props_weight::<T>(52 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32),53 data.iter().map(|t| match t {54 up_data_structs::CreateItemData::NFT(n) => n.properties.len() as u32,55 _ => 0,56 }),57 )58 }5960 fn burn_item() -> Weight {61 <SelfWeightOf<T>>::burn_item()62 }6364 fn set_collection_properties(amount: u32) -> Weight {65 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)66 }6768 fn set_token_properties(amount: u32) -> Weight {69 write_token_properties_total_weight::<T, _>([amount].into_iter(), |amount| {70 <SelfWeightOf<T>>::load_token_properties()71 .saturating_add(<SelfWeightOf<T>>::write_token_properties(amount))72 })73 }7475 fn delete_token_properties(amount: u32) -> Weight {76 Self::set_token_properties(amount)77 }7879 fn set_token_property_permissions(amount: u32) -> Weight {80 <SelfWeightOf<T>>::set_token_property_permissions(amount)81 }8283 fn transfer() -> Weight {84 <SelfWeightOf<T>>::transfer_raw()85 .saturating_add(<PalletCommonWeightOf<T>>::check_accesslist().saturating_mul(2))86 }8788 fn approve() -> Weight {89 <SelfWeightOf<T>>::approve()90 }9192 fn approve_from() -> Weight {93 <SelfWeightOf<T>>::approve_from()94 }9596 fn transfer_from() -> Weight {97 Self::transfer().saturating_add(<SelfWeightOf<T>>::check_allowed_raw())98 }99100 fn burn_from() -> Weight {101 <SelfWeightOf<T>>::burn_from()102 }103104 fn set_allowance_for_all() -> Weight {105 <SelfWeightOf<T>>::set_allowance_for_all()106 }107108 fn force_repair_item() -> Weight {109 <SelfWeightOf<T>>::repair_item()110 }111}112113/// Weight of minting tokens with properties114/// * `create_no_data_weight` -- the weight of minting without properties115/// * `token_properties_nums` -- number of properties of each token116#[inline]117pub(crate) fn mint_with_props_weight<T: Config>(118 create_no_data_weight: Weight,119 token_properties_nums: impl Iterator<Item = u32> + Clone,120) -> Weight {121 create_no_data_weight.saturating_add(write_token_properties_total_weight::<T, _>(122 token_properties_nums,123 <SelfWeightOf<T>>::write_token_properties,124 ))125}126127fn map_create_data<T: Config>(128 data: up_data_structs::CreateItemData,129 to: &T::CrossAccountId,130) -> Result<CreateItemData<T>, DispatchError> {131 match data {132 up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {133 properties: data.properties,134 owner: to.clone(),135 }),136 _ => fail!(<Error<T>>::NotNonfungibleDataUsedToMintFungibleCollectionToken),137 }138}139140/// Implementation of `CommonCollectionOperations` for `NonfungibleHandle`. It wraps Nonfungible Pallete141/// methods and adds weight info.142impl<T: Config> CommonCollectionOperations<T> for NonfungibleHandle<T> {143 fn create_item(144 &self,145 sender: T::CrossAccountId,146 to: T::CrossAccountId,147 data: up_data_structs::CreateItemData,148 nesting_budget: &dyn Budget,149 ) -> DispatchResultWithPostInfo {150 let weight = <CommonWeights<T>>::create_item(&data);151 with_weight(152 <Pallet<T>>::create_item(153 self,154 &sender,155 map_create_data::<T>(data, &to)?,156 nesting_budget,157 ),158 weight,159 )160 }161162 fn create_multiple_items(163 &self,164 sender: T::CrossAccountId,165 to: T::CrossAccountId,166 data: Vec<up_data_structs::CreateItemData>,167 nesting_budget: &dyn Budget,168 ) -> DispatchResultWithPostInfo {169 let weight = <CommonWeights<T>>::create_multiple_items(&data);170 let data = data171 .into_iter()172 .map(|d| map_create_data::<T>(d, &to))173 .collect::<Result<Vec<_>, DispatchError>>()?;174175 with_weight(176 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),177 weight,178 )179 }180181 fn create_multiple_items_ex(182 &self,183 sender: <T>::CrossAccountId,184 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,185 nesting_budget: &dyn Budget,186 ) -> DispatchResultWithPostInfo {187 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);188 let data = match data {189 up_data_structs::CreateItemExData::NFT(nft) => nft,190 _ => fail!(Error::<T>::NotNonfungibleDataUsedToMintFungibleCollectionToken),191 };192193 with_weight(194 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),195 weight,196 )197 }198199 fn set_collection_properties(200 &self,201 sender: T::CrossAccountId,202 properties: Vec<Property>,203 ) -> DispatchResultWithPostInfo {204 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);205206 with_weight(207 <Pallet<T>>::set_collection_properties(self, &sender, properties),208 weight,209 )210 }211212 fn delete_collection_properties(213 &self,214 sender: &T::CrossAccountId,215 property_keys: Vec<PropertyKey>,216 ) -> DispatchResultWithPostInfo {217 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);218219 with_weight(220 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),221 weight,222 )223 }224225 fn set_token_properties(226 &self,227 sender: T::CrossAccountId,228 token_id: TokenId,229 properties: Vec<Property>,230 nesting_budget: &dyn Budget,231 ) -> DispatchResultWithPostInfo {232 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);233234 with_weight(235 <Pallet<T>>::set_token_properties(236 self,237 &sender,238 token_id,239 properties.into_iter(),240 nesting_budget,241 ),242 weight,243 )244 }245246 fn delete_token_properties(247 &self,248 sender: T::CrossAccountId,249 token_id: TokenId,250 property_keys: Vec<PropertyKey>,251 nesting_budget: &dyn Budget,252 ) -> DispatchResultWithPostInfo {253 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);254255 with_weight(256 <Pallet<T>>::delete_token_properties(257 self,258 &sender,259 token_id,260 property_keys.into_iter(),261 nesting_budget,262 ),263 weight,264 )265 }266267 fn get_token_properties_raw(268 &self,269 token_id: TokenId,270 ) -> Option<up_data_structs::TokenProperties> {271 <TokenProperties<T>>::get((self.id, token_id))272 }273274 fn set_token_properties_raw(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {275 <TokenProperties<T>>::insert((self.id, token_id), map)276 }277278 fn set_token_property_permissions(279 &self,280 sender: &T::CrossAccountId,281 property_permissions: Vec<PropertyKeyPermission>,282 ) -> DispatchResultWithPostInfo {283 let weight =284 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);285286 with_weight(287 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),288 weight,289 )290 }291292 fn burn_item(293 &self,294 sender: T::CrossAccountId,295 token: TokenId,296 amount: u128,297 ) -> DispatchResultWithPostInfo {298 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);299 if amount == 1 {300 with_weight(301 <Pallet<T>>::burn(self, &sender, token),302 <CommonWeights<T>>::burn_item(),303 )304 } else {305 <Pallet<T>>::check_token_immediate_ownership(self, token, &sender)?;306 Ok(().into())307 }308 }309310 fn transfer(311 &self,312 from: T::CrossAccountId,313 to: T::CrossAccountId,314 token: TokenId,315 amount: u128,316 nesting_budget: &dyn Budget,317 ) -> DispatchResultWithPostInfo {318 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);319 if amount == 1 {320 <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget)321 } else {322 <Pallet<T>>::check_token_immediate_ownership(self, token, &from)?;323 Ok(().into())324 }325 }326327 fn approve(328 &self,329 sender: T::CrossAccountId,330 spender: T::CrossAccountId,331 token: TokenId,332 amount: u128,333 ) -> DispatchResultWithPostInfo {334 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);335336 with_weight(337 if amount == 1 {338 <Pallet<T>>::set_allowance(self, &sender, token, Some(&spender))339 } else {340 <Pallet<T>>::set_allowance(self, &sender, token, None)341 },342 <CommonWeights<T>>::approve(),343 )344 }345346 fn approve_from(347 &self,348 sender: T::CrossAccountId,349 from: T::CrossAccountId,350 to: T::CrossAccountId,351 token: TokenId,352 amount: u128,353 ) -> DispatchResultWithPostInfo {354 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);355356 with_weight(357 if amount == 1 {358 <Pallet<T>>::set_allowance_from(self, &sender, &from, token, Some(&to))359 } else {360 <Pallet<T>>::set_allowance_from(self, &sender, &from, token, None)361 },362 <CommonWeights<T>>::approve_from(),363 )364 }365366 fn transfer_from(367 &self,368 sender: T::CrossAccountId,369 from: T::CrossAccountId,370 to: T::CrossAccountId,371 token: TokenId,372 amount: u128,373 nesting_budget: &dyn Budget,374 ) -> DispatchResultWithPostInfo {375 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);376377 if amount == 1 {378 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget)379 } else {380 <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;381382 Ok(().into())383 }384 }385386 fn burn_from(387 &self,388 sender: T::CrossAccountId,389 from: T::CrossAccountId,390 token: TokenId,391 amount: u128,392 nesting_budget: &dyn Budget,393 ) -> DispatchResultWithPostInfo {394 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);395396 if amount == 1 {397 with_weight(398 <Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),399 <CommonWeights<T>>::burn_from(),400 )401 } else {402 <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;403404 Ok(().into())405 }406 }407408 fn check_nesting(409 &self,410 sender: &T::CrossAccountId,411 from: (CollectionId, TokenId),412 under: TokenId,413 nesting_budget: &dyn Budget,414 ) -> sp_runtime::DispatchResult {415 <Pallet<T>>::check_nesting(self, sender, from, under, nesting_budget)416 }417418 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId)) {419 <Pallet<T>>::nest((self.id, under), to_nest);420 }421422 fn unnest(&self, under: TokenId, to_unnest: (CollectionId, TokenId)) {423 <Pallet<T>>::unnest((self.id, under), to_unnest);424 }425426 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {427 <Owned<T>>::iter_prefix((self.id, account))428 .map(|(id, _)| id)429 .collect()430 }431432 fn collection_tokens(&self) -> Vec<TokenId> {433 <TokenData<T>>::iter_prefix((self.id,))434 .map(|(id, _)| id)435 .collect()436 }437438 fn token_exists(&self, token: TokenId) -> bool {439 <Pallet<T>>::token_exists(self, token)440 }441442 fn last_token_id(&self) -> TokenId {443 TokenId(<TokensMinted<T>>::get(self.id))444 }445446 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {447 <TokenData<T>>::get((self.id, token))448 .map(|t| t.owner)449 .ok_or(TokenOwnerError::NotFound)450 }451452 fn check_token_indirect_owner(453 &self,454 token: TokenId,455 maybe_owner: &T::CrossAccountId,456 nesting_budget: &dyn Budget,457 ) -> Result<bool, DispatchError> {458 <PalletStructure<T>>::check_indirectly_owned(459 maybe_owner.clone(),460 self.id,461 token,462 None,463 nesting_budget,464 )465 }466467 /// Returns token owners.468 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {469 self.token_owner(token).map_or_else(|_| vec![], |t| vec![t])470 }471472 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {473 <Pallet<T>>::token_properties((self.id, token_id))?474 .get(key)475 .cloned()476 }477478 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {479 let Some(properties) = <Pallet<T>>::token_properties((self.id, token_id)) else {480 return vec![];481 };482483 keys.map(|keys| {484 keys.into_iter()485 .filter_map(|key| {486 properties.get(&key).map(|value| Property {487 key,488 value: value.clone(),489 })490 })491 .collect()492 })493 .unwrap_or_else(|| {494 properties495 .into_iter()496 .map(|(key, value)| Property { key, value })497 .collect()498 })499 }500501 fn total_supply(&self) -> u32 {502 <Pallet<T>>::total_supply(self)503 }504505 fn account_balance(&self, account: T::CrossAccountId) -> u32 {506 <AccountBalance<T>>::get((self.id, account))507 }508509 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {510 if <TokenData<T>>::get((self.id, token))511 .map(|a| a.owner == account)512 .unwrap_or(false)513 {514 1515 } else {516 0517 }518 }519520 fn allowance(521 &self,522 sender: T::CrossAccountId,523 spender: T::CrossAccountId,524 token: TokenId,525 ) -> u128 {526 if <TokenData<T>>::get((self.id, token))527 .map(|a| a.owner != sender)528 .unwrap_or(true)529 {530 0531 } else if <Allowance<T>>::get((self.id, token)) == Some(spender) {532 1533 } else {534 0535 }536 }537538 fn total_pieces(&self, token: TokenId) -> Option<u128> {539 if <TokenData<T>>::contains_key((self.id, token)) {540 Some(1)541 } else {542 None543 }544 }545546 fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {547 Some(self)548 }549550 fn set_allowance_for_all(551 &self,552 owner: T::CrossAccountId,553 operator: T::CrossAccountId,554 approve: bool,555 ) -> DispatchResultWithPostInfo {556 with_weight(557 <Pallet<T>>::set_allowance_for_all(self, &owner, &operator, approve),558 <CommonWeights<T>>::set_allowance_for_all(),559 )560 }561562 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {563 <Pallet<T>>::allowance_for_all(self, &owner, &operator)564 }565566 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {567 with_weight(568 <Pallet<T>>::repair_item(self, token),569 <CommonWeights<T>>::force_repair_item(),570 )571 }572}573574impl<T: Config> XcmExtensions<T> for NonfungibleHandle<T> {575 fn is_foreign(&self) -> bool {576 self.flags.foreign577 }578579 fn create_item_internal(580 &self,581 depositor: &<T>::CrossAccountId,582 to: <T>::CrossAccountId,583 data: up_data_structs::CreateItemData,584 nesting_budget: &dyn Budget,585 ) -> Result<TokenId, sp_runtime::DispatchError> {586 <Pallet<T>>::create_multiple_items(587 self,588 &depositor,589 vec![map_create_data::<T>(data, &to)?],590 nesting_budget,591 )?;592593 Ok(self.last_token_id())594 }595596 fn transfer_item_internal(597 &self,598 depositor: &<T>::CrossAccountId,599 from: &<T>::CrossAccountId,600 to: &<T>::CrossAccountId,601 token: TokenId,602 amount: u128,603 nesting_budget: &dyn Budget,604 ) -> sp_runtime::DispatchResult {605 ensure!(amount == 1, <Error<T>>::NonfungibleItemsHaveNoAmount);606607 <Pallet<T>>::transfer_internal(self, &depositor, &from, &to, token, nesting_budget)608 .map(|_| ())609 .map_err(|post_info| post_info.error)610 }611612 fn burn_item_internal(613 &self,614 from: T::CrossAccountId,615 token: TokenId,616 amount: u128,617 ) -> sp_runtime::DispatchResult {618 ensure!(amount == 1, <Error<T>>::NonfungibleItemsHaveNoAmount);619620 <Pallet<T>>::burn(self, &from, token)621 }622}primitives/data-structs/src/budget.rsdiffbeforeafterboth--- a/primitives/data-structs/src/budget.rs
+++ b/primitives/data-structs/src/budget.rs
@@ -36,3 +36,10 @@
true
}
}
+
+pub struct ZeroBudget;
+impl Budget for ZeroBudget {
+ fn consume_custom(&self, _calls: u32) -> bool {
+ false
+ }
+}
runtime/common/config/pallets/foreign_asset.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/foreign_asset.rs
+++ b/runtime/common/config/pallets/foreign_asset.rs
@@ -1,14 +1,43 @@
use frame_support::{parameter_types, PalletId};
+use pallet_evm::account::CrossAccountId;
+use sp_core::H160;
+use staging_xcm::prelude::*;
+use staging_xcm_builder::AccountKey20Aliases;
-use crate::{runtime_common::config::governance, Runtime, RuntimeEvent};
+use crate::{
+ runtime_common::config::{
+ ethereum::CrossAccountId as ConfigCrossAccountId,
+ governance,
+ xcm::{LocationToAccountId, SelfLocation},
+ },
+ RelayNetwork, Runtime, RuntimeEvent,
+};
parameter_types! {
pub ForeignAssetPalletId: PalletId = PalletId(*b"frgnasts");
}
+pub struct LocationToCrossAccountId;
+impl staging_xcm_executor::traits::ConvertLocation<ConfigCrossAccountId>
+ for LocationToCrossAccountId
+{
+ fn convert_location(location: &MultiLocation) -> Option<ConfigCrossAccountId> {
+ LocationToAccountId::convert_location(location)
+ .map(|sub| ConfigCrossAccountId::from_sub(sub))
+ .or_else(|| {
+ let eth_address =
+ AccountKey20Aliases::<RelayNetwork, H160>::convert_location(location)?;
+
+ Some(ConfigCrossAccountId::from_eth(eth_address))
+ })
+ }
+}
+
impl pallet_foreign_assets::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ForceRegisterOrigin = governance::RootOrTechnicalCommitteeMember;
type PalletId = ForeignAssetPalletId;
+ type SelfLocation = SelfLocation;
+ type LocationToAccountId = LocationToCrossAccountId;
type WeightInfo = pallet_foreign_assets::weights::SubstrateWeight<Self>;
}