difftreelog
refactor draft foreign assets as proxy to collections
in: master
18 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -167,7 +167,6 @@
.map(|k| (k, 1 << 100))
.collect(),
},
- tokens: TokensConfig { balances: vec![] },
sudo: SudoConfig {
key: Some($root_key),
},
pallets/balances-adapter/src/common.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/common.rs
+++ b/pallets/balances-adapter/src/common.rs
@@ -332,10 +332,6 @@
0
}
- fn refungible_extensions(&self) -> Option<&dyn pallet_common::RefungibleExtensions<T>> {
- None
- }
-
fn set_allowance_for_all(
&self,
_owner: <T>::CrossAccountId,
pallets/common/src/dispatch.rsdiffbeforeafterboth--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -72,6 +72,7 @@
/// Create a collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
///
/// * `sender` - The user who will become the owner of the collection.
+ /// * `payer` - The user who pays the collection creation fee.
/// * `data` - Description of the created collection.
fn create(
sender: T::CrossAccountId,
@@ -79,6 +80,15 @@
data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError>;
+ /// Create a foreign collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
+ ///
+ /// * `sender` - The user who will become the owner of the collection.
+ /// * `data` - Description of the created collection.
+ fn create_foreign(
+ sender: T::CrossAccountId,
+ data: CreateCollectionData<T::CrossAccountId>,
+ ) -> Result<CollectionId, DispatchError>;
+
/// Delete the collection.
///
/// * `sender` - The owner of the collection.
pallets/common/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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use alloc::boxed::Box;57use core::{58 marker::PhantomData,59 ops::{Deref, DerefMut},60 slice::from_ref,61 unreachable,62};6364use evm_coder::ToLog;65use frame_support::{66 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Pays, PostDispatchInfo},67 ensure, fail,68 traits::{69 fungible::{Balanced, Debt, Inspect},70 tokens::{Imbalance, Precision, Preservation},71 Get,72 },73 transactional,74};75pub use pallet::*;76use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};77use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};78use sp_core::H160;79use sp_runtime::{traits::Zero, ArithmeticError, DispatchError, DispatchResult};80use sp_std::vec::Vec;81use sp_weights::Weight;82use up_data_structs::{83 budget::Budget, AccessMode, Collection, CollectionId, CollectionLimits, CollectionMode,84 CollectionPermissions, CollectionProperties as CollectionPropertiesT, CollectionStats,85 CreateCollectionData, CreateItemData, CreateItemExData, PhantomType, PropertiesError,86 PropertiesPermissionMap, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,87 PropertyScope, PropertyValue, RpcCollection, RpcCollectionFlags, SponsoringRateLimit,88 SponsorshipState, TokenChild, TokenData, TokenId, TokenOwnerError, TokenProperties,89 TrySetProperty, COLLECTION_ADMINS_LIMIT, COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT,90 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP,91 MAX_TOKEN_PREFIX_LENGTH, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,92};93use up_pov_estimate_rpc::PovInfo;9495#[cfg(feature = "runtime-benchmarks")]96pub mod benchmarking;97pub mod dispatch;98pub mod erc;99pub mod eth;100pub mod helpers;101#[allow(missing_docs)]102pub mod weights;103104use weights::WeightInfo;105106/// Weight info.107pub type SelfWeightOf<T> = <T as Config>::WeightInfo;108109/// Collection handle contains information about collection data and id.110/// Also provides functionality to count consumed gas.111///112/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).113/// It allows to perform common operations and queries on any collection type,114/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].115#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]116pub struct CollectionHandle<T: Config> {117 /// Collection id118 pub id: CollectionId,119 collection: Collection<T::AccountId>,120 /// Substrate recorder for counting consumed gas121 pub recorder: SubstrateRecorder<T>,122}123124impl<T: Config> WithRecorder<T> for CollectionHandle<T> {125 fn recorder(&self) -> &SubstrateRecorder<T> {126 &self.recorder127 }128 fn into_recorder(self) -> SubstrateRecorder<T> {129 self.recorder130 }131}132133impl<T: Config> CollectionHandle<T> {134 /// Same as [CollectionHandle::new] but with an explicit gas limit.135 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {136 Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))137 }138139 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].140 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {141 <CollectionById<T>>::get(id).map(|collection| Self {142 id,143 collection,144 recorder,145 })146 }147148 /// Retrives collection data from storage and creates collection handle with default parameters.149 /// If collection not found return `None`150 pub fn new(id: CollectionId) -> Option<Self> {151 Self::new_with_gas_limit(id, u64::MAX)152 }153154 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.155 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {156 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)157 }158159 /// Consume gas for reading.160 pub fn consume_store_reads(161 &self,162 reads: u64,163 ) -> pallet_evm_coder_substrate::execution::Result<()> {164 self.recorder().consume_store_reads(reads)165 }166167 /// Consume gas for writing.168 pub fn consume_store_writes(169 &self,170 writes: u64,171 ) -> pallet_evm_coder_substrate::execution::Result<()> {172 self.recorder().consume_store_writes(writes)173 }174175 /// Consume gas for reading and writing.176 pub fn consume_store_reads_and_writes(177 &self,178 reads: u64,179 writes: u64,180 ) -> pallet_evm_coder_substrate::execution::Result<()> {181 self.recorder()182 .consume_store_reads_and_writes(reads, writes)183 }184185 /// Save collection to storage.186 pub fn save(&self) -> DispatchResult {187 <CollectionById<T>>::insert(self.id, &self.collection);188 Ok(())189 }190191 /// Set collection sponsor.192 ///193 /// Unique collections allows sponsoring for certain actions.194 /// This method allows you to set the sponsor of the collection.195 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].196 pub fn set_sponsor(197 &mut self,198 sender: &T::CrossAccountId,199 sponsor: T::AccountId,200 ) -> DispatchResult {201 self.check_is_internal()?;202 self.check_is_owner_or_admin(sender)?;203204 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());205206 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));207 <PalletEvm<T>>::deposit_log(208 erc::CollectionHelpersEvents::CollectionChanged {209 collection_id: eth::collection_id_to_address(self.id),210 }211 .to_log(T::ContractAddress::get()),212 );213214 self.save()215 }216217 /// Force set `sponsor`.218 ///219 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation220 /// from the `sponsor` is not required.221 ///222 /// # Arguments223 ///224 /// * `sponsor`: ID of the account of the sponsor-to-be.225 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {226 self.check_is_internal()?;227228 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());229230 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));231 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));232 <PalletEvm<T>>::deposit_log(233 erc::CollectionHelpersEvents::CollectionChanged {234 collection_id: eth::collection_id_to_address(self.id),235 }236 .to_log(T::ContractAddress::get()),237 );238239 self.save()240 }241242 /// Confirm sponsorship243 ///244 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.245 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].246 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {247 self.check_is_internal()?;248 ensure!(249 self.collection.sponsorship.pending_sponsor() == Some(sender),250 Error::<T>::ConfirmSponsorshipFail251 );252253 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());254255 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));256 <PalletEvm<T>>::deposit_log(257 erc::CollectionHelpersEvents::CollectionChanged {258 collection_id: eth::collection_id_to_address(self.id),259 }260 .to_log(T::ContractAddress::get()),261 );262263 self.save()264 }265266 /// Remove collection sponsor.267 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {268 self.check_is_internal()?;269 self.check_is_owner_or_admin(sender)?;270271 self.collection.sponsorship = SponsorshipState::Disabled;272273 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));274 <PalletEvm<T>>::deposit_log(275 erc::CollectionHelpersEvents::CollectionChanged {276 collection_id: eth::collection_id_to_address(self.id),277 }278 .to_log(T::ContractAddress::get()),279 );280 self.save()281 }282283 /// Force remove `sponsor`.284 ///285 /// Differs from `remove_sponsor` in that286 /// it doesn't require consent from the `owner` of the collection.287 pub fn force_remove_sponsor(&mut self) -> DispatchResult {288 self.check_is_internal()?;289290 self.collection.sponsorship = SponsorshipState::Disabled;291292 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));293 <PalletEvm<T>>::deposit_log(294 erc::CollectionHelpersEvents::CollectionChanged {295 collection_id: eth::collection_id_to_address(self.id),296 }297 .to_log(T::ContractAddress::get()),298 );299 self.save()300 }301302 /// Checks that the collection was created with, and must be operated upon through **Unique API**.303 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.304 pub fn check_is_internal(&self) -> DispatchResult {305 if self.flags.external {306 return Err(<Error<T>>::CollectionIsExternal)?;307 }308309 Ok(())310 }311312 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.313 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.314 pub fn check_is_external(&self) -> DispatchResult {315 if !self.flags.external {316 return Err(<Error<T>>::CollectionIsInternal)?;317 }318319 Ok(())320 }321}322323impl<T: Config> Deref for CollectionHandle<T> {324 type Target = Collection<T::AccountId>;325326 fn deref(&self) -> &Self::Target {327 &self.collection328 }329}330331impl<T: Config> DerefMut for CollectionHandle<T> {332 fn deref_mut(&mut self) -> &mut Self::Target {333 &mut self.collection334 }335}336337impl<T: Config> CollectionHandle<T> {338 /// Checks if the `user` is the owner of the collection.339 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {340 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);341 Ok(())342 }343344 /// Returns **true** if the `user` is the owner or administrator of the collection.345 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {346 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))347 }348349 /// Checks if the `user` is the owner or administrator of the collection.350 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {351 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);352 Ok(())353 }354355 /// Returns **true** if356 /// * the `user`is a collection owner or admin357 /// * the collection limits allow the owner/admins to transfer/burn any collection token358 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {359 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)360 }361362 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.363 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {364 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)365 }366367 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.368 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {369 ensure!(370 <Allowlist<T>>::get((self.id, user)),371 <Error<T>>::AddressNotInAllowlist372 );373 Ok(())374 }375376 /// Changes collection owner to another account377 /// #### Store read/writes378 /// 1 writes379 pub fn change_owner(380 &mut self,381 caller: T::CrossAccountId,382 new_owner: T::CrossAccountId,383 ) -> DispatchResult {384 self.check_is_internal()?;385 self.check_is_owner(&caller)?;386 self.collection.owner = new_owner.as_sub().clone();387388 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(389 self.id,390 new_owner.as_sub().clone(),391 ));392 <PalletEvm<T>>::deposit_log(393 erc::CollectionHelpersEvents::CollectionChanged {394 collection_id: eth::collection_id_to_address(self.id),395 }396 .to_log(T::ContractAddress::get()),397 );398399 self.save()400 }401}402403#[frame_support::pallet]404pub mod pallet {405406 use dispatch::CollectionDispatch;407 use frame_support::{408 pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat,409 };410 use scale_info::TypeInfo;411 use up_data_structs::{mapping::TokenAddressMapping, TokenId};412 use weights::WeightInfo;413414 use super::*;415416 #[pallet::config]417 pub trait Config:418 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo419 {420 /// Weight information for functions of this pallet.421 type WeightInfo: WeightInfo;422423 /// Events compatible with [`frame_system::Config::Event`].424 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;425426 /// Handler of accounts and payment.427 type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;428429 /// Set price to create a collection.430 #[pallet::constant]431 type CollectionCreationPrice: Get<432 <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,433 >;434435 /// Dispatcher of operations on collections.436 type CollectionDispatch: CollectionDispatch<Self>;437438 /// Account which holds the chain's treasury.439 type TreasuryAccountId: Get<Self::AccountId>;440441 /// Address under which the CollectionHelper contract would be available.442 #[pallet::constant]443 type ContractAddress: Get<H160>;444445 /// Mapper for token addresses to Ethereum addresses.446 type EvmTokenAddressMapping: TokenAddressMapping<H160>;447448 /// Mapper for token addresses to [`CrossAccountId`].449 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;450 }451452 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);453 /// Collection id for native fungible collction.454 pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);455456 #[pallet::pallet]457 #[pallet::storage_version(STORAGE_VERSION)]458 pub struct Pallet<T>(_);459460 #[pallet::extra_constants]461 impl<T: Config> Pallet<T> {462 /// Maximum admins per collection.463 pub fn collection_admins_limit() -> u32 {464 COLLECTION_ADMINS_LIMIT465 }466 }467468 #[pallet::genesis_config]469 pub struct GenesisConfig<T>(PhantomData<T>);470471 impl<T: Config> Default for GenesisConfig<T> {472 fn default() -> Self {473 Self(Default::default())474 }475 }476477 #[pallet::genesis_build]478 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {479 fn build(&self) {480 StorageVersion::new(1).put::<Pallet<T>>();481 }482 }483484 impl<T: Config> Pallet<T> {485 /// Helper function that handles deposit events486 pub fn deposit_event(event: Event<T>) {487 let event = <T as Config>::RuntimeEvent::from(event);488 let event = event.into();489 <frame_system::Pallet<T>>::deposit_event(event)490 }491 }492493 #[pallet::event]494 pub enum Event<T: Config> {495 /// New collection was created496 CollectionCreated(497 /// Globally unique identifier of newly created collection.498 CollectionId,499 /// [`CollectionMode`] converted into _u8_.500 u8,501 /// Collection owner.502 T::AccountId,503 ),504505 /// New collection was destroyed506 CollectionDestroyed(507 /// Globally unique identifier of collection.508 CollectionId,509 ),510511 /// New item was created.512 ItemCreated(513 /// Id of the collection where item was created.514 CollectionId,515 /// Id of an item. Unique within the collection.516 TokenId,517 /// Owner of newly created item518 T::CrossAccountId,519 /// Always 1 for NFT520 u128,521 ),522523 /// Collection item was burned.524 ItemDestroyed(525 /// Id of the collection where item was destroyed.526 CollectionId,527 /// Identifier of burned NFT.528 TokenId,529 /// Which user has destroyed its tokens.530 T::CrossAccountId,531 /// Amount of token pieces destroed. Always 1 for NFT.532 u128,533 ),534535 /// Item was transferred536 Transfer(537 /// Id of collection to which item is belong.538 CollectionId,539 /// Id of an item.540 TokenId,541 /// Original owner of item.542 T::CrossAccountId,543 /// New owner of item.544 T::CrossAccountId,545 /// Amount of token pieces transfered. Always 1 for NFT.546 u128,547 ),548549 /// Amount pieces of token owned by `sender` was approved for `spender`.550 Approved(551 /// Id of collection to which item is belong.552 CollectionId,553 /// Id of an item.554 TokenId,555 /// Original owner of item.556 T::CrossAccountId,557 /// Id for which the approval was granted.558 T::CrossAccountId,559 /// Amount of token pieces transfered. Always 1 for NFT.560 u128,561 ),562563 /// A `sender` approves operations on all owned tokens for `spender`.564 ApprovedForAll(565 /// Id of collection to which item is belong.566 CollectionId,567 /// Owner of a wallet.568 T::CrossAccountId,569 /// Id for which operator status was granted or rewoked.570 T::CrossAccountId,571 /// Is operator status granted or revoked?572 bool,573 ),574575 /// The colletion property has been added or edited.576 CollectionPropertySet(577 /// Id of collection to which property has been set.578 CollectionId,579 /// The property that was set.580 PropertyKey,581 ),582583 /// The property has been deleted.584 CollectionPropertyDeleted(585 /// Id of collection to which property has been deleted.586 CollectionId,587 /// The property that was deleted.588 PropertyKey,589 ),590591 /// The token property has been added or edited.592 TokenPropertySet(593 /// Identifier of the collection whose token has the property set.594 CollectionId,595 /// The token for which the property was set.596 TokenId,597 /// The property that was set.598 PropertyKey,599 ),600601 /// The token property has been deleted.602 TokenPropertyDeleted(603 /// Identifier of the collection whose token has the property deleted.604 CollectionId,605 /// The token for which the property was deleted.606 TokenId,607 /// The property that was deleted.608 PropertyKey,609 ),610611 /// The token property permission of a collection has been set.612 PropertyPermissionSet(613 /// ID of collection to which property permission has been set.614 CollectionId,615 /// The property permission that was set.616 PropertyKey,617 ),618619 /// Address was added to the allow list.620 AllowListAddressAdded(621 /// ID of the affected collection.622 CollectionId,623 /// Address of the added account.624 T::CrossAccountId,625 ),626627 /// Address was removed from the allow list.628 AllowListAddressRemoved(629 /// ID of the affected collection.630 CollectionId,631 /// Address of the removed account.632 T::CrossAccountId,633 ),634635 /// Collection admin was added.636 CollectionAdminAdded(637 /// ID of the affected collection.638 CollectionId,639 /// Admin address.640 T::CrossAccountId,641 ),642643 /// Collection admin was removed.644 CollectionAdminRemoved(645 /// ID of the affected collection.646 CollectionId,647 /// Removed admin address.648 T::CrossAccountId,649 ),650651 /// Collection limits were set.652 CollectionLimitSet(653 /// ID of the affected collection.654 CollectionId,655 ),656657 /// Collection owned was changed.658 CollectionOwnerChanged(659 /// ID of the affected collection.660 CollectionId,661 /// New owner address.662 T::AccountId,663 ),664665 /// Collection permissions were set.666 CollectionPermissionSet(667 /// ID of the affected collection.668 CollectionId,669 ),670671 /// Collection sponsor was set.672 CollectionSponsorSet(673 /// ID of the affected collection.674 CollectionId,675 /// New sponsor address.676 T::AccountId,677 ),678679 /// New sponsor was confirm.680 SponsorshipConfirmed(681 /// ID of the affected collection.682 CollectionId,683 /// New sponsor address.684 T::AccountId,685 ),686687 /// Collection sponsor was removed.688 CollectionSponsorRemoved(689 /// ID of the affected collection.690 CollectionId,691 ),692 }693694 #[pallet::error]695 pub enum Error<T> {696 /// This collection does not exist.697 CollectionNotFound,698 /// Sender parameter and item owner must be equal.699 MustBeTokenOwner,700 /// No permission to perform action701 NoPermission,702 /// Destroying only empty collections is allowed703 CantDestroyNotEmptyCollection,704 /// Collection is not in mint mode.705 PublicMintingNotAllowed,706 /// Address is not in allow list.707 AddressNotInAllowlist,708709 /// Collection name can not be longer than 63 char.710 CollectionNameLimitExceeded,711 /// Collection description can not be longer than 255 char.712 CollectionDescriptionLimitExceeded,713 /// Token prefix can not be longer than 15 char.714 CollectionTokenPrefixLimitExceeded,715 /// Total collections bound exceeded.716 TotalCollectionsLimitExceeded,717 /// Exceeded max admin count718 CollectionAdminCountExceeded,719 /// Collection limit bounds per collection exceeded720 CollectionLimitBoundsExceeded,721 /// Tried to enable permissions which are only permitted to be disabled722 OwnerPermissionsCantBeReverted,723 /// Collection settings not allowing items transferring724 TransferNotAllowed,725 /// Account token limit exceeded per collection726 AccountTokenLimitExceeded,727 /// Collection token limit exceeded728 CollectionTokenLimitExceeded,729 /// Metadata flag frozen730 MetadataFlagFrozen,731732 /// Item does not exist733 TokenNotFound,734 /// Item is balance not enough735 TokenValueTooLow,736 /// Requested value is more than the approved737 ApprovedValueTooLow,738 /// Tried to approve more than owned739 CantApproveMoreThanOwned,740 /// Only spending from eth mirror could be approved741 AddressIsNotEthMirror,742743 /// Can't transfer tokens to ethereum zero address744 AddressIsZero,745746 /// The operation is not supported747 UnsupportedOperation,748749 /// Insufficient funds to perform an action750 NotSufficientFounds,751752 /// User does not satisfy the nesting rule753 UserIsNotAllowedToNest,754 /// Only tokens from specific collections may nest tokens under this one755 SourceCollectionIsNotAllowedToNest,756757 /// Tried to store more data than allowed in collection field758 CollectionFieldSizeExceeded,759760 /// Tried to store more property data than allowed761 NoSpaceForProperty,762763 /// Tried to store more property keys than allowed764 PropertyLimitReached,765766 /// Property key is too long767 PropertyKeyIsTooLong,768769 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed770 InvalidCharacterInPropertyKey,771772 /// Empty property keys are forbidden773 EmptyPropertyKey,774775 /// Tried to access an external collection with an internal API776 CollectionIsExternal,777778 /// Tried to access an internal collection with an external API779 CollectionIsInternal,780781 /// This address is not set as sponsor, use setCollectionSponsor first.782 ConfirmSponsorshipFail,783784 /// The user is not an administrator.785 UserIsNotCollectionAdmin,786787 /// Fungible tokens hold no ID, and the default value of TokenId for a fungible collection is 0.788 FungibleItemsHaveNoId,789 }790791 /// Storage of the count of created collections. Essentially contains the last collection ID.792 #[pallet::storage]793 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;794795 /// Storage of the count of deleted collections.796 #[pallet::storage]797 pub type DestroyedCollectionCount<T> =798 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;799800 /// Storage of collection info.801 #[pallet::storage]802 pub type CollectionById<T> = StorageMap<803 Hasher = Blake2_128Concat,804 Key = CollectionId,805 Value = Collection<<T as frame_system::Config>::AccountId>,806 QueryKind = OptionQuery,807 >;808809 /// Storage of collection properties.810 #[pallet::storage]811 #[pallet::getter(fn collection_properties)]812 pub type CollectionProperties<T> = StorageMap<813 Hasher = Blake2_128Concat,814 Key = CollectionId,815 Value = CollectionPropertiesT,816 QueryKind = ValueQuery,817 >;818819 /// Storage of token property permissions of a collection.820 #[pallet::storage]821 #[pallet::getter(fn property_permissions)]822 pub type CollectionPropertyPermissions<T> = StorageMap<823 Hasher = Blake2_128Concat,824 Key = CollectionId,825 Value = PropertiesPermissionMap,826 QueryKind = ValueQuery,827 >;828829 /// Storage of the amount of collection admins.830 #[pallet::storage]831 pub type AdminAmount<T> = StorageMap<832 Hasher = Blake2_128Concat,833 Key = CollectionId,834 Value = u32,835 QueryKind = ValueQuery,836 >;837838 /// List of collection admins.839 #[pallet::storage]840 pub type IsAdmin<T: Config> = StorageNMap<841 Key = (842 Key<Blake2_128Concat, CollectionId>,843 Key<Blake2_128Concat, T::CrossAccountId>,844 ),845 Value = bool,846 QueryKind = ValueQuery,847 >;848849 /// Allowlisted collection users.850 #[pallet::storage]851 pub type Allowlist<T: Config> = StorageNMap<852 Key = (853 Key<Blake2_128Concat, CollectionId>,854 Key<Blake2_128Concat, T::CrossAccountId>,855 ),856 Value = bool,857 QueryKind = ValueQuery,858 >;859860 /// Not used by code, exists only to provide some types to metadata.861 #[pallet::storage]862 pub type DummyStorageValue<T: Config> = StorageValue<863 Value = (864 CollectionStats,865 CollectionId,866 TokenId,867 TokenChild,868 PhantomType<(869 TokenData<T::CrossAccountId>,870 RpcCollection<T::AccountId>,871 // PoV Estimate Info872 PovInfo,873 )>,874 ),875 QueryKind = OptionQuery,876 >;877}878879enum LazyValueState<'a, T> {880 Pending(Box<dyn FnOnce() -> T + 'a>),881 InProgress,882 Computed(T),883}884885/// Value representation with delayed initialization time.886pub struct LazyValue<'a, T> {887 state: LazyValueState<'a, T>,888}889890impl<'a, T> LazyValue<'a, T> {891 /// Create a new LazyValue.892 pub fn new(f: impl FnOnce() -> T + 'a) -> Self {893 Self {894 state: LazyValueState::Pending(Box::new(f)),895 }896 }897898 /// Get the value. If it is called the first time, the value will be initialized.899 pub fn value(&mut self) -> &T {900 self.force_value();901 self.value_mut()902 }903904 /// Get the value. If it is called the first time, the value will be initialized.905 pub fn value_mut(&mut self) -> &mut T {906 self.force_value();907908 if let LazyValueState::Computed(value) = &mut self.state {909 value910 } else {911 unreachable!()912 }913 }914915 fn into_inner(mut self) -> T {916 self.force_value();917 if let LazyValueState::Computed(value) = self.state {918 value919 } else {920 unreachable!()921 }922 }923924 /// Is value initialized?925 pub fn has_value(&self) -> bool {926 matches!(self.state, LazyValueState::Computed(_))927 }928929 fn force_value(&mut self) {930 use LazyValueState::*;931932 if self.has_value() {933 return;934 }935936 match sp_std::mem::replace(&mut self.state, InProgress) {937 Pending(f) => self.state = Computed(f()),938 _ => panic!("recursion isn't supported"),939 }940 }941}942943fn check_token_permissions<T: Config>(944 collection_admin_permitted: bool,945 token_owner_permitted: bool,946 is_collection_admin: &mut LazyValue<bool>,947 is_token_owner: &mut LazyValue<Result<bool, DispatchError>>,948 is_token_exist: &mut LazyValue<bool>,949) -> DispatchResult {950 if !(collection_admin_permitted && *is_collection_admin.value()951 || token_owner_permitted && (*is_token_owner.value())?)952 {953 fail!(<Error<T>>::NoPermission);954 }955956 let token_exist_due_to_owner_check_success =957 is_token_owner.has_value() && (*is_token_owner.value())?;958959 // If the token owner check has occurred and succeeded,960 // we know the token exists (otherwise, the owner check must fail).961 if !token_exist_due_to_owner_check_success {962 // If the token owner check didn't occur,963 // we must check the token's existence ourselves.964 if !is_token_exist.value() {965 fail!(<Error<T>>::TokenNotFound);966 }967 }968969 Ok(())970}971972impl<T: Config> Pallet<T> {973 /// Enshure that receiver address is correct.974 ///975 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.976 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {977 ensure!(978 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,979 <Error<T>>::AddressIsZero980 );981 Ok(())982 }983984 /// Get a vector of collection admins.985 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {986 <IsAdmin<T>>::iter_prefix((collection,))987 .map(|(a, _)| a)988 .collect()989 }990991 /// Get a vector of users allowed to mint tokens.992 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {993 <Allowlist<T>>::iter_prefix((collection,))994 .map(|(a, _)| a)995 .collect()996 }997998 /// Is `user` allowed to mint token in `collection`.999 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {1000 <Allowlist<T>>::get((collection, user))1001 }10021003 /// Get statistics of collections.1004 pub fn collection_stats() -> CollectionStats {1005 let created = <CreatedCollectionCount<T>>::get();1006 let destroyed = <DestroyedCollectionCount<T>>::get();1007 CollectionStats {1008 created: created.0,1009 destroyed: destroyed.0,1010 alive: created.0 - destroyed.0,1011 }1012 }10131014 /// Get the effective limits for the collection.1015 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {1016 let collection = <CollectionById<T>>::get(collection)?;1017 let limits = collection.limits;1018 let effective_limits = CollectionLimits {1019 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1020 sponsored_data_size: Some(limits.sponsored_data_size()),1021 sponsored_data_rate_limit: Some(1022 limits1023 .sponsored_data_rate_limit1024 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),1025 ),1026 token_limit: Some(limits.token_limit()),1027 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1028 match collection.mode {1029 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1030 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1031 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1032 },1033 )),1034 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1035 owner_can_transfer: Some(limits.owner_can_transfer()),1036 owner_can_destroy: Some(limits.owner_can_destroy()),1037 transfers_enabled: Some(limits.transfers_enabled()),1038 };10391040 Some(effective_limits)1041 }10421043 /// Returns information about the `collection` adapted for rpc.1044 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1045 let Collection {1046 name,1047 description,1048 owner,1049 mode,1050 token_prefix,1051 sponsorship,1052 limits,1053 permissions,1054 flags,1055 } = <CollectionById<T>>::get(collection)?;10561057 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1058 .into_iter()1059 .map(|(key, permission)| PropertyKeyPermission { key, permission })1060 .collect();10611062 let properties = <CollectionProperties<T>>::get(collection)1063 .into_iter()1064 .map(|(key, value)| Property { key, value })1065 .collect();10661067 let permissions = CollectionPermissions {1068 access: Some(permissions.access()),1069 mint_mode: Some(permissions.mint_mode()),1070 nesting: Some(permissions.nesting().clone()),1071 };10721073 Some(RpcCollection {1074 name: name.into_inner(),1075 description: description.into_inner(),1076 owner,1077 mode,1078 token_prefix: token_prefix.into_inner(),1079 sponsorship,1080 limits,1081 permissions,1082 token_property_permissions,1083 properties,1084 read_only: flags.external,10851086 flags: RpcCollectionFlags {1087 foreign: flags.foreign,1088 erc721metadata: flags.erc721metadata,1089 },1090 })1091 }1092}10931094macro_rules! limit_default {1095 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1096 $(1097 if let Some($new) = $new.$field {1098 let $old = $old.$field($($arg)?);1099 let _ = $new;1100 let _ = $old;1101 $check1102 } else {1103 $new.$field = $old.$field1104 }1105 )*1106 }};1107}1108macro_rules! limit_default_clone {1109 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1110 $(1111 if let Some($new) = $new.$field.clone() {1112 let $old = $old.$field($($arg)?);1113 let _ = $new;1114 let _ = $old;1115 $check1116 } else {1117 $new.$field = $old.$field.clone()1118 }1119 )*1120 }};1121}11221123impl<T: Config> Pallet<T> {1124 /// Create new collection.1125 ///1126 /// * `owner` - The owner of the collection.1127 /// * `data` - Description of the created collection.1128 /// * `flags` - Extra flags to store.1129 pub fn init_collection(1130 owner: T::CrossAccountId,1131 payer: T::CrossAccountId,1132 data: CreateCollectionData<T::CrossAccountId>,1133 ) -> Result<CollectionId, DispatchError> {1134 ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);11351136 // Take a (non-refundable) deposit of collection creation1137 {1138 let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1139 imbalance.subsume(<T as Config>::Currency::deposit(1140 &T::TreasuryAccountId::get(),1141 T::CollectionCreationPrice::get(),1142 Precision::Exact,1143 )?);1144 let credit =1145 <T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1146 .map_err(|_| Error::<T>::NotSufficientFounds)?;11471148 debug_assert!(credit.peek().is_zero())1149 }11501151 Self::init_collection_internal(owner, data)1152 }11531154 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.1155 pub fn init_foreign_collection(1156 owner: T::CrossAccountId,1157 mut data: CreateCollectionData<T::CrossAccountId>,1158 ) -> Result<CollectionId, DispatchError> {1159 data.flags.foreign = true;1160 let id = Self::init_collection_internal(owner, data)?;1161 Ok(id)1162 }11631164 fn init_collection_internal(1165 owner: T::CrossAccountId,1166 data: CreateCollectionData<T::CrossAccountId>,1167 ) -> Result<CollectionId, DispatchError> {1168 {1169 ensure!(1170 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1171 Error::<T>::CollectionTokenPrefixLimitExceeded1172 );1173 }11741175 let created_count = <CreatedCollectionCount<T>>::get()1176 .01177 .checked_add(1)1178 .ok_or(ArithmeticError::Overflow)?;1179 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1180 let id = CollectionId(created_count);11811182 // bound Total number of collections1183 ensure!(1184 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1185 <Error<T>>::TotalCollectionsLimitExceeded1186 );11871188 // =========11891190 let collection = Collection {1191 owner: owner.as_sub().clone(),1192 name: data.name,1193 mode: data.mode.clone(),1194 description: data.description,1195 token_prefix: data.token_prefix,1196 sponsorship: data1197 .pending_sponsor1198 .map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1199 .unwrap_or_default(),1200 limits: data1201 .limits1202 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1203 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1204 permissions: data1205 .permissions1206 .map(|permissions| {1207 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1208 })1209 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1210 flags: data.flags,1211 };12121213 let mut collection_properties = CollectionPropertiesT::new();1214 collection_properties1215 .try_set_from_iter(data.properties.into_iter())1216 .map_err(<Error<T>>::from)?;12171218 CollectionProperties::<T>::insert(id, collection_properties);12191220 let mut token_props_permissions = PropertiesPermissionMap::new();1221 token_props_permissions1222 .try_set_from_iter(data.token_property_permissions.into_iter())1223 .map_err(<Error<T>>::from)?;12241225 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);12261227 let mut admin_amount = 0u32;1228 for admin in data.admin_list.iter() {1229 if !<IsAdmin<T>>::get((id, admin)) {1230 <IsAdmin<T>>::insert((id, admin), true);1231 admin_amount = admin_amount1232 .checked_add(1)1233 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1234 }1235 }1236 ensure!(1237 admin_amount <= Self::collection_admins_limit(),1238 <Error<T>>::CollectionAdminCountExceeded,1239 );1240 <AdminAmount<T>>::insert(id, admin_amount);12411242 <CreatedCollectionCount<T>>::put(created_count);1243 <Pallet<T>>::deposit_event(Event::CollectionCreated(1244 id,1245 data.mode.id(),1246 owner.as_sub().clone(),1247 ));1248 <PalletEvm<T>>::deposit_log(1249 erc::CollectionHelpersEvents::CollectionCreated {1250 owner: *owner.as_eth(),1251 collection_id: eth::collection_id_to_address(id),1252 }1253 .to_log(T::ContractAddress::get()),1254 );1255 <CollectionById<T>>::insert(id, collection);1256 Ok(id)1257 }12581259 /// Destroy collection.1260 ///1261 /// * `collection` - Collection handler.1262 /// * `sender` - The owner or administrator of the collection.1263 pub fn destroy_collection(1264 collection: CollectionHandle<T>,1265 sender: &T::CrossAccountId,1266 ) -> DispatchResult {1267 ensure!(1268 collection.limits.owner_can_destroy(),1269 <Error<T>>::NoPermission,1270 );1271 collection.check_is_owner(sender)?;12721273 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1274 .01275 .checked_add(1)1276 .ok_or(ArithmeticError::Overflow)?;12771278 // =========12791280 <DestroyedCollectionCount<T>>::put(destroyed_collections);1281 <CollectionById<T>>::remove(collection.id);1282 <AdminAmount<T>>::remove(collection.id);1283 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1284 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1285 <CollectionProperties<T>>::remove(collection.id);12861287 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12881289 <PalletEvm<T>>::deposit_log(1290 erc::CollectionHelpersEvents::CollectionDestroyed {1291 collection_id: eth::collection_id_to_address(collection.id),1292 }1293 .to_log(T::ContractAddress::get()),1294 );1295 Ok(())1296 }12971298 /// This function sets or removes a collection properties according to1299 /// `properties_updates` contents:1300 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1301 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1302 ///1303 /// This function fires an event for each property change.1304 /// In case of an error, all the changes (including the events) will be reverted1305 /// since the function is transactional.1306 #[transactional]1307 fn modify_collection_properties(1308 collection: &CollectionHandle<T>,1309 sender: &T::CrossAccountId,1310 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1311 ) -> DispatchResult {1312 collection.check_is_owner_or_admin(sender)?;13131314 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);13151316 for (key, value) in properties_updates {1317 match value {1318 Some(value) => {1319 stored_properties1320 .try_set(key.clone(), value)1321 .map_err(<Error<T>>::from)?;13221323 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1324 <PalletEvm<T>>::deposit_log(1325 erc::CollectionHelpersEvents::CollectionChanged {1326 collection_id: eth::collection_id_to_address(collection.id),1327 }1328 .to_log(T::ContractAddress::get()),1329 );1330 }1331 None => {1332 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13331334 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1335 <PalletEvm<T>>::deposit_log(1336 erc::CollectionHelpersEvents::CollectionChanged {1337 collection_id: eth::collection_id_to_address(collection.id),1338 }1339 .to_log(T::ContractAddress::get()),1340 );1341 }1342 }1343 }13441345 <CollectionProperties<T>>::set(collection.id, stored_properties);13461347 Ok(())1348 }13491350 /// Sets or unsets the approval of a given operator.1351 ///1352 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1353 /// - `owner`: Token owner1354 /// - `operator`: Operator1355 /// - `approve`: Should operator status be granted or revoked?1356 pub fn set_allowance_for_all(1357 collection: &CollectionHandle<T>,1358 owner: &T::CrossAccountId,1359 operator: &T::CrossAccountId,1360 approve: bool,1361 set_allowance: impl FnOnce(),1362 log: evm_coder::ethereum::Log,1363 ) -> DispatchResult {1364 if collection.permissions.access() == AccessMode::AllowList {1365 collection.check_allowlist(owner)?;1366 collection.check_allowlist(operator)?;1367 }13681369 Self::ensure_correct_receiver(operator)?;13701371 set_allowance();13721373 <PalletEvm<T>>::deposit_log(log);1374 Self::deposit_event(Event::ApprovedForAll(1375 collection.id,1376 owner.clone(),1377 operator.clone(),1378 approve,1379 ));1380 Ok(())1381 }13821383 /// Set collection property.1384 ///1385 /// * `collection` - Collection handler.1386 /// * `sender` - The owner or administrator of the collection.1387 /// * `property` - The property to set.1388 pub fn set_collection_property(1389 collection: &CollectionHandle<T>,1390 sender: &T::CrossAccountId,1391 property: Property,1392 ) -> DispatchResult {1393 Self::set_collection_properties(collection, sender, [property].into_iter())1394 }13951396 /// Set a scoped collection property, where the scope is a special prefix1397 /// prohibiting a user access to change the property directly.1398 ///1399 /// * `collection_id` - ID of the collection for which the property is being set.1400 /// * `scope` - Property scope.1401 /// * `property` - The property to set.1402 pub fn set_scoped_collection_property(1403 collection_id: CollectionId,1404 scope: PropertyScope,1405 property: Property,1406 ) -> DispatchResult {1407 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1408 properties.try_scoped_set(scope, property.key, property.value)1409 })1410 .map_err(<Error<T>>::from)?;14111412 Ok(())1413 }14141415 /// Set scoped collection properties, where the scope is a special prefix1416 /// prohibiting a user access to change the properties directly.1417 ///1418 /// * `collection_id` - ID of the collection for which the properties is being set.1419 /// * `scope` - Property scope.1420 /// * `properties` - The properties to set.1421 pub fn set_scoped_collection_properties(1422 collection_id: CollectionId,1423 scope: PropertyScope,1424 properties: impl Iterator<Item = Property>,1425 ) -> DispatchResult {1426 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1427 stored_properties.try_scoped_set_from_iter(scope, properties)1428 })1429 .map_err(<Error<T>>::from)?;14301431 Ok(())1432 }14331434 /// Set collection properties.1435 ///1436 /// * `collection` - Collection handler.1437 /// * `sender` - The owner or administrator of the collection.1438 /// * `properties` - The properties to set.1439 pub fn set_collection_properties(1440 collection: &CollectionHandle<T>,1441 sender: &T::CrossAccountId,1442 properties: impl Iterator<Item = Property>,1443 ) -> DispatchResult {1444 Self::modify_collection_properties(1445 collection,1446 sender,1447 properties.map(|property| (property.key, Some(property.value))),1448 )1449 }14501451 /// Delete collection property.1452 ///1453 /// * `collection` - Collection handler.1454 /// * `sender` - The owner or administrator of the collection.1455 /// * `property` - The property to delete.1456 pub fn delete_collection_property(1457 collection: &CollectionHandle<T>,1458 sender: &T::CrossAccountId,1459 property_key: PropertyKey,1460 ) -> DispatchResult {1461 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1462 }14631464 /// Delete collection properties.1465 ///1466 /// * `collection` - Collection handler.1467 /// * `sender` - The owner or administrator of the collection.1468 /// * `properties` - The properties to delete.1469 pub fn delete_collection_properties(1470 collection: &CollectionHandle<T>,1471 sender: &T::CrossAccountId,1472 property_keys: impl Iterator<Item = PropertyKey>,1473 ) -> DispatchResult {1474 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1475 }14761477 /// Set collection propetry permission without any checks.1478 ///1479 /// Used for migrations.1480 ///1481 /// * `collection` - Collection handler.1482 /// * `property_permissions` - Property permissions.1483 pub fn set_property_permission_unchecked(1484 collection: CollectionId,1485 property_permission: PropertyKeyPermission,1486 ) -> DispatchResult {1487 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1488 permissions.try_set(property_permission.key, property_permission.permission)1489 })1490 .map_err(<Error<T>>::from)?;1491 Ok(())1492 }14931494 /// Set collection property permission.1495 ///1496 /// * `collection` - Collection handler.1497 /// * `sender` - The owner or administrator of the collection.1498 /// * `property_permission` - Property permission.1499 pub fn set_property_permission(1500 collection: &CollectionHandle<T>,1501 sender: &T::CrossAccountId,1502 property_permission: PropertyKeyPermission,1503 ) -> DispatchResult {1504 Self::set_scoped_property_permission(1505 collection,1506 sender,1507 PropertyScope::None,1508 property_permission,1509 )1510 }15111512 /// Set collection property permission with scope.1513 ///1514 /// * `collection` - Collection handler.1515 /// * `sender` - The owner or administrator of the collection.1516 /// * `scope` - Property scope.1517 /// * `property_permission` - Property permission.1518 pub fn set_scoped_property_permission(1519 collection: &CollectionHandle<T>,1520 sender: &T::CrossAccountId,1521 scope: PropertyScope,1522 property_permission: PropertyKeyPermission,1523 ) -> DispatchResult {1524 collection.check_is_owner_or_admin(sender)?;15251526 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1527 let current_permission = all_permissions.get(&property_permission.key);1528 if matches![1529 current_permission,1530 Some(PropertyPermission { mutable: false, .. })1531 ] {1532 return Err(<Error<T>>::NoPermission.into());1533 }15341535 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1536 let property_permission = property_permission.clone();1537 permissions.try_scoped_set(1538 scope,1539 property_permission.key,1540 property_permission.permission,1541 )1542 })1543 .map_err(<Error<T>>::from)?;15441545 Self::deposit_event(Event::PropertyPermissionSet(1546 collection.id,1547 property_permission.key,1548 ));1549 <PalletEvm<T>>::deposit_log(1550 erc::CollectionHelpersEvents::CollectionChanged {1551 collection_id: eth::collection_id_to_address(collection.id),1552 }1553 .to_log(T::ContractAddress::get()),1554 );15551556 Ok(())1557 }15581559 /// Set token property permission.1560 ///1561 /// * `collection` - Collection handler.1562 /// * `sender` - The owner or administrator of the collection.1563 /// * `property_permissions` - Property permissions.1564 #[transactional]1565 pub fn set_token_property_permissions(1566 collection: &CollectionHandle<T>,1567 sender: &T::CrossAccountId,1568 property_permissions: Vec<PropertyKeyPermission>,1569 ) -> DispatchResult {1570 Self::set_scoped_token_property_permissions(1571 collection,1572 sender,1573 PropertyScope::None,1574 property_permissions,1575 )1576 }15771578 /// Set token property permission with scope.1579 ///1580 /// * `collection` - Collection handler.1581 /// * `sender` - The owner or administrator of the collection.1582 /// * `scope` - Property scope.1583 /// * `property_permissions` - Property permissions.1584 #[transactional]1585 pub fn set_scoped_token_property_permissions(1586 collection: &CollectionHandle<T>,1587 sender: &T::CrossAccountId,1588 scope: PropertyScope,1589 property_permissions: Vec<PropertyKeyPermission>,1590 ) -> DispatchResult {1591 for prop_pemission in property_permissions {1592 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1593 }15941595 Ok(())1596 }15971598 /// Get collection property.1599 pub fn get_collection_property(1600 collection_id: CollectionId,1601 key: &PropertyKey,1602 ) -> Option<PropertyValue> {1603 Self::collection_properties(collection_id).get(key).cloned()1604 }16051606 /// Convert byte vector to property key vector.1607 pub fn bytes_keys_to_property_keys(1608 keys: Vec<Vec<u8>>,1609 ) -> Result<Vec<PropertyKey>, DispatchError> {1610 keys.into_iter()1611 .map(|key| -> Result<PropertyKey, DispatchError> {1612 key.try_into()1613 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1614 })1615 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1616 }16171618 /// Get properties according to given keys.1619 pub fn filter_collection_properties(1620 collection_id: CollectionId,1621 keys: Option<Vec<PropertyKey>>,1622 ) -> Result<Vec<Property>, DispatchError> {1623 let properties = Self::collection_properties(collection_id);16241625 let properties = keys1626 .map(|keys| {1627 keys.into_iter()1628 .filter_map(|key| {1629 properties.get(&key).map(|value| Property {1630 key,1631 value: value.clone(),1632 })1633 })1634 .collect()1635 })1636 .unwrap_or_else(|| {1637 properties1638 .into_iter()1639 .map(|(key, value)| Property { key, value })1640 .collect()1641 });16421643 Ok(properties)1644 }16451646 /// Get property permissions according to given keys.1647 pub fn filter_property_permissions(1648 collection_id: CollectionId,1649 keys: Option<Vec<PropertyKey>>,1650 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1651 let permissions = Self::property_permissions(collection_id);16521653 let key_permissions = keys1654 .map(|keys| {1655 keys.into_iter()1656 .filter_map(|key| {1657 permissions1658 .get(&key)1659 .map(|permission| PropertyKeyPermission {1660 key,1661 permission: permission.clone(),1662 })1663 })1664 .collect()1665 })1666 .unwrap_or_else(|| {1667 permissions1668 .into_iter()1669 .map(|(key, permission)| PropertyKeyPermission { key, permission })1670 .collect()1671 });16721673 Ok(key_permissions)1674 }16751676 /// Toggle `user` participation in the `collection`'s allow list.1677 /// #### Store read/writes1678 /// 1 writes1679 pub fn toggle_allowlist(1680 collection: &CollectionHandle<T>,1681 sender: &T::CrossAccountId,1682 user: &T::CrossAccountId,1683 allowed: bool,1684 ) -> DispatchResult {1685 collection.check_is_owner_or_admin(sender)?;16861687 // =========16881689 if allowed {1690 <Allowlist<T>>::insert((collection.id, user), true);1691 Self::deposit_event(Event::<T>::AllowListAddressAdded(1692 collection.id,1693 user.clone(),1694 ));1695 } else {1696 <Allowlist<T>>::remove((collection.id, user));1697 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1698 collection.id,1699 user.clone(),1700 ));1701 }17021703 <PalletEvm<T>>::deposit_log(1704 erc::CollectionHelpersEvents::CollectionChanged {1705 collection_id: eth::collection_id_to_address(collection.id),1706 }1707 .to_log(T::ContractAddress::get()),1708 );17091710 Ok(())1711 }17121713 /// Toggle `user` participation in the `collection`'s admin list.1714 /// #### Store read/writes1715 /// 2 reads, 2 writes1716 pub fn toggle_admin(1717 collection: &CollectionHandle<T>,1718 sender: &T::CrossAccountId,1719 user: &T::CrossAccountId,1720 admin: bool,1721 ) -> DispatchResult {1722 collection.check_is_internal()?;1723 collection.check_is_owner(sender)?;17241725 let is_admin = <IsAdmin<T>>::get((collection.id, user));1726 if is_admin == admin {1727 if admin {1728 return Ok(());1729 } else {1730 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1731 }1732 }1733 let amount = <AdminAmount<T>>::get(collection.id);17341735 // =========17361737 if admin {1738 let amount = amount1739 .checked_add(1)1740 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1741 ensure!(1742 amount <= Self::collection_admins_limit(),1743 <Error<T>>::CollectionAdminCountExceeded,1744 );17451746 <AdminAmount<T>>::insert(collection.id, amount);1747 <IsAdmin<T>>::insert((collection.id, user), true);17481749 Self::deposit_event(Event::<T>::CollectionAdminAdded(1750 collection.id,1751 user.clone(),1752 ));1753 } else {1754 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1755 <IsAdmin<T>>::remove((collection.id, user));17561757 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1758 collection.id,1759 user.clone(),1760 ));1761 }17621763 <PalletEvm<T>>::deposit_log(1764 erc::CollectionHelpersEvents::CollectionChanged {1765 collection_id: eth::collection_id_to_address(collection.id),1766 }1767 .to_log(T::ContractAddress::get()),1768 );17691770 Ok(())1771 }17721773 /// Update collection limits.1774 pub fn update_limits(1775 user: &T::CrossAccountId,1776 collection: &mut CollectionHandle<T>,1777 new_limit: CollectionLimits,1778 ) -> DispatchResult {1779 collection.check_is_internal()?;1780 collection.check_is_owner_or_admin(user)?;17811782 collection.limits =1783 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17841785 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1786 <PalletEvm<T>>::deposit_log(1787 erc::CollectionHelpersEvents::CollectionChanged {1788 collection_id: eth::collection_id_to_address(collection.id),1789 }1790 .to_log(T::ContractAddress::get()),1791 );17921793 collection.save()1794 }17951796 /// Merge set fields from `new_limit` to `old_limit`.1797 fn clamp_limits(1798 mode: CollectionMode,1799 old_limit: &CollectionLimits,1800 mut new_limit: CollectionLimits,1801 ) -> Result<CollectionLimits, DispatchError> {1802 let limits = old_limit;1803 limit_default!(old_limit, new_limit,1804 account_token_ownership_limit => ensure!(1805 new_limit <= MAX_TOKEN_OWNERSHIP,1806 <Error<T>>::CollectionLimitBoundsExceeded,1807 ),1808 sponsored_data_size => ensure!(1809 new_limit <= CUSTOM_DATA_LIMIT,1810 <Error<T>>::CollectionLimitBoundsExceeded,1811 ),18121813 sponsored_data_rate_limit => {},1814 token_limit => ensure!(1815 old_limit >= new_limit && new_limit > 0,1816 <Error<T>>::CollectionTokenLimitExceeded1817 ),18181819 sponsor_transfer_timeout(match mode {1820 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1821 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1822 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1823 }) => ensure!(1824 new_limit <= MAX_SPONSOR_TIMEOUT,1825 <Error<T>>::CollectionLimitBoundsExceeded,1826 ),1827 sponsor_approve_timeout => {},1828 owner_can_transfer => ensure!(1829 !limits.owner_can_transfer_instaled() ||1830 old_limit || !new_limit,1831 <Error<T>>::OwnerPermissionsCantBeReverted,1832 ),1833 owner_can_destroy => ensure!(1834 old_limit || !new_limit,1835 <Error<T>>::OwnerPermissionsCantBeReverted,1836 ),1837 transfers_enabled => {},1838 );1839 Ok(new_limit)1840 }18411842 /// Update collection permissions.1843 pub fn update_permissions(1844 user: &T::CrossAccountId,1845 collection: &mut CollectionHandle<T>,1846 new_permission: CollectionPermissions,1847 ) -> DispatchResult {1848 collection.check_is_internal()?;1849 collection.check_is_owner_or_admin(user)?;1850 collection.permissions = Self::clamp_permissions(1851 collection.mode.clone(),1852 &collection.permissions,1853 new_permission,1854 )?;18551856 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1857 <PalletEvm<T>>::deposit_log(1858 erc::CollectionHelpersEvents::CollectionChanged {1859 collection_id: eth::collection_id_to_address(collection.id),1860 }1861 .to_log(T::ContractAddress::get()),1862 );18631864 collection.save()1865 }18661867 /// Merge set fields from `new_permission` to `old_permission`.1868 fn clamp_permissions(1869 _mode: CollectionMode,1870 old_permission: &CollectionPermissions,1871 mut new_permission: CollectionPermissions,1872 ) -> Result<CollectionPermissions, DispatchError> {1873 limit_default_clone!(old_permission, new_permission,1874 access => {},1875 mint_mode => {},1876 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1877 );1878 Ok(new_permission)1879 }18801881 /// Repair possibly broken properties of a collection.1882 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1883 CollectionProperties::<T>::mutate(collection_id, |properties| {1884 properties.recompute_consumed_space();1885 });18861887 Ok(())1888 }1889}18901891/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1892#[macro_export]1893macro_rules! unsupported {1894 ($runtime:path) => {1895 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1896 };1897}18981899/// Return weights for various worst-case operations.1900pub trait CommonWeightInfo<CrossAccountId> {1901 /// Weight of item creation.1902 fn create_item(data: &CreateItemData) -> Weight {1903 Self::create_multiple_items(from_ref(data))1904 }19051906 /// Weight of items creation.1907 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19081909 /// Weight of items creation.1910 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19111912 /// The weight of the burning item.1913 fn burn_item() -> Weight;19141915 /// Property setting weight.1916 ///1917 /// * `amount`- The number of properties to set.1918 fn set_collection_properties(amount: u32) -> Weight;19191920 /// Collection property deletion weight.1921 ///1922 /// * `amount`- The number of properties to set.1923 fn delete_collection_properties(amount: u32) -> Weight {1924 Self::set_collection_properties(amount)1925 }19261927 /// Token property setting weight.1928 ///1929 /// * `amount`- The number of properties to set.1930 fn set_token_properties(amount: u32) -> Weight;19311932 /// Token property deletion weight.1933 ///1934 /// * `amount`- The number of properties to delete.1935 fn delete_token_properties(amount: u32) -> Weight {1936 Self::set_token_properties(amount)1937 }19381939 /// Token property permissions set weight.1940 ///1941 /// * `amount`- The number of property permissions to set.1942 fn set_token_property_permissions(amount: u32) -> Weight;19431944 /// Transfer price of the token or its parts.1945 fn transfer() -> Weight;19461947 /// The price of setting the permission of the operation from another user.1948 fn approve() -> Weight;19491950 /// The price of setting the permission of the operation from another user for eth mirror.1951 fn approve_from() -> Weight;19521953 /// Transfer price from another user.1954 fn transfer_from() -> Weight;19551956 /// The price of burning a token from another user.1957 fn burn_from() -> Weight;19581959 /// The price of setting approval for all1960 fn set_allowance_for_all() -> Weight;19611962 /// The price of repairing an item.1963 fn force_repair_item() -> Weight;1964}19651966/// Weight info extension trait for refungible pallet.1967pub trait RefungibleExtensionsWeightInfo {1968 /// Weight of token repartition.1969 fn repartition() -> Weight;1970}19711972/// Common collection operations.1973///1974/// It wraps methods in Fungible, Nonfungible and Refungible pallets1975/// and adds weight info.1976pub trait CommonCollectionOperations<T: Config> {1977 /// Create token.1978 ///1979 /// * `sender` - The user who mint the token and pays for the transaction.1980 /// * `to` - The user who will own the token.1981 /// * `data` - Token data.1982 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1983 fn create_item(1984 &self,1985 sender: T::CrossAccountId,1986 to: T::CrossAccountId,1987 data: CreateItemData,1988 nesting_budget: &dyn Budget,1989 ) -> DispatchResultWithPostInfo;19901991 /// Create multiple tokens.1992 ///1993 /// * `sender` - The user who mint the token and pays for the transaction.1994 /// * `to` - The user who will own the token.1995 /// * `data` - Token data.1996 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1997 fn create_multiple_items(1998 &self,1999 sender: T::CrossAccountId,2000 to: T::CrossAccountId,2001 data: Vec<CreateItemData>,2002 nesting_budget: &dyn Budget,2003 ) -> DispatchResultWithPostInfo;20042005 /// Create multiple tokens.2006 ///2007 /// * `sender` - The user who mint the token and pays for the transaction.2008 /// * `to` - The user who will own the token.2009 /// * `data` - Token data.2010 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2011 fn create_multiple_items_ex(2012 &self,2013 sender: T::CrossAccountId,2014 data: CreateItemExData<T::CrossAccountId>,2015 nesting_budget: &dyn Budget,2016 ) -> DispatchResultWithPostInfo;20172018 /// Burn token.2019 ///2020 /// * `sender` - The user who owns the token.2021 /// * `token` - Token id that will burned.2022 /// * `amount` - The number of parts of the token that will be burned.2023 fn burn_item(2024 &self,2025 sender: T::CrossAccountId,2026 token: TokenId,2027 amount: u128,2028 ) -> DispatchResultWithPostInfo;20292030 /// Set collection properties.2031 ///2032 /// * `sender` - Must be either the owner of the collection or its admin.2033 /// * `properties` - Properties to be set.2034 fn set_collection_properties(2035 &self,2036 sender: T::CrossAccountId,2037 properties: Vec<Property>,2038 ) -> DispatchResultWithPostInfo;20392040 /// Delete collection properties.2041 ///2042 /// * `sender` - Must be either the owner of the collection or its admin.2043 /// * `properties` - The properties to be removed.2044 fn delete_collection_properties(2045 &self,2046 sender: &T::CrossAccountId,2047 property_keys: Vec<PropertyKey>,2048 ) -> DispatchResultWithPostInfo;20492050 /// Set token properties.2051 ///2052 /// The appropriate [`PropertyPermission`] for the token property2053 /// must be set with [`Self::set_token_property_permissions`].2054 ///2055 /// * `sender` - Must be either the owner of the token or its admin.2056 /// * `token_id` - The token for which the properties are being set.2057 /// * `properties` - Properties to be set.2058 /// * `budget` - Budget for setting properties.2059 fn set_token_properties(2060 &self,2061 sender: T::CrossAccountId,2062 token_id: TokenId,2063 properties: Vec<Property>,2064 budget: &dyn Budget,2065 ) -> DispatchResultWithPostInfo;20662067 /// Remove token properties.2068 ///2069 /// The appropriate [`PropertyPermission`] for the token property2070 /// must be set with [`Self::set_token_property_permissions`].2071 ///2072 /// * `sender` - Must be either the owner of the token or its admin.2073 /// * `token_id` - The token for which the properties are being remove.2074 /// * `property_keys` - Keys to remove corresponding properties.2075 /// * `budget` - Budget for removing properties.2076 fn delete_token_properties(2077 &self,2078 sender: T::CrossAccountId,2079 token_id: TokenId,2080 property_keys: Vec<PropertyKey>,2081 budget: &dyn Budget,2082 ) -> DispatchResultWithPostInfo;20832084 /// Get token properties raw map.2085 ///2086 /// * `token_id` - The token which properties are needed.2087 fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20882089 /// Set token properties raw map.2090 ///2091 /// * `token_id` - The token for which the properties are being set.2092 /// * `map` - The raw map containing the token's properties.2093 fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20942095 /// Set token property permissions.2096 ///2097 /// * `sender` - Must be either the owner of the token or its admin.2098 /// * `token_id` - The token for which the properties are being set.2099 /// * `property_permissions` - Property permissions to be set.2100 /// * `budget` - Budget for setting properties.2101 fn set_token_property_permissions(2102 &self,2103 sender: &T::CrossAccountId,2104 property_permissions: Vec<PropertyKeyPermission>,2105 ) -> DispatchResultWithPostInfo;21062107 /// Transfer amount of token pieces.2108 ///2109 /// * `sender` - Donor user.2110 /// * `to` - Recepient user.2111 /// * `token` - The token of which parts are being sent.2112 /// * `amount` - The number of parts of the token that will be transferred.2113 /// * `budget` - The maximum budget that can be spent on the transfer.2114 fn transfer(2115 &self,2116 sender: T::CrossAccountId,2117 to: T::CrossAccountId,2118 token: TokenId,2119 amount: u128,2120 budget: &dyn Budget,2121 ) -> DispatchResultWithPostInfo;21222123 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2124 ///2125 /// * `sender` - The user who grants access to the token.2126 /// * `spender` - The user to whom the rights are granted.2127 /// * `token` - The token to which access is granted.2128 /// * `amount` - The amount of pieces that another user can dispose of.2129 fn approve(2130 &self,2131 sender: T::CrossAccountId,2132 spender: T::CrossAccountId,2133 token: TokenId,2134 amount: u128,2135 ) -> DispatchResultWithPostInfo;21362137 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2138 ///2139 /// * `sender` - The user who grants access to the token.2140 /// * `from` - Spender's eth mirror.2141 /// * `to` - The user to whom the rights are granted.2142 /// * `token` - The token to which access is granted.2143 /// * `amount` - The amount of pieces that another user can dispose of.2144 fn approve_from(2145 &self,2146 sender: T::CrossAccountId,2147 from: T::CrossAccountId,2148 to: T::CrossAccountId,2149 token: TokenId,2150 amount: u128,2151 ) -> DispatchResultWithPostInfo;21522153 /// Send parts of a token owned by another user.2154 ///2155 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2156 ///2157 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2158 /// * `from` - The user who owns the token.2159 /// * `to` - Recepient user.2160 /// * `token` - The token of which parts are being sent.2161 /// * `amount` - The number of parts of the token that will be transferred.2162 /// * `budget` - The maximum budget that can be spent on the transfer.2163 fn transfer_from(2164 &self,2165 sender: T::CrossAccountId,2166 from: T::CrossAccountId,2167 to: T::CrossAccountId,2168 token: TokenId,2169 amount: u128,2170 budget: &dyn Budget,2171 ) -> DispatchResultWithPostInfo;21722173 /// Burn parts of a token owned by another user.2174 ///2175 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2176 ///2177 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2178 /// * `from` - The user who owns the token.2179 /// * `token` - The token of which parts are being sent.2180 /// * `amount` - The number of parts of the token that will be transferred.2181 /// * `budget` - The maximum budget that can be spent on the burn.2182 fn burn_from(2183 &self,2184 sender: T::CrossAccountId,2185 from: T::CrossAccountId,2186 token: TokenId,2187 amount: u128,2188 budget: &dyn Budget,2189 ) -> DispatchResultWithPostInfo;21902191 /// Check permission to nest token.2192 ///2193 /// * `sender` - The user who initiated the check.2194 /// * `from` - The token that is checked for embedding.2195 /// * `under` - Token under which to check.2196 /// * `budget` - The maximum budget that can be spent on the check.2197 fn check_nesting(2198 &self,2199 sender: &T::CrossAccountId,2200 from: (CollectionId, TokenId),2201 under: TokenId,2202 budget: &dyn Budget,2203 ) -> DispatchResult;22042205 /// Nest one token into another.2206 ///2207 /// * `under` - Token holder.2208 /// * `to_nest` - Nested token.2209 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22102211 /// Unnest token.2212 ///2213 /// * `under` - Token holder.2214 /// * `to_nest` - Token to unnest.2215 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22162217 /// Get all user tokens.2218 ///2219 /// * `account` - Account for which you need to get tokens.2220 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22212222 /// Get all the tokens in the collection.2223 fn collection_tokens(&self) -> Vec<TokenId>;22242225 /// Check if the token exists.2226 ///2227 /// * `token` - Id token to check.2228 fn token_exists(&self, token: TokenId) -> bool;22292230 /// Get the id of the last minted token.2231 fn last_token_id(&self) -> TokenId;22322233 /// Get the owner of the token.2234 ///2235 /// * `token` - The token for which you need to find out the owner.2236 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22372238 /// Checks if the `maybe_owner` is the indirect owner of the `token`.2239 ///2240 /// * `token` - Id token to check.2241 /// * `maybe_owner` - The account to check.2242 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2243 fn check_token_indirect_owner(2244 &self,2245 token: TokenId,2246 maybe_owner: &T::CrossAccountId,2247 nesting_budget: &dyn Budget,2248 ) -> Result<bool, DispatchError>;22492250 /// Returns 10 tokens owners in no particular order.2251 ///2252 /// * `token` - The token for which you need to find out the owners.2253 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22542255 /// Get the value of the token property by key.2256 ///2257 /// * `token` - Token with the property to get.2258 /// * `key` - Property name.2259 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22602261 /// Get a set of token properties by key vector.2262 ///2263 /// * `token` - Token with the property to get.2264 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2265 /// then all properties are returned.2266 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22672268 /// Amount of unique collection tokens2269 fn total_supply(&self) -> u32;22702271 /// Amount of different tokens account has.2272 ///2273 /// * `account` - The account for which need to get the balance.2274 fn account_balance(&self, account: T::CrossAccountId) -> u32;22752276 /// Amount of specific token account have.2277 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22782279 /// Amount of token pieces2280 fn total_pieces(&self, token: TokenId) -> Option<u128>;22812282 /// Get the number of parts of the token that a trusted user can manage.2283 ///2284 /// * `sender` - Trusted user.2285 /// * `spender` - Owner of the token.2286 /// * `token` - The token for which to get the value.2287 fn allowance(2288 &self,2289 sender: T::CrossAccountId,2290 spender: T::CrossAccountId,2291 token: TokenId,2292 ) -> u128;22932294 /// Get extension for RFT collection.2295 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {2296 None2297 }22982299 /// Get XCM extensions.2300 fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {2301 None2302 }23032304 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2305 /// * `owner` - Token owner2306 /// * `operator` - Operator2307 /// * `approve` - Should operator status be granted or revoked?2308 fn set_allowance_for_all(2309 &self,2310 owner: T::CrossAccountId,2311 operator: T::CrossAccountId,2312 approve: bool,2313 ) -> DispatchResultWithPostInfo;23142315 /// Tells whether the given `owner` approves the `operator`.2316 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23172318 /// Repairs a possibly broken item.2319 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2320}23212322/// Extension for RFT collection.2323pub trait RefungibleExtensions<T>2324where2325 T: Config,2326{2327 /// Change the number of parts of the token.2328 ///2329 /// When the value changes down, this function is equivalent to burning parts of the token.2330 ///2331 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2332 /// * `token` - The token for which you want to change the number of parts.2333 /// * `amount` - The new value of the parts of the token.2334 fn repartition(2335 &self,2336 sender: &T::CrossAccountId,2337 token: TokenId,2338 amount: u128,2339 ) -> DispatchResultWithPostInfo;2340}23412342/// XCM extensions for fungible and NFT collections2343pub trait XcmExtensions<T>2344where2345 T: Config,2346{2347 /// Is the collection a foreign one?2348 fn is_foreign(&self) -> bool;23492350 /// Create a collection's item.2351 fn create_item(2352 &self,2353 to: T::CrossAccountId,2354 data: CreateItemData,2355 ) -> Result<TokenId, DispatchError>;23562357 /// Transfer an item from the `from` account to the `to` account.2358 fn transfer(2359 &self,2360 from: T::CrossAccountId,2361 to: T::CrossAccountId,2362 token: TokenId,2363 amount: u128,2364 ) -> DispatchResult;23652366 /// Burn a collection's item.2367 fn burn(&self, from: T::CrossAccountId, token: TokenId, amount: u128) -> DispatchResult;2368}23692370/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2371///2372/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2373pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2374 let post_info = PostDispatchInfo {2375 actual_weight: Some(weight),2376 pays_fee: Pays::Yes,2377 };2378 match res {2379 Ok(()) => Ok(post_info),2380 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2381 }2382}23832384impl<T: Config> From<PropertiesError> for Error<T> {2385 fn from(error: PropertiesError) -> Self {2386 match error {2387 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2388 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2389 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2390 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2391 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2392 }2393 }2394}23952396/// The type-safe interface for writing properties (setting or deleting) to tokens.2397/// It has two distinct implementations for newly created tokens and existing ones.2398///2399/// This type utilizes the lazy evaluation to avoid repeating the computation2400/// of several performance-heavy or PoV-heavy tasks,2401/// such as checking the indirect ownership or reading the token property permissions.2402pub struct PropertyWriter<'a, WriterVariant, T, Handle> {2403 collection: &'a Handle,2404 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2405 _phantom: PhantomData<(T, WriterVariant)>,2406}24072408impl<'a, T, Handle, WriterVariant> PropertyWriter<'a, WriterVariant, T, Handle>2409where2410 T: Config,2411 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2412{2413 fn internal_write_token_properties(2414 &mut self,2415 token_id: TokenId,2416 mut token_lazy_info: PropertyWriterLazyTokenInfo,2417 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2418 log: evm_coder::ethereum::Log,2419 ) -> DispatchResult {2420 for (key, value) in properties_updates {2421 let permission = self2422 .collection_lazy_info2423 .property_permissions2424 .value()2425 .get(&key)2426 .cloned()2427 .unwrap_or_else(PropertyPermission::none);24282429 match permission {2430 PropertyPermission { mutable: false, .. }2431 if token_lazy_info2432 .stored_properties2433 .value()2434 .get(&key)2435 .is_some() =>2436 {2437 return Err(<Error<T>>::NoPermission.into());2438 }24392440 PropertyPermission {2441 collection_admin,2442 token_owner,2443 ..2444 } => check_token_permissions::<T>(2445 collection_admin,2446 token_owner,2447 &mut self.collection_lazy_info.is_collection_admin,2448 &mut token_lazy_info.is_token_owner,2449 &mut token_lazy_info.is_token_exist,2450 )?,2451 }24522453 match value {2454 Some(value) => {2455 token_lazy_info2456 .stored_properties2457 .value_mut()2458 .try_set(key.clone(), value)2459 .map_err(<Error<T>>::from)?;24602461 <Pallet<T>>::deposit_event(Event::TokenPropertySet(2462 self.collection.id,2463 token_id,2464 key,2465 ));2466 }2467 None => {2468 token_lazy_info2469 .stored_properties2470 .value_mut()2471 .remove(&key)2472 .map_err(<Error<T>>::from)?;24732474 <Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2475 self.collection.id,2476 token_id,2477 key,2478 ));2479 }2480 }2481 }24822483 let properties_changed = token_lazy_info.stored_properties.has_value();2484 if properties_changed {2485 <PalletEvm<T>>::deposit_log(log);24862487 self.collection2488 .set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2489 }24902491 Ok(())2492 }2493}24942495/// A helper structure for the [`PropertyWriter`] that holds2496/// the collection-related info. The info is loaded using lazy evaluation.2497/// This info is common for any token for which we write properties.2498pub struct PropertyWriterLazyCollectionInfo<'a> {2499 is_collection_admin: LazyValue<'a, bool>,2500 property_permissions: LazyValue<'a, PropertiesPermissionMap>,2501}25022503/// A helper structure for the [`PropertyWriter`] that holds2504/// the token-related info. The info is loaded using lazy evaluation.2505pub struct PropertyWriterLazyTokenInfo<'a> {2506 is_token_exist: LazyValue<'a, bool>,2507 is_token_owner: LazyValue<'a, Result<bool, DispatchError>>,2508 stored_properties: LazyValue<'a, TokenProperties>,2509}25102511impl<'a> PropertyWriterLazyTokenInfo<'a> {2512 /// Create a lazy token info.2513 pub fn new(2514 check_token_exist: impl FnOnce() -> bool + 'a,2515 check_token_owner: impl FnOnce() -> Result<bool, DispatchError> + 'a,2516 get_token_properties: impl FnOnce() -> TokenProperties + 'a,2517 ) -> Self {2518 Self {2519 is_token_exist: LazyValue::new(check_token_exist),2520 is_token_owner: LazyValue::new(check_token_owner),2521 stored_properties: LazyValue::new(get_token_properties),2522 }2523 }2524}25252526/// A marker structure that enables the writer implementation2527/// to provide the interface to write properties to **newly created** tokens.2528pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2529impl<T: Config> NewTokenPropertyWriter<T> {2530 /// Creates a [`PropertyWriter`] for **newly created** tokens.2531 pub fn new<'a, Handle>(2532 collection: &'a Handle,2533 sender: &'a T::CrossAccountId,2534 ) -> PropertyWriter<'a, Self, T, Handle>2535 where2536 T: Config,2537 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2538 {2539 PropertyWriter {2540 collection,2541 collection_lazy_info: PropertyWriterLazyCollectionInfo {2542 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2543 property_permissions: LazyValue::new(|| {2544 <Pallet<T>>::property_permissions(collection.id)2545 }),2546 },2547 _phantom: PhantomData,2548 }2549 }2550}25512552impl<'a, T, Handle> PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle>2553where2554 T: Config,2555 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2556{2557 /// A function to write properties to a **newly created** token.2558 pub fn write_token_properties(2559 &mut self,2560 mint_target_is_sender: bool,2561 token_id: TokenId,2562 properties_updates: impl Iterator<Item = Property>,2563 log: evm_coder::ethereum::Log,2564 ) -> DispatchResult {2565 let check_token_exist = || {2566 debug_assert!(self.collection.token_exists(token_id));2567 true2568 };25692570 let check_token_owner = || Ok(mint_target_is_sender);25712572 let get_token_properties = || {2573 debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2574 TokenProperties::new()2575 };25762577 self.internal_write_token_properties(2578 token_id,2579 PropertyWriterLazyTokenInfo::new(2580 check_token_exist,2581 check_token_owner,2582 get_token_properties,2583 ),2584 properties_updates.map(|p| (p.key, Some(p.value))),2585 log,2586 )2587 }2588}25892590/// A marker structure that enables the writer implementation2591/// to provide the interface to write properties to **already existing** tokens.2592pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2593impl<T: Config> ExistingTokenPropertyWriter<T> {2594 /// Creates a [`PropertyWriter`] for **already existing** tokens.2595 pub fn new<'a, Handle>(2596 collection: &'a Handle,2597 sender: &'a T::CrossAccountId,2598 ) -> PropertyWriter<'a, Self, T, Handle>2599 where2600 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2601 {2602 PropertyWriter {2603 collection,2604 collection_lazy_info: PropertyWriterLazyCollectionInfo {2605 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2606 property_permissions: LazyValue::new(|| {2607 <Pallet<T>>::property_permissions(collection.id)2608 }),2609 },2610 _phantom: PhantomData,2611 }2612 }2613}26142615impl<'a, T, Handle> PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle>2616where2617 T: Config,2618 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2619{2620 /// A function to write properties to an **already existing** token.2621 pub fn write_token_properties(2622 &mut self,2623 sender: &T::CrossAccountId,2624 token_id: TokenId,2625 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2626 nesting_budget: &dyn Budget,2627 log: evm_coder::ethereum::Log,2628 ) -> DispatchResult {2629 let check_token_exist = || self.collection.token_exists(token_id);2630 let check_token_owner = || {2631 self.collection2632 .check_token_indirect_owner(token_id, sender, nesting_budget)2633 };2634 let get_token_properties = || {2635 self.collection2636 .get_token_properties_raw(token_id)2637 .unwrap_or_default()2638 };26392640 self.internal_write_token_properties(2641 token_id,2642 PropertyWriterLazyTokenInfo::new(2643 check_token_exist,2644 check_token_owner,2645 get_token_properties,2646 ),2647 properties_updates,2648 log,2649 )2650 }2651}26522653/// A marker structure that enables the writer implementation2654/// to benchmark the token properties writing.2655#[cfg(feature = "runtime-benchmarks")]2656pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);26572658#[cfg(feature = "runtime-benchmarks")]2659impl<T: Config> BenchmarkPropertyWriter<T> {2660 /// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2661 pub fn new<'a, Handle>(2662 collection: &'a Handle,2663 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2664 ) -> PropertyWriter<'a, Self, T, Handle>2665 where2666 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2667 {2668 PropertyWriter {2669 collection,2670 collection_lazy_info,2671 _phantom: PhantomData,2672 }2673 }26742675 /// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2676 pub fn load_collection_info<Handle>(2677 collection_handle: &Handle,2678 sender: &T::CrossAccountId,2679 ) -> PropertyWriterLazyCollectionInfo<'static>2680 where2681 Handle: Deref<Target = CollectionHandle<T>>,2682 {2683 let is_collection_admin = collection_handle.is_owner_or_admin(sender);2684 let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);26852686 PropertyWriterLazyCollectionInfo {2687 is_collection_admin: LazyValue::new(move || is_collection_admin),2688 property_permissions: LazyValue::new(move || property_permissions),2689 }2690 }26912692 /// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2693 pub fn load_token_properties<Handle>(2694 collection: &Handle,2695 token_id: TokenId,2696 ) -> PropertyWriterLazyTokenInfo2697 where2698 Handle: CommonCollectionOperations<T>,2699 {2700 let stored_properties = collection2701 .get_token_properties_raw(token_id)2702 .unwrap_or_default();27032704 PropertyWriterLazyTokenInfo {2705 is_token_exist: LazyValue::new(|| true),2706 is_token_owner: LazyValue::new(|| Ok(true)),2707 stored_properties: LazyValue::new(move || stored_properties),2708 }2709 }2710}27112712#[cfg(feature = "runtime-benchmarks")]2713impl<'a, T, Handle> PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle>2714where2715 T: Config,2716 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2717{2718 /// A function to benchmark the writing of token properties.2719 pub fn write_token_properties(2720 &mut self,2721 token_id: TokenId,2722 properties_updates: impl Iterator<Item = Property>,2723 log: evm_coder::ethereum::Log,2724 ) -> DispatchResult {2725 let check_token_exist = || true;2726 let check_token_owner = || Ok(true);2727 let get_token_properties = TokenProperties::new;27282729 self.internal_write_token_properties(2730 token_id,2731 PropertyWriterLazyTokenInfo::new(2732 check_token_exist,2733 check_token_owner,2734 get_token_properties,2735 ),2736 properties_updates.map(|p| (p.key, Some(p.value))),2737 log,2738 )2739 }2740}27412742/// Computes the weight of writing properties to tokens.2743/// * `properties_nums` - The properties num of each created token.2744/// * `per_token_weight_weight` - The function to obtain the weight2745/// of writing properties from a token's properties num.2746pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2747 properties_nums: impl Iterator<Item = u32>,2748 per_token_weight: I,2749) -> Weight {2750 let mut weight = properties_nums2751 .filter_map(|properties_num| {2752 if properties_num > 0 {2753 Some(per_token_weight(properties_num))2754 } else {2755 None2756 }2757 })2758 .fold(Weight::zero(), |a, b| a.saturating_add(b));27592760 if !weight.is_zero() {2761 // If we are here, it means the token properties were written at least once.2762 // Because of that, some common collection data was also loaded; we must add this weight.2763 // However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.27642765 weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2766 }27672768 weight2769}27702771#[cfg(any(feature = "tests", test))]2772#[allow(missing_docs)]2773pub mod tests {2774 use crate::{Config, DispatchError, DispatchResult, LazyValue};27752776 const fn to_bool(u: u8) -> bool {2777 u != 02778 }27792780 #[derive(Debug)]2781 pub struct TestCase {2782 pub collection_admin: bool,2783 pub is_collection_admin: bool,2784 pub token_owner: bool,2785 pub is_token_owner: bool,2786 pub no_permission: bool,2787 }27882789 impl TestCase {2790 const fn new(2791 collection_admin: u8,2792 is_collection_admin: u8,2793 token_owner: u8,2794 is_token_owner: u8,2795 no_permission: u8,2796 ) -> Self {2797 Self {2798 collection_admin: to_bool(collection_admin),2799 is_collection_admin: to_bool(is_collection_admin),2800 token_owner: to_bool(token_owner),2801 is_token_owner: to_bool(is_token_owner),2802 no_permission: to_bool(no_permission),2803 }2804 }2805 }28062807 #[rustfmt::skip]2808 pub const TABLE: [TestCase; 16] = [2809 // ┌╴collection_admin2810 // │ ┌╴is_collection_admin2811 // │ │ ┌╴token_owner2812 // │ │ │ ┌╴is_token_ownership2813 // │ │ │ │ ┌╴no_permission2814 /* 0*/ TestCase::new(0, 0, 0, 0, 1),2815 /* 1*/ TestCase::new(0, 0, 0, 1, 1),2816 /* 2*/ TestCase::new(0, 0, 1, 0, 1),2817 /* 3*/ TestCase::new(0, 0, 1, 1, 0),2818 /* 4*/ TestCase::new(0, 1, 0, 0, 1),2819 /* 5*/ TestCase::new(0, 1, 0, 1, 1),2820 /* 6*/ TestCase::new(0, 1, 1, 0, 1),2821 /* 7*/ TestCase::new(0, 1, 1, 1, 0),2822 /* 8*/ TestCase::new(1, 0, 0, 0, 1),2823 /* 9*/ TestCase::new(1, 0, 0, 1, 1),2824 /* 10*/ TestCase::new(1, 0, 1, 0, 1),2825 /* 11*/ TestCase::new(1, 0, 1, 1, 0),2826 /* 12*/ TestCase::new(1, 1, 0, 0, 0),2827 /* 13*/ TestCase::new(1, 1, 0, 1, 0),2828 /* 14*/ TestCase::new(1, 1, 1, 0, 0),2829 /* 15*/ TestCase::new(1, 1, 1, 1, 0),2830 ];28312832 pub fn check_token_permissions<T: Config>(2833 collection_admin_permitted: bool,2834 token_owner_permitted: bool,2835 is_collection_admin: &mut LazyValue<bool>,2836 check_token_ownership: &mut LazyValue<Result<bool, DispatchError>>,2837 check_token_existence: &mut LazyValue<bool>,2838 ) -> DispatchResult {2839 crate::check_token_permissions::<T>(2840 collection_admin_permitted,2841 token_owner_permitted,2842 is_collection_admin,2843 check_token_ownership,2844 check_token_existence,2845 )2846 }2847}pallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ /dev/null
@@ -1,499 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network 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.
-
-// Unique Network 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 Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-//! Implementations for fungibles trait.
-
-use frame_support::traits::tokens::{
- DepositConsequence, Fortitude, Precision, Preservation, Provenance, WithdrawConsequence,
-};
-use frame_system::Config as SystemConfig;
-use pallet_common::{CollectionHandle, CommonCollectionOperations};
-use pallet_fungible::FungibleHandle;
-use sp_runtime::traits::{CheckedAdd, CheckedSub};
-use up_data_structs::budget;
-
-use super::*;
-
-impl<T: Config> fungibles::Inspect<<T as SystemConfig>::AccountId> for Pallet<T>
-where
- T: orml_tokens::Config<CurrencyId = AssetId>,
- BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
- BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
- <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
- <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,
-{
- type AssetId = AssetId;
- type Balance = BalanceOf<T>;
-
- fn total_issuance(asset: Self::AssetId) -> Self::Balance {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible total_issuance");
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::total_issuance()
- .into()
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::total_issuance(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- )
- .into()
- }
- AssetId::ForeignAssetId(fid) => {
- let target_collection_id = match <AssetBinding<T>>::get(fid) {
- Some(v) => v,
- None => return Zero::zero(),
- };
- let collection_handle = match <CollectionHandle<T>>::try_get(target_collection_id) {
- Ok(v) => v,
- Err(_) => return Zero::zero(),
- };
- let collection = FungibleHandle::cast(collection_handle);
- Self::Balance::try_from(collection.total_supply()).unwrap_or(Zero::zero())
- }
- }
- }
-
- fn minimum_balance(asset: Self::AssetId) -> Self::Balance {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible minimum_balance");
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::minimum_balance()
- .into()
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::minimum_balance(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- )
- .into()
- }
- AssetId::ForeignAssetId(fid) => AssetMetadatas::<T>::get(AssetId::ForeignAssetId(fid))
- .map(|x| x.minimal_balance)
- .unwrap_or_else(Zero::zero),
- }
- }
-
- fn balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible balance");
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::balance(who).into()
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::balance(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- )
- .into()
- }
- AssetId::ForeignAssetId(fid) => {
- let target_collection_id = match <AssetBinding<T>>::get(fid) {
- Some(v) => v,
- None => return Zero::zero(),
- };
- let collection_handle = match <CollectionHandle<T>>::try_get(target_collection_id) {
- Ok(v) => v,
- Err(_) => return Zero::zero(),
- };
- let collection = FungibleHandle::cast(collection_handle);
- Self::Balance::try_from(
- collection.balance(T::CrossAccountId::from_sub(who.clone()), TokenId(0)),
- )
- .unwrap_or(Zero::zero())
- }
- }
- }
-
- fn total_balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {
- Self::balance(asset, who)
- }
-
- fn reducible_balance(
- asset: Self::AssetId,
- who: &<T as SystemConfig>::AccountId,
- preservation: Preservation,
- fortitude: Fortitude,
- ) -> Self::Balance {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible reducible_balance");
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::reducible_balance(
- who,
- preservation,
- fortitude,
- )
- .into()
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::reducible_balance(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- preservation,
- fortitude,
- )
- .into()
- }
- _ => Self::balance(asset, who),
- }
- }
-
- fn can_deposit(
- asset: Self::AssetId,
- who: &<T as SystemConfig>::AccountId,
- amount: Self::Balance,
- provenance: Provenance,
- ) -> DepositConsequence {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_deposit");
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_deposit(
- who,
- amount.into(),
- provenance,
- )
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_deposit(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- amount.into(),
- provenance,
- )
- }
- _ => {
- if amount.is_zero() {
- return DepositConsequence::Success;
- }
-
- let extential_deposit_value = T::ExistentialDeposit::get();
- let ed_value: u128 = match extential_deposit_value.try_into() {
- Ok(val) => val,
- Err(_) => return DepositConsequence::CannotCreate,
- };
- let extential_deposit: Self::Balance = match ed_value.try_into() {
- Ok(val) => val,
- Err(_) => return DepositConsequence::CannotCreate,
- };
-
- let new_total_balance = match Self::balance(asset, who).checked_add(&amount) {
- Some(x) => x,
- None => return DepositConsequence::Overflow,
- };
-
- if new_total_balance < extential_deposit {
- return DepositConsequence::BelowMinimum;
- }
-
- DepositConsequence::Success
- }
- }
- }
-
- fn can_withdraw(
- asset: Self::AssetId,
- who: &<T as SystemConfig>::AccountId,
- amount: Self::Balance,
- ) -> WithdrawConsequence<Self::Balance> {
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_withdraw");
- let value: u128 = match amount.try_into() {
- Ok(val) => val,
- Err(_) => return WithdrawConsequence::UnknownAsset,
- };
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return WithdrawConsequence::UnknownAsset;
- }
- };
- match <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_withdraw(
- who,
- this_amount,
- ) {
- WithdrawConsequence::BalanceLow => WithdrawConsequence::BalanceLow,
- WithdrawConsequence::WouldDie => WithdrawConsequence::WouldDie,
- WithdrawConsequence::UnknownAsset => WithdrawConsequence::UnknownAsset,
- WithdrawConsequence::Underflow => WithdrawConsequence::Underflow,
- WithdrawConsequence::Overflow => WithdrawConsequence::Overflow,
- WithdrawConsequence::Frozen => WithdrawConsequence::Frozen,
- WithdrawConsequence::Success => WithdrawConsequence::Success,
- _ => WithdrawConsequence::BalanceLow,
- }
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {
- Ok(val) => val,
- Err(_) => {
- return WithdrawConsequence::UnknownAsset;
- }
- };
- match <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_withdraw(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- parent_amount,
- ) {
- WithdrawConsequence::BalanceLow => WithdrawConsequence::BalanceLow,
- WithdrawConsequence::WouldDie => WithdrawConsequence::WouldDie,
- WithdrawConsequence::UnknownAsset => WithdrawConsequence::UnknownAsset,
- WithdrawConsequence::Underflow => WithdrawConsequence::Underflow,
- WithdrawConsequence::Overflow => WithdrawConsequence::Overflow,
- WithdrawConsequence::Frozen => WithdrawConsequence::Frozen,
- WithdrawConsequence::Success => WithdrawConsequence::Success,
- _ => WithdrawConsequence::BalanceLow,
- }
- }
- _ => match Self::balance(asset, who).checked_sub(&amount) {
- Some(_) => WithdrawConsequence::Success,
- None => WithdrawConsequence::BalanceLow,
- },
- }
- }
-
- fn asset_exists(asset: AssetId) -> bool {
- match asset {
- AssetId::NativeAssetId(_) => true,
- AssetId::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),
- }
- }
-}
-
-impl<T: Config> fungibles::Mutate<<T as SystemConfig>::AccountId> for Pallet<T>
-where
- T: orml_tokens::Config<CurrencyId = AssetId>,
- BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
- BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
- <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
- <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,
- u128: From<BalanceOf<T>>,
-{
- fn mint_into(
- asset: Self::AssetId,
- who: &<T as SystemConfig>::AccountId,
- amount: Self::Balance,
- ) -> Result<BalanceOf<T>, DispatchError> {
- //Self::do_mint(asset, who, amount, None)
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible mint_into {:?}", asset);
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::mint_into(
- who,
- amount.into(),
- )
- .map(Into::into)
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::mint_into(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- amount.into(),
- )
- .map(Into::into)
- }
- AssetId::ForeignAssetId(fid) => {
- let target_collection_id = match <AssetBinding<T>>::get(fid) {
- Some(v) => v,
- None => {
- return Err(DispatchError::Other(
- "Associated collection not found for asset",
- ))
- }
- };
- let collection =
- 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(), amount.into());
-
- pallet_fungible::Pallet::<T>::create_item_foreign(
- &collection,
- &account,
- amount_data,
- &budget::Value::new(0),
- )?;
-
- Ok(amount)
- }
- }
- }
-
- fn burn_from(
- asset: Self::AssetId,
- who: &<T as SystemConfig>::AccountId,
- amount: Self::Balance,
- precision: Precision,
- fortitude: Fortitude,
- ) -> Result<Self::Balance, DispatchError> {
- // let f = DebitFlags { keep_alive: false, best_effort: false };
- log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible burn_from");
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::burn_from(
- who,
- amount.into(),
- precision,
- fortitude,
- )
- .map(Into::into)
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::burn_from(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- who,
- amount.into(),
- precision,
- fortitude,
- )
- .map(Into::into)
- }
- AssetId::ForeignAssetId(fid) => {
- let target_collection_id = match <AssetBinding<T>>::get(fid) {
- Some(v) => v,
- None => {
- return Err(DispatchError::Other(
- "Associated collection not found for asset",
- ))
- }
- };
- let collection =
- FungibleHandle::cast(<CollectionHandle<T>>::try_get(target_collection_id)?);
- pallet_fungible::Pallet::<T>::burn_foreign(
- &collection,
- &T::CrossAccountId::from_sub(who.clone()),
- amount.into(),
- )?;
-
- Ok(amount)
- }
- }
- }
-
- fn transfer(
- asset: Self::AssetId,
- source: &<T as SystemConfig>::AccountId,
- dest: &<T as SystemConfig>::AccountId,
- amount: Self::Balance,
- preservation: Preservation,
- ) -> 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");
-
- match asset {
- AssetId::NativeAssetId(NativeCurrency::Here) => {
- match <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::transfer(
- source,
- dest,
- amount.into(),
- preservation,
- ) {
- Ok(_) => Ok(amount),
- Err(_) => Err(DispatchError::Other(
- "Bad amount to relay chain value conversion",
- )),
- }
- }
- AssetId::NativeAssetId(NativeCurrency::Parent) => {
- match <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::transfer(
- AssetId::NativeAssetId(NativeCurrency::Parent),
- source,
- dest,
- amount.into(),
- preservation,
- ) {
- Ok(_) => Ok(amount),
- Err(e) => Err(e),
- }
- }
- AssetId::ForeignAssetId(fid) => {
- let target_collection_id = match <AssetBinding<T>>::get(fid) {
- Some(v) => v,
- None => {
- return Err(DispatchError::Other(
- "Associated collection not found for asset",
- ))
- }
- };
- let collection =
- FungibleHandle::cast(<CollectionHandle<T>>::try_get(target_collection_id)?);
-
- pallet_fungible::Pallet::<T>::transfer(
- &collection,
- &T::CrossAccountId::from_sub(source.clone()),
- &T::CrossAccountId::from_sub(dest.clone()),
- amount.into(),
- &budget::Value::new(0),
- )
- .map_err(|e| e.error)?;
-
- Ok(amount)
- }
- }
- }
-}
-
-#[cfg(not(debug_assertions))]
-extern "C" {
- // This function does not exists, thus compilation will fail, if its call is
- // not optimized away, which is only possible if it's not called at all.
- //
- // not(debug_assertions) is used to ensure compiler is dropping unused functions, as
- // this option is enabled in release by defailt
- //
- // FIXME: maybe use build.rs, to ensure it will fail even in release with debug_assertions
- // enabled?
- fn unbalanced_fungible_is_called();
-}
-macro_rules! ensure_balanced {
- () => {{
- #[cfg(debug_assertions)]
- panic!("unbalanced fungible methods should not be used");
- #[cfg(not(debug_assertions))]
- {
- unsafe { unbalanced_fungible_is_called() };
- unreachable!();
- }
- }};
-}
-
-impl<T: Config> fungibles::Unbalanced<<T as SystemConfig>::AccountId> for Pallet<T>
-where
- T: orml_tokens::Config<CurrencyId = AssetId>,
- BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
- BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
- <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
- <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,
- u128: From<BalanceOf<T>>,
-{
- fn handle_dust(_dust: fungibles::Dust<<T as SystemConfig>::AccountId, Self>) {
- ensure_balanced!();
- }
- fn write_balance(
- _asset: Self::AssetId,
- _who: &<T as SystemConfig>::AccountId,
- _amount: Self::Balance,
- ) -> Result<Option<Self::Balance>, DispatchError> {
- ensure_balanced!();
- }
- fn set_total_issuance(_asset: Self::AssetId, _amount: Self::Balance) {
- ensure_balanced!();
- }
-}
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -34,93 +34,27 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]
-use frame_support::{
- dispatch::DispatchResult,
- ensure,
- pallet_prelude::*,
- traits::{fungible, fungibles, Currency, EnsureOrigin},
-};
+use frame_support::{dispatch::DispatchResult, pallet_prelude::*, traits::EnsureOrigin, PalletId};
use frame_system::pallet_prelude::*;
-use pallet_common::erc::CrossAccountId;
-use pallet_fungible::Pallet as PalletFungible;
-use scale_info::TypeInfo;
-use serde::{Deserialize, Serialize};
-use sp_runtime::{
- traits::{One, Zero},
- ArithmeticError,
+use pallet_common::{
+ dispatch::CollectionDispatch, erc::CrossAccountId, NATIVE_FUNGIBLE_COLLECTION_ID,
};
-use sp_std::{boxed::Box, vec::Vec};
-use staging_xcm::{latest::MultiLocation, VersionedMultiLocation};
+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::XcmContext,
+ v3::{prelude::*, MultiAsset, XcmContext},
+};
+use staging_xcm_executor::{
+ traits::{TransactAsset, WeightTrader},
+ Assets,
};
-use staging_xcm_executor::{traits::WeightTrader, Assets};
-use up_data_structs::{CollectionId, CollectionMode, CreateCollectionData, TokenId};
-
-// TODO: Move to primitives
-// Id of native currency.
-// 0 - QTZ\UNQ
-// 1 - KSM\DOT
-#[derive(
- Clone,
- Copy,
- Eq,
- PartialEq,
- PartialOrd,
- Ord,
- MaxEncodedLen,
- RuntimeDebug,
- Encode,
- Decode,
- TypeInfo,
- Serialize,
- Deserialize,
-)]
-pub enum NativeCurrency {
- Here = 0,
- Parent = 1,
-}
-
-#[derive(
- Clone,
- Copy,
- Eq,
- PartialEq,
- PartialOrd,
- Ord,
- MaxEncodedLen,
- RuntimeDebug,
- Encode,
- Decode,
- TypeInfo,
- Serialize,
- Deserialize,
-)]
-pub enum AssetId {
- ForeignAssetId(ForeignAssetId),
- NativeAssetId(NativeCurrency),
-}
-
-pub trait TryAsForeign<T, F> {
- fn try_as_foreign(asset: T) -> Option<F>;
-}
-
-impl TryAsForeign<AssetId, ForeignAssetId> for AssetId {
- fn try_as_foreign(asset: AssetId) -> Option<ForeignAssetId> {
- match asset {
- Self::ForeignAssetId(id) => Some(id),
- _ => None,
- }
- }
-}
-
-pub type ForeignAssetId = u32;
-pub type CurrencyId = AssetId;
+use up_data_structs::{
+ CollectionId, CollectionMode, CollectionName, CreateCollectionData, PropertyKey, TokenId,
+};
-mod impl_fungibles;
pub mod weights;
#[cfg(feature = "runtime-benchmarks")]
@@ -128,44 +62,13 @@
pub use module::*;
pub use weights::WeightInfo;
-
-/// Type alias for currency balance.
-pub type BalanceOf<T> =
- <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
-
-/// A mapping between ForeignAssetId and AssetMetadata.
-pub trait AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata> {
- /// Returns the AssetMetadata associated with a given ForeignAssetId.
- fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata>;
- /// Returns the MultiLocation associated with a given ForeignAssetId.
- fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation>;
- /// Returns the CurrencyId associated with a given MultiLocation.
- fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId>;
-}
-
-pub struct XcmForeignAssetIdMapping<T>(sp_std::marker::PhantomData<T>);
-
-impl<T: Config> AssetIdMapping<ForeignAssetId, MultiLocation, AssetMetadata<BalanceOf<T>>>
- for XcmForeignAssetIdMapping<T>
-{
- fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {
- log::trace!(target: "fassets::asset_metadatas", "call");
- Pallet::<T>::asset_metadatas(AssetId::ForeignAssetId(foreign_asset_id))
- }
-
- fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {
- log::trace!(target: "fassets::get_multi_location", "call");
- Pallet::<T>::foreign_asset_locations(foreign_asset_id)
- }
- fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {
- log::trace!(target: "fassets::get_currency_id", "call");
- Pallet::<T>::location_to_currency_ids(multi_location).map(AssetId::ForeignAssetId)
- }
-}
-
#[frame_support::pallet]
pub mod module {
+ use up_data_structs::{
+ CollectionDescription, Property, PropertyKeyPermission, PropertyPermission,
+ };
+
use super::*;
#[pallet::config]
@@ -173,44 +76,25 @@
frame_system::Config
+ pallet_common::Config
+ pallet_fungible::Config
- + orml_tokens::Config
+ pallet_balances::Config
{
/// The overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
- /// Currency type for withdraw and balance storage.
- type Currency: Currency<Self::AccountId>;
+ /// Origin for force registering of a foreign asset.
+ type ForceRegisterOrigin: EnsureOrigin<Self::RuntimeOrigin>;
- /// Required origin for registering asset.
- type RegisterOrigin: EnsureOrigin<Self::RuntimeOrigin>;
+ /// The ID of the foreign assets pallet.
+ type PalletId: Get<PalletId>;
/// Weight information for the extrinsics in this module.
type WeightInfo: WeightInfo;
}
-
- pub type AssetName = BoundedVec<u8, ConstU32<32>>;
- pub type AssetSymbol = BoundedVec<u8, ConstU32<7>>;
- #[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)]
- pub struct AssetMetadata<Balance> {
- pub name: AssetName,
- pub symbol: AssetSymbol,
- pub decimals: u8,
- pub minimal_balance: Balance,
- }
-
#[pallet::error]
pub enum Error<T> {
- /// The given location could not be used (e.g. because it cannot be expressed in the
- /// desired version of XCM).
- BadLocation,
- /// MultiLocation existed
- MultiLocationExisted,
- /// AssetId not exists
- AssetIdNotExists,
- /// AssetId exists
- AssetIdExisted,
+ /// The foreign asset is already registered
+ ForeignAssetAlreadyRegistered,
}
#[pallet::event]
@@ -218,64 +102,28 @@
pub enum Event<T: Config> {
/// The foreign asset registered.
ForeignAssetRegistered {
- asset_id: ForeignAssetId,
- asset_address: MultiLocation,
- metadata: AssetMetadata<BalanceOf<T>>,
- },
- /// The foreign asset updated.
- ForeignAssetUpdated {
- asset_id: ForeignAssetId,
- asset_address: MultiLocation,
- metadata: AssetMetadata<BalanceOf<T>>,
- },
- /// The asset registered.
- AssetRegistered {
- asset_id: AssetId,
- metadata: AssetMetadata<BalanceOf<T>>,
+ asset_id: CollectionId,
+ reserve_location: MultiLocation,
},
- /// The asset updated.
- AssetUpdated {
- asset_id: AssetId,
- metadata: AssetMetadata<BalanceOf<T>>,
- },
}
- /// Next available Foreign AssetId ID.
- ///
- /// NextForeignAssetId: ForeignAssetId
- #[pallet::storage]
- #[pallet::getter(fn next_foreign_asset_id)]
- pub type NextForeignAssetId<T: Config> = StorageValue<_, ForeignAssetId, ValueQuery>;
- /// The storages for MultiLocations.
- ///
- /// ForeignAssetLocations: map ForeignAssetId => Option<MultiLocation>
- #[pallet::storage]
- #[pallet::getter(fn foreign_asset_locations)]
- pub type ForeignAssetLocations<T: Config> =
- StorageMap<_, Twox64Concat, ForeignAssetId, staging_xcm::v3::MultiLocation, OptionQuery>;
-
- /// The storages for CurrencyIds.
- ///
- /// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>
+ /// The corresponding collections of reserve locations.
#[pallet::storage]
- #[pallet::getter(fn location_to_currency_ids)]
- pub type LocationToCurrencyIds<T: Config> =
- StorageMap<_, Twox64Concat, staging_xcm::v3::MultiLocation, ForeignAssetId, OptionQuery>;
+ #[pallet::getter(fn foreign_reserve_location_to_collection)]
+ pub type ForeignReserveLocationToCollection<T: Config> =
+ StorageMap<_, Twox64Concat, staging_xcm::v3::MultiLocation, CollectionId, OptionQuery>;
- /// The storages for AssetMetadatas.
- ///
- /// AssetMetadatas: map AssetIds => Option<AssetMetadata>
+ /// The correponding NFT token id of reserve NFTs
#[pallet::storage]
- #[pallet::getter(fn asset_metadatas)]
- pub type AssetMetadatas<T: Config> =
- StorageMap<_, Twox64Concat, AssetId, AssetMetadata<BalanceOf<T>>, OptionQuery>;
-
- /// The storages for assets to fungible collection binding
- ///
- #[pallet::storage]
- #[pallet::getter(fn asset_binding)]
- pub type AssetBinding<T: Config> =
- StorageMap<_, Twox64Concat, ForeignAssetId, CollectionId, OptionQuery>;
+ #[pallet::getter(fn foreign_reserve_asset_instance_to_token_id)]
+ pub type ForeignReserveAssetInstanceToTokenId<T: Config> = StorageDoubleMap<
+ Hasher1 = Twox64Concat,
+ Key1 = CollectionId,
+ Hasher2 = Twox64Concat,
+ Key2 = staging_xcm::v3::AssetInstance,
+ Value = TokenId,
+ QueryKind = OptionQuery,
+ >;
#[pallet::pallet]
pub struct Pallet<T>(_);
@@ -284,164 +132,152 @@
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::register_foreign_asset())]
- pub fn register_foreign_asset(
+ pub fn force_register_foreign_asset(
origin: OriginFor<T>,
- owner: T::AccountId,
- location: Box<VersionedMultiLocation>,
- metadata: Box<AssetMetadata<BalanceOf<T>>>,
+ reserve_location: MultiLocation,
+ name: CollectionName,
+ mode: CollectionMode,
) -> DispatchResult {
- T::RegisterOrigin::ensure_origin(origin.clone())?;
+ T::ForceRegisterOrigin::ensure_origin(origin.clone())?;
- let location: MultiLocation = (*location)
- .try_into()
- .map_err(|()| Error::<T>::BadLocation)?;
+ let foreign_collection_owner = Self::pallet_account();
- let md = metadata.clone();
- let name: Vec<u16> = md.name.into_iter().map(|x| x as u16).collect::<Vec<u16>>();
- let mut description: Vec<u16> = "Foreign assets collection for "
+ let description: CollectionDescription = "Foreign Assets Collection"
.encode_utf16()
- .collect::<Vec<u16>>();
- description.append(&mut name.clone());
+ .collect::<Vec<_>>()
+ .try_into()
+ .expect("description length < max description length; qed");
- let data: CreateCollectionData<T::CrossAccountId> = CreateCollectionData {
- name: name.try_into().unwrap(),
- description: description.try_into().unwrap(),
- mode: CollectionMode::Fungible(md.decimals),
- ..Default::default()
- };
- let owner = T::CrossAccountId::from_sub(owner);
- let bounded_collection_id =
- <PalletFungible<T>>::init_foreign_collection(owner.clone(), owner, data)?;
- let foreign_asset_id =
- Self::do_register_foreign_asset(&location, &metadata, bounded_collection_id)?;
+ let collection_id = T::CollectionDispatch::create_foreign(
+ foreign_collection_owner,
+ CreateCollectionData {
+ name,
+ description,
+ mode,
- Self::deposit_event(Event::<T>::ForeignAssetRegistered {
- asset_id: foreign_asset_id,
- asset_address: location,
- metadata: *metadata,
- });
- Ok(())
- }
+ properties: vec![Property {
+ key: Self::reserve_location_property_key(),
+ value: reserve_location
+ .encode()
+ .try_into()
+ .expect("multilocation is less than 32k; qed"),
+ }]
+ .try_into()
+ .expect("just one property can always be stored; qed"),
- #[pallet::call_index(1)]
- #[pallet::weight(<T as Config>::WeightInfo::update_foreign_asset())]
- pub fn update_foreign_asset(
- origin: OriginFor<T>,
- foreign_asset_id: ForeignAssetId,
- location: Box<VersionedMultiLocation>,
- metadata: Box<AssetMetadata<BalanceOf<T>>>,
- ) -> DispatchResult {
- T::RegisterOrigin::ensure_origin(origin)?;
+ token_property_permissions: vec![PropertyKeyPermission {
+ key: Self::reserve_asset_instance_property_key(),
+ permission: PropertyPermission {
+ mutable: false,
+ collection_admin: true,
+ token_owner: false,
+ },
+ }]
+ .try_into()
+ .expect("just one property permission can always be stored; qed"),
+ ..Default::default()
+ },
+ )?;
- let location: MultiLocation = (*location)
- .try_into()
- .map_err(|()| Error::<T>::BadLocation)?;
- Self::do_update_foreign_asset(foreign_asset_id, &location, &metadata)?;
+ <ForeignReserveLocationToCollection<T>>::insert(reserve_location, collection_id);
- Self::deposit_event(Event::<T>::ForeignAssetUpdated {
- asset_id: foreign_asset_id,
- asset_address: location,
- metadata: *metadata,
+ Self::deposit_event(Event::<T>::ForeignAssetRegistered {
+ asset_id: collection_id,
+ reserve_location,
});
+
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
- fn get_next_foreign_asset_id() -> Result<ForeignAssetId, DispatchError> {
- NextForeignAssetId::<T>::try_mutate(|current| -> Result<ForeignAssetId, DispatchError> {
- let id = *current;
- *current = current
- .checked_add(One::one())
- .ok_or(ArithmeticError::Overflow)?;
- Ok(id)
- })
+ fn pallet_account() -> T::CrossAccountId {
+ let owner: T::AccountId = T::PalletId::get().into_account_truncating();
+ T::CrossAccountId::from_sub(owner)
}
- fn do_register_foreign_asset(
- location: &MultiLocation,
- metadata: &AssetMetadata<BalanceOf<T>>,
- bounded_collection_id: CollectionId,
- ) -> Result<ForeignAssetId, DispatchError> {
- let foreign_asset_id = Self::get_next_foreign_asset_id()?;
- LocationToCurrencyIds::<T>::try_mutate(location, |maybe_currency_ids| -> DispatchResult {
- ensure!(
- maybe_currency_ids.is_none(),
- Error::<T>::MultiLocationExisted
- );
- *maybe_currency_ids = Some(foreign_asset_id);
- // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));
+ fn reserve_location_property_key() -> PropertyKey {
+ b"reserve-location"
+ .to_vec()
+ .try_into()
+ .expect("key length < max property key length; qed")
+ }
- ForeignAssetLocations::<T>::try_mutate(
- foreign_asset_id,
- |maybe_location| -> DispatchResult {
- ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);
- *maybe_location = Some(*location);
+ fn reserve_asset_instance_property_key() -> PropertyKey {
+ b"reserve-asset-instance"
+ .to_vec()
+ .try_into()
+ .expect("key length < max property key length; qed")
+ }
+}
- AssetMetadatas::<T>::try_mutate(
- AssetId::ForeignAssetId(foreign_asset_id),
- |maybe_asset_metadatas| -> DispatchResult {
- ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);
- *maybe_asset_metadatas = Some(metadata.clone());
- Ok(())
- },
- )
- },
- )?;
+impl<T: Config> TransactAsset for Pallet<T> {
+ fn can_check_in(
+ _origin: &MultiLocation,
+ _what: &MultiAsset,
+ _context: &XcmContext,
+ ) -> XcmResult {
+ Err(XcmError::Unimplemented)
+ }
- AssetBinding::<T>::try_mutate(foreign_asset_id, |collection_id| -> DispatchResult {
- *collection_id = Some(bounded_collection_id);
- Ok(())
- })
- })?;
+ fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
- Ok(foreign_asset_id)
+ fn can_check_out(
+ _dest: &MultiLocation,
+ _what: &MultiAsset,
+ _context: &XcmContext,
+ ) -> XcmResult {
+ Err(XcmError::Unimplemented)
+ }
+
+ fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
+
+ fn deposit_asset(what: &MultiAsset, to: &MultiLocation, context: &XcmContext) -> XcmResult {
+ Err(XcmError::Unimplemented)
+ }
+
+ fn withdraw_asset(
+ what: &MultiAsset,
+ from: &MultiLocation,
+ _maybe_context: Option<&XcmContext>,
+ ) -> Result<staging_xcm_executor::Assets, XcmError> {
+ Err(XcmError::Unimplemented)
}
- fn do_update_foreign_asset(
- foreign_asset_id: ForeignAssetId,
- location: &MultiLocation,
- metadata: &AssetMetadata<BalanceOf<T>>,
- ) -> DispatchResult {
- ForeignAssetLocations::<T>::try_mutate(
- foreign_asset_id,
- |maybe_multi_locations| -> DispatchResult {
- let old_multi_locations = maybe_multi_locations
- .as_mut()
- .ok_or(Error::<T>::AssetIdNotExists)?;
+ fn internal_transfer_asset(
+ what: &MultiAsset,
+ from: &MultiLocation,
+ to: &MultiLocation,
+ _context: &XcmContext,
+ ) -> Result<staging_xcm_executor::Assets, XcmError> {
+ Err(XcmError::Unimplemented)
+ }
+}
- AssetMetadatas::<T>::try_mutate(
- AssetId::ForeignAssetId(foreign_asset_id),
- |maybe_asset_metadatas| -> DispatchResult {
- ensure!(
- maybe_asset_metadatas.is_some(),
- Error::<T>::AssetIdNotExists
- );
+pub struct CurrencyIdConvert<T: Config>(PhantomData<T>);
+impl<T: Config> sp_runtime::traits::Convert<CollectionId, Option<MultiLocation>>
+ for CurrencyIdConvert<T>
+{
+ fn convert(collection_id: CollectionId) -> Option<MultiLocation> {
+ 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()?;
- // modify location
- if location != old_multi_locations {
- LocationToCurrencyIds::<T>::remove(*old_multi_locations);
- LocationToCurrencyIds::<T>::try_mutate(
- location,
- |maybe_currency_ids| -> DispatchResult {
- ensure!(
- maybe_currency_ids.is_none(),
- Error::<T>::MultiLocationExisted
- );
- // *maybe_currency_ids = Some(CurrencyId::ForeignAsset(foreign_asset_id));
- *maybe_currency_ids = Some(foreign_asset_id);
- Ok(())
- },
- )?;
- }
- *maybe_asset_metadatas = Some(metadata.clone());
- *old_multi_locations = *location;
- Ok(())
- },
- )
- },
- )
+ // 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!()
+ }
}
}
@@ -452,28 +288,11 @@
weights::{WeightToFee, WeightToFeePolynomial},
};
-pub struct FreeForAll<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
->(
- Weight,
- Currency::Balance,
- PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,
-);
+pub struct FreeForAll;
-impl<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
- > WeightTrader for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
-{
+impl WeightTrader for FreeForAll {
fn new() -> Self {
- Self(Weight::default(), Zero::zero(), PhantomData)
+ Self
}
fn buy_weight(
@@ -484,17 +303,5 @@
) -> Result<Assets, XcmError> {
log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);
Ok(payment)
- }
-}
-impl<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced> Drop
- for FreeForAll<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
-where
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
-{
- fn drop(&mut self) {
- OnUnbalanced::on_unbalanced(Currency::issue(self.1));
}
}
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -428,10 +428,6 @@
<Allowance<T>>::get((self.id, sender, spender))
}
- fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {
- None
- }
-
fn total_pieces(&self, token: TokenId) -> Option<u128> {
if token != TokenId::default() {
return None;
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -212,24 +212,6 @@
/// Pallet implementation for fungible assets
impl<T: Config> Pallet<T> {
- /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.
- pub fn init_collection(
- owner: T::CrossAccountId,
- payer: T::CrossAccountId,
- data: CreateCollectionData<T::CrossAccountId>,
- ) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data)
- }
-
- /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.
- pub fn init_foreign_collection(
- owner: T::CrossAccountId,
- payer: T::CrossAccountId,
- data: CreateCollectionData<T::CrossAccountId>,
- ) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_foreign_collection(owner, payer, data)
- }
-
/// Destroys a collection.
pub fn destroy_collection(
collection: FungibleHandle<T>,
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -535,10 +535,6 @@
}
}
- fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {
- None
- }
-
fn total_pieces(&self, token: TokenId) -> Option<u128> {
if <TokenData<T>>::contains_key((self.id, token)) {
Some(1)
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -383,19 +383,6 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- /// Create NFT collection
- ///
- /// `init_collection` will take non-refundable deposit for collection creation.
- ///
- /// - `data`: Contains settings for collection limits and permissions.
- pub fn init_collection(
- owner: T::CrossAccountId,
- payer: T::CrossAccountId,
- data: CreateCollectionData<T::CrossAccountId>,
- ) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(owner, payer, data)
- }
-
/// Destroy NFT collection
///
/// `destroy_collection` will throw error if collection contains any tokens.
runtime/common/config/orml.rsdiffbeforeafterboth--- a/runtime/common/config/orml.rs
+++ b/runtime/common/config/orml.rs
@@ -14,31 +14,21 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use frame_support::{
- parameter_types,
- traits::{Contains, Everything},
-};
+use frame_support::{parameter_types, traits::Everything};
use frame_system::EnsureSigned;
use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key};
-use pallet_foreign_assets::{CurrencyId, NativeCurrency};
+use pallet_foreign_assets::CurrencyIdConvert;
use sp_runtime::traits::Convert;
-use sp_std::{vec, vec::Vec};
use staging_xcm::latest::{Junction::*, Junctions::*, MultiLocation, Weight};
use staging_xcm_executor::XcmExecutor;
use up_common::{
constants::*,
types::{AccountId, Balance},
};
+use up_data_structs::CollectionId;
use crate::{
- runtime_common::config::{
- pallets::TreasuryAccountId,
- substrate::{MaxLocks, MaxReserves},
- xcm::{
- xcm_assets::CurrencyIdConvert, SelfLocation, UniversalLocation, Weigher,
- XcmExecutorConfig,
- },
- },
+ runtime_common::config::xcm::{SelfLocation, UniversalLocation, Weigher, XcmExecutorConfig},
RelayChainBlockNumberProvider, Runtime, RuntimeEvent,
};
@@ -59,29 +49,6 @@
};
}
-parameter_type_with_key! {
- pub ExistentialDeposits: |currency_id: CurrencyId| -> Balance {
- match currency_id {
- CurrencyId::NativeAssetId(symbol) => match symbol {
- NativeCurrency::Here => 0,
- NativeCurrency::Parent=> 0,
- },
- _ => 100_000
- }
- };
-}
-
-pub fn get_all_module_accounts() -> Vec<AccountId> {
- vec![TreasuryAccountId::get()]
-}
-
-pub struct DustRemovalWhitelist;
-impl Contains<AccountId> for DustRemovalWhitelist {
- fn contains(a: &AccountId) -> bool {
- get_all_module_accounts().contains(a)
- }
-}
-
pub struct AccountIdToMultiLocation;
impl Convert<AccountId, MultiLocation> for AccountIdToMultiLocation {
fn convert(account: AccountId) -> MultiLocation {
@@ -91,18 +58,6 @@
})
.into()
}
-}
-
-pub struct CurrencyHooks;
-impl orml_traits::currency::MutationHooks<AccountId, CurrencyId, Balance> for CurrencyHooks {
- type OnDust = orml_tokens::TransferDust<Runtime, TreasuryAccountId>;
- type OnSlash = ();
- type PreTransfer = ();
- type PostTransfer = ();
- type PreDeposit = ();
- type PostDeposit = ();
- type OnNewTokenAccount = ();
- type OnKilledTokenAccount = ();
}
impl orml_vesting::Config for Runtime {
@@ -113,29 +68,13 @@
type WeightInfo = ();
type MaxVestingSchedules = MaxVestingSchedules;
type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
-}
-
-impl orml_tokens::Config for Runtime {
- type RuntimeEvent = RuntimeEvent;
- type Balance = Balance;
- type Amount = Amount;
- type CurrencyId = CurrencyId;
- type WeightInfo = ();
- type ExistentialDeposits = ExistentialDeposits;
- type CurrencyHooks = CurrencyHooks;
- type MaxLocks = MaxLocks;
- type MaxReserves = MaxReserves;
- // TODO: Add all module accounts
- type DustRemovalWhitelist = DustRemovalWhitelist;
- /// The id type for named reserves.
- type ReserveIdentifier = ();
}
impl orml_xtokens::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Balance = Balance;
- type CurrencyId = CurrencyId;
- type CurrencyIdConvert = CurrencyIdConvert;
+ type CurrencyId = CollectionId;
+ type CurrencyIdConvert = CurrencyIdConvert<Self>;
type AccountIdToMultiLocation = AccountIdToMultiLocation;
type SelfLocation = SelfLocation;
type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
runtime/common/config/pallets/foreign_asset.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/foreign_asset.rs
+++ b/runtime/common/config/pallets/foreign_asset.rs
@@ -1,10 +1,14 @@
-use up_common::types::AccountId;
+use frame_support::{parameter_types, PalletId};
+
+use crate::{runtime_common::config::governance, Runtime, RuntimeEvent};
-use crate::{Balances, Runtime, RuntimeEvent};
+parameter_types! {
+ pub ForeignAssetPalletId: PalletId = PalletId(*b"frgnasts");
+}
impl pallet_foreign_assets::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
- type Currency = Balances;
- type RegisterOrigin = frame_system::EnsureRoot<AccountId>;
+ type ForceRegisterOrigin = governance::RootOrTechnicalCommitteeMember;
+ type PalletId = ForeignAssetPalletId;
type WeightInfo = pallet_foreign_assets::weights::SubstrateWeight<Self>;
}
runtime/common/config/xcm.rsdiffbeforeafterboth--- /dev/null
+++ b/runtime/common/config/xcm.rs
@@ -0,0 +1,254 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network 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.
+
+// Unique Network 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 Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+use cumulus_primitives_core::ParaId;
+use frame_support::{
+ parameter_types,
+ traits::{ConstU32, Everything, Get, Nothing, ProcessMessageError},
+};
+use frame_system::EnsureRoot;
+use orml_traits::location::AbsoluteReserveProvider;
+use orml_xcm_support::MultiNativeAsset;
+use pallet_foreign_assets::FreeForAll;
+use pallet_xcm::XcmPassthrough;
+use polkadot_parachain_primitives::primitives::Sibling;
+use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery;
+use sp_std::marker::PhantomData;
+use staging_xcm::{
+ latest::{prelude::*, MultiLocation, Weight},
+ v3::Instruction,
+};
+use staging_xcm_builder::{
+ AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds, ParentIsPreset, RelayChainAsNative,
+ SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
+ SignedToAccountId32, SovereignSignedViaLocation,
+};
+use staging_xcm_executor::{
+ traits::{Properties, ShouldExecute},
+ XcmExecutor,
+};
+use up_common::types::AccountId;
+
+#[cfg(feature = "governance")]
+use crate::runtime_common::config::governance;
+use crate::{
+ xcm_barrier::Barrier, AllPalletsWithSystem, Balances, ForeignAssets, ParachainInfo,
+ ParachainSystem, PolkadotXcm, RelayNetwork, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
+ XcmpQueue,
+};
+
+parameter_types! {
+ pub const RelayLocation: MultiLocation = MultiLocation::parent();
+ pub RelayOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
+ pub UniversalLocation: InteriorMultiLocation = (
+ GlobalConsensus(crate::RelayNetwork::get()),
+ Parachain(ParachainInfo::get().into()),
+ ).into();
+ pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
+
+ // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.
+ pub UnitWeightCost: Weight = Weight::from_parts(1_000_000, 1000); // ?
+ pub const MaxInstructions: u32 = 100;
+}
+
+/// Type for specifying how a `MultiLocation` 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.
+pub type LocationToAccountId = (
+ // The parent (Relay-chain) origin converts to the default `AccountId`.
+ ParentIsPreset<AccountId>,
+ // Sibling parachain origins convert to AccountId via the `ParaId::into`.
+ SiblingParachainConvertsVia<Sibling, AccountId>,
+ // Straight up local `AccountId32` origins just alias directly to `AccountId`.
+ AccountId32Aliases<RelayNetwork, AccountId>,
+);
+
+/// No local origins on this chain are allowed to dispatch XCM sends/executions.
+pub type LocalOriginToLocation = (SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>,);
+
+/// The means for routing XCM messages which are not for local execution into the right message
+/// queues.
+pub type XcmRouter = (
+ // Two routers - use UMP to communicate with the relay chain:
+ cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,
+ // ..and XCMP to communicate with the sibling chains.
+ XcmpQueue,
+);
+
+/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
+/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
+/// biases the kind of local `Origin` it will become.
+pub type XcmOriginToTransactDispatchOrigin = (
+ // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
+ // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
+ // foreign chains who want to have a local sovereign account on this chain which they control.
+ SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
+ // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
+ // recognised.
+ RelayChainAsNative<RelayOrigin, RuntimeOrigin>,
+ // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
+ // recognised.
+ SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
+ // Native signed account converter; this just converts an `AccountId32` origin into a normal
+ // `Origin::Signed` origin of the same 32-byte value.
+ SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
+ // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
+ XcmPassthrough<RuntimeOrigin>,
+);
+
+pub trait TryPass {
+ fn try_pass<Call>(
+ origin: &MultiLocation,
+ message: &mut [Instruction<Call>],
+ ) -> Result<(), ProcessMessageError>;
+}
+
+#[impl_trait_for_tuples::impl_for_tuples(30)]
+impl TryPass for Tuple {
+ fn try_pass<Call>(
+ origin: &MultiLocation,
+ message: &mut [Instruction<Call>],
+ ) -> Result<(), ProcessMessageError> {
+ for_tuples!( #(
+ Tuple::try_pass(origin, message)?;
+ )* );
+
+ Ok(())
+ }
+}
+
+/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.
+/// If it passes the Deny, and matches one of the Allow cases then it is let through.
+pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)
+where
+ Deny: TryPass,
+ Allow: ShouldExecute;
+
+impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>
+where
+ Deny: TryPass,
+ Allow: ShouldExecute,
+{
+ fn should_execute<Call>(
+ origin: &MultiLocation,
+ message: &mut [Instruction<Call>],
+ max_weight: Weight,
+ properties: &mut Properties,
+ ) -> Result<(), ProcessMessageError> {
+ Deny::try_pass(origin, message)?;
+ Allow::should_execute(origin, message, max_weight, properties)
+ }
+}
+
+pub type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
+
+pub type IsReserve = MultiNativeAsset<AbsoluteReserveProvider>;
+
+pub type Trader = FreeForAll;
+
+pub struct XcmExecutorConfig<T>(PhantomData<T>);
+impl<T> staging_xcm_executor::Config for XcmExecutorConfig<T>
+where
+ T: pallet_configuration::Config,
+{
+ type RuntimeCall = RuntimeCall;
+ type XcmSender = XcmRouter;
+ // How to withdraw and deposit an asset.
+ type AssetTransactor = ForeignAssets;
+ type OriginConverter = XcmOriginToTransactDispatchOrigin;
+ type IsReserve = IsReserve;
+ type IsTeleporter = (); // Teleportation is disabled
+ type UniversalLocation = UniversalLocation;
+ type Barrier = Barrier;
+ type Weigher = Weigher;
+ type Trader = Trader;
+ type ResponseHandler = PolkadotXcm;
+ type SubscriptionService = PolkadotXcm;
+ type PalletInstancesInfo = AllPalletsWithSystem;
+ type MaxAssetsIntoHolding = ConstU32<8>;
+
+ type AssetTrap = PolkadotXcm;
+ type AssetClaims = PolkadotXcm;
+ type AssetLocker = ();
+ type AssetExchanger = ();
+ type FeeManager = ();
+ type MessageExporter = ();
+ type UniversalAliases = Nothing;
+ type CallDispatcher = RuntimeCall;
+ type SafeCallFilter = Nothing;
+ type Aliasers = Nothing;
+}
+
+#[cfg(feature = "runtime-benchmarks")]
+parameter_types! {
+ pub ReachableDest: Option<MultiLocation> = Some(Parent.into());
+}
+
+impl pallet_xcm::Config for Runtime {
+ type RuntimeEvent = RuntimeEvent;
+ type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, ()>;
+ type XcmRouter = XcmRouter;
+ type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
+ type XcmExecuteFilter = Everything;
+ type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
+ type XcmTeleportFilter = Everything;
+ type XcmReserveTransferFilter = Everything;
+ type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
+ type RuntimeOrigin = RuntimeOrigin;
+ type RuntimeCall = RuntimeCall;
+ const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
+ type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
+ type UniversalLocation = UniversalLocation;
+ type Currency = Balances;
+ type CurrencyMatcher = ();
+ type TrustedLockers = ();
+ type SovereignAccountOf = LocationToAccountId;
+ type MaxLockers = ConstU32<8>;
+ type WeightInfo = crate::weights::xcm::SubstrateWeight<Runtime>;
+ type AdminOrigin = EnsureRoot<AccountId>;
+ type MaxRemoteLockConsumers = ConstU32<0>;
+ type RemoteLockConsumerIdentifier = ();
+ #[cfg(feature = "runtime-benchmarks")]
+ type ReachableDest = ReachableDest;
+}
+
+impl cumulus_pallet_xcm::Config for Runtime {
+ type RuntimeEvent = RuntimeEvent;
+ type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
+}
+impl cumulus_pallet_xcmp_queue::Config for Runtime {
+ type WeightInfo = ();
+ type RuntimeEvent = RuntimeEvent;
+ type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
+ type ChannelInfo = ParachainSystem;
+ type VersionWrapper = PolkadotXcm;
+ type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
+
+ #[cfg(feature = "governance")]
+ type ControllerOrigin = governance::RootOrTechnicalCommitteeMember;
+
+ #[cfg(not(feature = "governance"))]
+ type ControllerOrigin = frame_system::EnsureRoot<AccountId>;
+
+ type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
+ type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
+}
+
+impl cumulus_pallet_dmp_queue::Config for Runtime {
+ type RuntimeEvent = RuntimeEvent;
+ type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
+ type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
+}
runtime/common/config/xcm/foreignassets.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/foreignassets.rs
+++ /dev/null
@@ -1,205 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network 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.
-
-// Unique Network 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 Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-use frame_support::{parameter_types, traits::Get};
-use orml_traits::location::AbsoluteReserveProvider;
-use orml_xcm_support::MultiNativeAsset;
-use pallet_foreign_assets::{
- AssetId, AssetIdMapping, CurrencyId, ForeignAssetId, FreeForAll, NativeCurrency, TryAsForeign,
- XcmForeignAssetIdMapping,
-};
-use sp_runtime::traits::{Convert, MaybeEquivalence};
-use sp_std::marker::PhantomData;
-use staging_xcm::latest::{prelude::*, MultiAsset, MultiLocation};
-use staging_xcm_builder::{ConvertedConcreteId, FungiblesAdapter, NoChecking};
-use staging_xcm_executor::traits::{JustTry, TransactAsset};
-use up_common::types::{AccountId, Balance};
-
-use super::{LocationToAccountId, RelayLocation};
-use crate::{Balances, ForeignAssets, ParachainInfo, PolkadotXcm, Runtime};
-
-parameter_types! {
- pub CheckingAccount: AccountId = PolkadotXcm::check_account();
-}
-
-pub struct AsInnerId<ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
-impl<ConvertAssetId: MaybeEquivalence<AssetId, AssetId>> MaybeEquivalence<MultiLocation, AssetId>
- for AsInnerId<ConvertAssetId>
-{
- fn convert(id: &MultiLocation) -> Option<AssetId> {
- log::trace!(
- target: "xcm::AsInnerId::Convert",
- "AsInnerId {:?}",
- id
- );
-
- let parent = MultiLocation::parent();
- let here = MultiLocation::here();
- let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
-
- if *id == parent {
- return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent));
- }
-
- if *id == here || *id == self_location {
- return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here));
- }
-
- match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {
- Some(AssetId::ForeignAssetId(foreign_asset_id)) => {
- ConvertAssetId::convert(&AssetId::ForeignAssetId(foreign_asset_id))
- }
- _ => None,
- }
- }
-
- fn convert_back(asset_id: &AssetId) -> Option<MultiLocation> {
- log::trace!(
- target: "xcm::AsInnerId::Reverse",
- "AsInnerId",
- );
-
- let parent_id =
- ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent)).unwrap();
- let here_id =
- ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here)).unwrap();
-
- if *asset_id == parent_id {
- return Some(MultiLocation::parent());
- }
-
- if *asset_id == here_id {
- return Some(MultiLocation::new(
- 1,
- X1(Parachain(ParachainInfo::get().into())),
- ));
- }
-
- let fid = <AssetId as TryAsForeign<AssetId, ForeignAssetId>>::try_as_foreign(*asset_id)?;
- XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid)
- }
-}
-
-/// Means for transacting assets besides the native currency on this chain.
-pub type FungiblesTransactor = FungiblesAdapter<
- // Use this fungibles implementation:
- ForeignAssets,
- // Use this currency when it is a fungible asset matching the given location or name:
- ConvertedConcreteId<AssetId, Balance, AsInnerId<JustTry>, JustTry>,
- // Convert an XCM MultiLocation into a local account id:
- LocationToAccountId,
- // Our chain's account ID type (we can't get away without mentioning it explicitly):
- AccountId,
- // No Checking for teleported assets since we disallow teleports at all.
- NoChecking,
- // The account to use for tracking teleports.
- CheckingAccount,
->;
-
-/// Means for transacting assets on this chain.
-pub struct AssetTransactor;
-impl TransactAsset for AssetTransactor {
- fn can_check_in(
- _origin: &MultiLocation,
- _what: &MultiAsset,
- _context: &XcmContext,
- ) -> XcmResult {
- Err(XcmError::Unimplemented)
- }
-
- fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
-
- fn can_check_out(
- _dest: &MultiLocation,
- _what: &MultiAsset,
- _context: &XcmContext,
- ) -> XcmResult {
- Err(XcmError::Unimplemented)
- }
-
- fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {}
-
- fn deposit_asset(
- what: &MultiAsset,
- who: &MultiLocation,
- context: Option<&XcmContext>,
- ) -> XcmResult {
- FungiblesTransactor::deposit_asset(what, who, context)
- }
-
- fn withdraw_asset(
- what: &MultiAsset,
- who: &MultiLocation,
- maybe_context: Option<&XcmContext>,
- ) -> Result<staging_xcm_executor::Assets, XcmError> {
- FungiblesTransactor::withdraw_asset(what, who, maybe_context)
- }
-
- fn internal_transfer_asset(
- what: &MultiAsset,
- from: &MultiLocation,
- to: &MultiLocation,
- context: &XcmContext,
- ) -> Result<staging_xcm_executor::Assets, XcmError> {
- FungiblesTransactor::internal_transfer_asset(what, from, to, context)
- }
-}
-
-pub type IsReserve = MultiNativeAsset<AbsoluteReserveProvider>;
-
-pub type Trader<T> = FreeForAll<
- pallet_configuration::WeightToFee<T, Balance>,
- RelayLocation,
- AccountId,
- Balances,
- (),
->;
-
-pub struct CurrencyIdConvert;
-impl Convert<AssetId, Option<MultiLocation>> for CurrencyIdConvert {
- fn convert(id: AssetId) -> Option<MultiLocation> {
- match id {
- AssetId::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
- 1,
- X1(Parachain(ParachainInfo::get().into())),
- )),
- AssetId::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
- AssetId::ForeignAssetId(foreign_asset_id) => {
- XcmForeignAssetIdMapping::<Runtime>::get_multi_location(foreign_asset_id)
- }
- }
- }
-}
-
-impl Convert<MultiLocation, Option<CurrencyId>> for CurrencyIdConvert {
- fn convert(location: MultiLocation) -> Option<CurrencyId> {
- if location == MultiLocation::here()
- || location == MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())))
- {
- return Some(AssetId::NativeAssetId(NativeCurrency::Here));
- }
-
- if location == MultiLocation::parent() {
- return Some(AssetId::NativeAssetId(NativeCurrency::Parent));
- }
-
- if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {
- return Some(currency_id);
- }
-
- None
- }
-}
runtime/common/config/xcm/mod.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/mod.rs
+++ /dev/null
@@ -1,259 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network 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.
-
-// Unique Network 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 Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-use cumulus_primitives_core::ParaId;
-use frame_support::{
- parameter_types,
- traits::{ConstU32, Everything, Get, Nothing, ProcessMessageError},
-};
-use frame_system::EnsureRoot;
-use pallet_xcm::XcmPassthrough;
-use polkadot_parachain_primitives::primitives::Sibling;
-use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery;
-use sp_std::marker::PhantomData;
-use staging_xcm::{
- latest::{prelude::*, MultiLocation, Weight},
- v3::Instruction,
-};
-use staging_xcm_builder::{
- AccountId32Aliases, EnsureXcmOrigin, FixedWeightBounds, ParentIsPreset, RelayChainAsNative,
- SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,
- SignedToAccountId32, SovereignSignedViaLocation,
-};
-use staging_xcm_executor::{
- traits::{Properties, ShouldExecute},
- XcmExecutor,
-};
-use up_common::types::AccountId;
-
-use crate::{
- xcm_barrier::Barrier, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem,
- PolkadotXcm, RelayNetwork, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, XcmpQueue,
-};
-
-#[cfg(feature = "foreign-assets")]
-pub mod foreignassets;
-
-#[cfg(not(feature = "foreign-assets"))]
-pub mod nativeassets;
-
-#[cfg(feature = "foreign-assets")]
-pub use foreignassets as xcm_assets;
-#[cfg(not(feature = "foreign-assets"))]
-pub use nativeassets as xcm_assets;
-use xcm_assets::{AssetTransactor, IsReserve, Trader};
-
-#[cfg(feature = "governance")]
-use crate::runtime_common::config::governance;
-
-parameter_types! {
- pub const RelayLocation: MultiLocation = MultiLocation::parent();
- pub RelayOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
- pub UniversalLocation: InteriorMultiLocation = (
- GlobalConsensus(crate::RelayNetwork::get()),
- Parachain(ParachainInfo::get().into()),
- ).into();
- pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
-
- // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.
- pub UnitWeightCost: Weight = Weight::from_parts(1_000_000, 1000); // ?
- pub const MaxInstructions: u32 = 100;
-}
-
-/// Type for specifying how a `MultiLocation` 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.
-pub type LocationToAccountId = (
- // The parent (Relay-chain) origin converts to the default `AccountId`.
- ParentIsPreset<AccountId>,
- // Sibling parachain origins convert to AccountId via the `ParaId::into`.
- SiblingParachainConvertsVia<Sibling, AccountId>,
- // Straight up local `AccountId32` origins just alias directly to `AccountId`.
- AccountId32Aliases<RelayNetwork, AccountId>,
-);
-
-/// No local origins on this chain are allowed to dispatch XCM sends/executions.
-pub type LocalOriginToLocation = (SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>,);
-
-/// The means for routing XCM messages which are not for local execution into the right message
-/// queues.
-pub type XcmRouter = (
- // Two routers - use UMP to communicate with the relay chain:
- cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,
- // ..and XCMP to communicate with the sibling chains.
- XcmpQueue,
-);
-
-/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
-/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
-/// biases the kind of local `Origin` it will become.
-pub type XcmOriginToTransactDispatchOrigin = (
- // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
- // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
- // foreign chains who want to have a local sovereign account on this chain which they control.
- SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
- // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
- // recognised.
- RelayChainAsNative<RelayOrigin, RuntimeOrigin>,
- // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
- // recognised.
- SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
- // Native signed account converter; this just converts an `AccountId32` origin into a normal
- // `Origin::Signed` origin of the same 32-byte value.
- SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
- // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
- XcmPassthrough<RuntimeOrigin>,
-);
-
-pub trait TryPass {
- fn try_pass<Call>(
- origin: &MultiLocation,
- message: &mut [Instruction<Call>],
- ) -> Result<(), ProcessMessageError>;
-}
-
-#[impl_trait_for_tuples::impl_for_tuples(30)]
-impl TryPass for Tuple {
- fn try_pass<Call>(
- origin: &MultiLocation,
- message: &mut [Instruction<Call>],
- ) -> Result<(), ProcessMessageError> {
- for_tuples!( #(
- Tuple::try_pass(origin, message)?;
- )* );
-
- Ok(())
- }
-}
-
-/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.
-/// If it passes the Deny, and matches one of the Allow cases then it is let through.
-pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)
-where
- Deny: TryPass,
- Allow: ShouldExecute;
-
-impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>
-where
- Deny: TryPass,
- Allow: ShouldExecute,
-{
- fn should_execute<Call>(
- origin: &MultiLocation,
- message: &mut [Instruction<Call>],
- max_weight: Weight,
- properties: &mut Properties,
- ) -> Result<(), ProcessMessageError> {
- Deny::try_pass(origin, message)?;
- Allow::should_execute(origin, message, max_weight, properties)
- }
-}
-
-pub type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
-
-pub struct XcmExecutorConfig<T>(PhantomData<T>);
-impl<T> staging_xcm_executor::Config for XcmExecutorConfig<T>
-where
- T: pallet_configuration::Config,
-{
- type RuntimeCall = RuntimeCall;
- type XcmSender = XcmRouter;
- // How to withdraw and deposit an asset.
- type AssetTransactor = AssetTransactor;
- type OriginConverter = XcmOriginToTransactDispatchOrigin;
- type IsReserve = IsReserve;
- type IsTeleporter = (); // Teleportation is disabled
- type UniversalLocation = UniversalLocation;
- type Barrier = Barrier;
- type Weigher = Weigher;
- type Trader = Trader<T>;
- type ResponseHandler = PolkadotXcm;
- type SubscriptionService = PolkadotXcm;
- type PalletInstancesInfo = AllPalletsWithSystem;
- type MaxAssetsIntoHolding = ConstU32<8>;
-
- type AssetTrap = PolkadotXcm;
- type AssetClaims = PolkadotXcm;
- type AssetLocker = ();
- type AssetExchanger = ();
- type FeeManager = ();
- type MessageExporter = ();
- type UniversalAliases = Nothing;
- type CallDispatcher = RuntimeCall;
- type SafeCallFilter = Nothing;
- type Aliasers = Nothing;
-}
-
-#[cfg(feature = "runtime-benchmarks")]
-parameter_types! {
- pub ReachableDest: Option<MultiLocation> = Some(Parent.into());
-}
-
-impl pallet_xcm::Config for Runtime {
- type RuntimeEvent = RuntimeEvent;
- type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, ()>;
- type XcmRouter = XcmRouter;
- type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
- type XcmExecuteFilter = Everything;
- type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
- type XcmTeleportFilter = Everything;
- type XcmReserveTransferFilter = Everything;
- type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
- type RuntimeOrigin = RuntimeOrigin;
- type RuntimeCall = RuntimeCall;
- const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
- type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
- type UniversalLocation = UniversalLocation;
- type Currency = Balances;
- type CurrencyMatcher = ();
- type TrustedLockers = ();
- type SovereignAccountOf = LocationToAccountId;
- type MaxLockers = ConstU32<8>;
- type WeightInfo = crate::weights::xcm::SubstrateWeight<Runtime>;
- type AdminOrigin = EnsureRoot<AccountId>;
- type MaxRemoteLockConsumers = ConstU32<0>;
- type RemoteLockConsumerIdentifier = ();
- #[cfg(feature = "runtime-benchmarks")]
- type ReachableDest = ReachableDest;
-}
-
-impl cumulus_pallet_xcm::Config for Runtime {
- type RuntimeEvent = RuntimeEvent;
- type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
-}
-impl cumulus_pallet_xcmp_queue::Config for Runtime {
- type WeightInfo = ();
- type RuntimeEvent = RuntimeEvent;
- type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
- type ChannelInfo = ParachainSystem;
- type VersionWrapper = PolkadotXcm;
- type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
-
- #[cfg(feature = "governance")]
- type ControllerOrigin = governance::RootOrTechnicalCommitteeMember;
-
- #[cfg(not(feature = "governance"))]
- type ControllerOrigin = frame_system::EnsureRoot<AccountId>;
-
- type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
- type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
-}
-
-impl cumulus_pallet_dmp_queue::Config for Runtime {
- type RuntimeEvent = RuntimeEvent;
- type XcmExecutor = XcmExecutor<XcmExecutorConfig<Self>>;
- type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
-}
runtime/common/config/xcm/nativeassets.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/nativeassets.rs
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network 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.
-
-// Unique Network 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 Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-use cumulus_primitives_core::XcmContext;
-use frame_support::{
- traits::{tokens::currency::Currency as CurrencyT, Get, OnUnbalanced as OnUnbalancedT},
- weights::WeightToFeePolynomial,
-};
-use pallet_foreign_assets::{AssetIds, NativeCurrency};
-use sp_runtime::traits::{CheckedConversion, Convert, Zero};
-use sp_std::marker::PhantomData;
-use staging_xcm::latest::{
- AssetId::Concrete, Error as XcmError, Fungibility::Fungible as XcmFungible, Junction::*,
- Junctions::*, MultiAsset, MultiLocation, Weight,
-};
-use staging_xcm_builder::{CurrencyAdapter, NativeAsset};
-use staging_xcm_executor::{
- traits::{MatchesFungible, WeightTrader},
- Assets,
-};
-use up_common::types::{AccountId, Balance};
-
-use super::{LocationToAccountId, RelayLocation};
-use crate::{Balances, ParachainInfo};
-
-pub struct OnlySelfCurrency;
-impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {
- fn matches_fungible(a: &MultiAsset) -> Option<B> {
- let paraid = Parachain(ParachainInfo::parachain_id().into());
- match (&a.id, &a.fun) {
- (
- Concrete(MultiLocation {
- parents: 1,
- interior: X1(loc),
- }),
- XcmFungible(ref amount),
- ) if paraid == *loc => CheckedConversion::checked_from(*amount),
- (
- Concrete(MultiLocation {
- parents: 0,
- interior: Here,
- }),
- XcmFungible(ref amount),
- ) => CheckedConversion::checked_from(*amount),
- _ => None,
- }
- }
-}
-
-/// Means for transacting assets on this chain.
-pub type LocalAssetTransactor = CurrencyAdapter<
- // Use this currency:
- Balances,
- // Use this currency when it is a fungible asset matching the given location or name:
- OnlySelfCurrency,
- // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:
- LocationToAccountId,
- // Our chain's account ID type (we can't get away without mentioning it explicitly):
- AccountId,
- // We don't track any teleports.
- (),
->;
-
-pub type AssetTransactor = LocalAssetTransactor;
-
-pub type IsReserve = NativeAsset;
-
-pub struct UsingOnlySelfCurrencyComponents<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
->(
- Weight,
- Currency::Balance,
- PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,
-);
-impl<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
- > WeightTrader
- for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
-{
- fn new() -> Self {
- // FIXME: benchmark
- Self(Weight::from_parts(0, 0), Zero::zero(), PhantomData)
- }
-
- fn buy_weight(
- &mut self,
- _weight: Weight,
- payment: Assets,
- _xcm: &XcmContext,
- ) -> Result<Assets, XcmError> {
- Ok(payment)
- }
-}
-impl<
- WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,
- AssetId: Get<MultiLocation>,
- AccountId,
- Currency: CurrencyT<AccountId>,
- OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,
- > Drop
- for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>
-{
- fn drop(&mut self) {
- OnUnbalanced::on_unbalanced(Currency::issue(self.1));
- }
-}
-
-pub type Trader<T> = UsingOnlySelfCurrencyComponents<
- pallet_configuration::WeightToFee<T, Balance>,
- RelayLocation,
- AccountId,
- Balances,
- (),
->;
-
-pub struct CurrencyIdConvert;
-impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
- fn convert(id: AssetIds) -> Option<MultiLocation> {
- match id {
- AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
- 1,
- X1(Parachain(ParachainInfo::get().into())),
- )),
- _ => None,
- }
- }
-}
runtime/common/construct_runtime.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime.rs
+++ b/runtime/common/construct_runtime.rs
@@ -47,7 +47,7 @@
Vesting: orml_vesting = 37,
XTokens: orml_xtokens = 38,
- Tokens: orml_tokens = 39,
+ // [REMOVED] Tokens: orml_tokens = 39,
// Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,
#[cfg(feature = "governance")]
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -17,11 +17,9 @@
use frame_support::{dispatch::DispatchResult, ensure, fail};
use pallet_balances_adapter::NativeFungibleHandle;
pub use pallet_common::dispatch::CollectionDispatch;
-#[cfg(not(feature = "refungible"))]
-use pallet_common::unsupported;
use pallet_common::{
- erc::CommonEvmHandler, eth::map_eth_to_id, CollectionById, CollectionHandle,
- CommonCollectionOperations,
+ erc::CommonEvmHandler, eth::map_eth_to_id, unsupported, CollectionById, CollectionHandle,
+ CommonCollectionOperations, Pallet as PalletCommon,
};
use pallet_evm::{PrecompileHandle, PrecompileResult};
use pallet_fungible::{FungibleHandle, Pallet as PalletFungible};
@@ -73,24 +71,42 @@
payer: T::CrossAccountId,
data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
- let id = match data.mode {
- CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, payer, data)?,
+ match data.mode {
CollectionMode::Fungible(decimal_points) => {
// check params
ensure!(
decimal_points <= MAX_DECIMAL_POINTS,
pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
);
- <PalletFungible<T>>::init_collection(sender, payer, data)?
}
- #[cfg(feature = "refungible")]
- CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, payer, data)?,
+ #[cfg(not(feature = "refungible"))]
+ CollectionMode::ReFungible => return unsupported!(T),
+
+ _ => {}
+ };
+
+ <PalletCommon<T>>::init_collection(sender, payer, data)
+ }
+
+ fn create_foreign(
+ sender: <T>::CrossAccountId,
+ data: CreateCollectionData<<T>::CrossAccountId>,
+ ) -> Result<CollectionId, DispatchError> {
+ match data.mode {
+ CollectionMode::Fungible(decimal_points) => {
+ // check params
+ ensure!(
+ decimal_points <= MAX_DECIMAL_POINTS,
+ pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
+ );
+ }
- #[cfg(not(feature = "refungible"))]
CollectionMode::ReFungible => return unsupported!(T),
+ _ => {}
};
- Ok(id)
+
+ <PalletCommon<T>>::init_foreign_collection(sender, data)
}
fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult {