git.delta.rocks / unique-network / refs/commits / 538e9236a6e0

difftreelog

wip checkpoint. Opal builds.

Ilja Khabarov2022-08-19parent: #83658e7.patch.diff
in: master

8 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5190,7 +5190,10 @@
  "frame-try-runtime",
  "hex-literal",
  "log",
+ "orml-tokens",
+ "orml-traits",
  "orml-vesting",
+ "orml-xtokens",
  "pallet-aura",
  "pallet-balances",
  "pallet-base-fee",
@@ -5202,6 +5205,7 @@
  "pallet-evm-contract-helpers",
  "pallet-evm-migration",
  "pallet-evm-transaction-payment",
+ "pallet-foreing-assets",
  "pallet-fungible",
  "pallet-inflation",
  "pallet-nonfungible",
@@ -5307,6 +5311,53 @@
 ]
 
 [[package]]
+name = "orml-tokens"
+version = "0.4.1-dev"
+source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.27#377213f750755cc48e80a3131eaae63b5eda8362"
+dependencies = [
+ "frame-support",
+ "frame-system",
+ "orml-traits",
+ "parity-scale-codec 3.1.5",
+ "scale-info",
+ "serde",
+ "sp-runtime",
+ "sp-std",
+]
+
+[[package]]
+name = "orml-traits"
+version = "0.4.1-dev"
+source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.27#377213f750755cc48e80a3131eaae63b5eda8362"
+dependencies = [
+ "frame-support",
+ "impl-trait-for-tuples",
+ "num-traits",
+ "orml-utilities",
+ "parity-scale-codec 3.1.5",
+ "scale-info",
+ "serde",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+ "xcm",
+]
+
+[[package]]
+name = "orml-utilities"
+version = "0.4.1-dev"
+source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.27#377213f750755cc48e80a3131eaae63b5eda8362"
+dependencies = [
+ "frame-support",
+ "parity-scale-codec 3.1.5",
+ "scale-info",
+ "serde",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+]
+
+[[package]]
 name = "orml-vesting"
 version = "0.4.1-dev"
 source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.27#377213f750755cc48e80a3131eaae63b5eda8362"
@@ -5322,6 +5373,41 @@
 ]
 
 [[package]]
+name = "orml-xcm-support"
+version = "0.4.1-dev"
+source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.27#377213f750755cc48e80a3131eaae63b5eda8362"
+dependencies = [
+ "frame-support",
+ "orml-traits",
+ "parity-scale-codec 3.1.5",
+ "sp-runtime",
+ "sp-std",
+ "xcm",
+ "xcm-executor",
+]
+
+[[package]]
+name = "orml-xtokens"
+version = "0.4.1-dev"
+source = "git+https://github.com/open-web3-stack/open-runtime-module-library?branch=polkadot-v0.9.27#377213f750755cc48e80a3131eaae63b5eda8362"
+dependencies = [
+ "cumulus-primitives-core",
+ "frame-support",
+ "frame-system",
+ "orml-traits",
+ "orml-xcm-support",
+ "pallet-xcm",
+ "parity-scale-codec 3.1.5",
+ "scale-info",
+ "serde",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+ "xcm",
+ "xcm-executor",
+]
+
+[[package]]
 name = "os_str_bytes"
 version = "6.3.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -5789,6 +5875,33 @@
 ]
 
 [[package]]
+name = "pallet-foreing-assets"
+version = "0.1.0"
+dependencies = [
+ "frame-support",
+ "frame-system",
+ "hex",
+ "log",
+ "orml-tokens",
+ "pallet-balances",
+ "pallet-common",
+ "pallet-fungible",
+ "pallet-timestamp",
+ "parity-scale-codec 3.1.5",
+ "scale-info",
+ "serde",
+ "serde_json",
+ "sp-core",
+ "sp-io",
+ "sp-runtime",
+ "sp-std",
+ "up-data-structs",
+ "xcm",
+ "xcm-builder",
+ "xcm-executor",
+]
+
+[[package]]
 name = "pallet-fungible"
 version = "0.1.3"
 dependencies = [
@@ -12130,7 +12243,7 @@
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675"
 dependencies = [
- "cfg-if 1.0.0",
+ "cfg-if 0.1.10",
  "digest 0.10.3",
  "rand 0.8.5",
  "static_assertions",
@@ -12473,7 +12586,7 @@
 
 [[package]]
 name = "up-common"
-version = "0.9.25"
+version = "0.9.27"
 dependencies = [
  "fp-rpc",
  "frame-support",
modifiedpallets/foreing-assets/Cargo.tomldiffbeforeafterboth
--- a/pallets/foreing-assets/Cargo.toml
+++ b/pallets/foreing-assets/Cargo.toml
@@ -9,26 +9,29 @@
 serde = { version = "1.0.136", optional = true }
 scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
 codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false }
-sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false }
-sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false  }
-frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false }
-frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false }
+sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false }
+sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false  }
+frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false }
+frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false }
 up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
-pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24", default-features = false }
+pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27", default-features = false }
 pallet-common = { default-features = false, path = '../common' }
 pallet-fungible = { default-features = false, path = '../fungible' }
-xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.24", default-features = false }
-xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.24", default-features = false }
-xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.24", default-features = false }
-orml-tokens = { git = 'https://github.com/UniqueNetwork/open-runtime-module-library', branch = 'unique-polkadot-v0.9.24', version = "0.4.1-dev", default-features = false }
+xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27", default-features = false }
+xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27", default-features = false }
+xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.27", default-features = false }
+#orml-tokens = { git = 'https://github.com/UniqueNetwork/open-runtime-module-library', branch = 'unique-polkadot-v0.9.24', version = "0.4.1-dev", default-features = false }
+orml-tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", branch = "polkadot-v0.9.27", version = "0.4.1-dev", default-features = false }
+#git = "https://github.com/open-web3-stack/open-runtime-module-library"
+#branch = "polkadot-v0.9.27"
 
 [dev-dependencies]
 serde_json = "1.0.68"
 hex = { version = "0.4" }
-sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
-sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
-pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
-pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
+pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.27" }
 
 [features]
 default = ["std"]
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
before · pallets/fungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//!	- [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::{ensure};84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86	AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,87	budget::Budget,88};89use pallet_common::{90	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91	eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115	use up_data_structs::CollectionId;116	use super::weights::WeightInfo;117118	#[pallet::error]119	pub enum Error<T> {120		/// Not Fungible item data used to mint in Fungible collection.121		NotFungibleDataUsedToMintFungibleCollectionToken,122		/// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.123		FungibleItemsHaveNoId,124		/// Tried to set data for fungible item.125		FungibleItemsDontHaveData,126		/// Fungible token does not support nesting.127		FungibleDisallowsNesting,128		/// Setting item properties is not allowed.129		SettingPropertiesNotAllowed,130	}131132	#[pallet::config]133	pub trait Config:134		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config135	{136		type WeightInfo: WeightInfo;137	}138139	#[pallet::pallet]140	#[pallet::generate_store(pub(super) trait Store)]141	pub struct Pallet<T>(_);142143	/// Total amount of fungible tokens inside a collection.144	#[pallet::storage]145	pub type TotalSupply<T: Config> =146		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;147148	/// Amount of tokens owned by an account inside a collection.149	#[pallet::storage]150	pub type Balance<T: Config> = StorageNMap<151		Key = (152			Key<Twox64Concat, CollectionId>,153			Key<Blake2_128Concat, T::CrossAccountId>,154		),155		Value = u128,156		QueryKind = ValueQuery,157	>;158159	/// Storage for assets delegated to a limited extent to other users.160	#[pallet::storage]161	pub type Allowance<T: Config> = StorageNMap<162		Key = (163			Key<Twox64Concat, CollectionId>,164			Key<Blake2_128, T::CrossAccountId>,165			Key<Blake2_128Concat, T::CrossAccountId>,166		),167		Value = u128,168		QueryKind = ValueQuery,169	>;170}171172/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.173/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].174pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);175176/// Implementation of methods required for dispatching during runtime.177impl<T: Config> FungibleHandle<T> {178	/// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].179	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {180		Self(inner)181	}182183	/// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].184	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {185		self.0186	}187	/// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].188	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {189		&mut self.0190	}191}192impl<T: Config> WithRecorder<T> for FungibleHandle<T> {193	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {194		self.0.recorder()195	}196	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {197		self.0.into_recorder()198	}199}200impl<T: Config> Deref for FungibleHandle<T> {201	type Target = pallet_common::CollectionHandle<T>;202203	fn deref(&self) -> &Self::Target {204		&self.0205	}206}207208/// Pallet implementation for fungible assets209impl<T: Config> Pallet<T> {210	/// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.211	pub fn init_collection(212		owner: T::CrossAccountId,213		data: CreateCollectionData<T::AccountId>,214	) -> Result<CollectionId, DispatchError> {215		<PalletCommon<T>>::init_collection(owner, data, false)216	}217218	/// Destroys a collection.219	pub fn destroy_collection(220		collection: FungibleHandle<T>,221		sender: &T::CrossAccountId,222	) -> DispatchResult {223		let id = collection.id;224225		if Self::collection_has_tokens(id) {226			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());227		}228229		// =========230231		PalletCommon::destroy_collection(collection.0, sender)?;232233		<TotalSupply<T>>::remove(id);234		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);235		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);236		Ok(())237	}238239	///Checks if collection has tokens. Return `true` if it has.240	fn collection_has_tokens(collection_id: CollectionId) -> bool {241		<TotalSupply<T>>::get(collection_id) != 0242	}243244	/// Burns the specified amount of the token. If the token balance245	/// or total supply is less than the given value,246	/// it will return [DispatchError].247	pub fn burn(248		collection: &FungibleHandle<T>,249		owner: &T::CrossAccountId,250		amount: u128,251	) -> DispatchResult {252		let total_supply = <TotalSupply<T>>::get(collection.id)253			.checked_sub(amount)254			.ok_or(<CommonError<T>>::TokenValueTooLow)?;255256		let balance = <Balance<T>>::get((collection.id, owner))257			.checked_sub(amount)258			.ok_or(<CommonError<T>>::TokenValueTooLow)?;259260		if collection.permissions.access() == AccessMode::AllowList {261			collection.check_allowlist(owner)?;262		}263264		// =========265266		if balance == 0 {267			<Balance<T>>::remove((collection.id, owner));268			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());269		} else {270			<Balance<T>>::insert((collection.id, owner), balance);271		}272		<TotalSupply<T>>::insert(collection.id, total_supply);273274		<PalletEvm<T>>::deposit_log(275			ERC20Events::Transfer {276				from: *owner.as_eth(),277				to: H160::default(),278				value: amount.into(),279			}280			.to_log(collection_id_to_address(collection.id)),281		);282		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(283			collection.id,284			TokenId::default(),285			owner.clone(),286			amount,287		));288		Ok(())289	}290291	/// Transfers the specified amount of tokens. Will check that292	/// the transfer is allowed for the token.293	///294	/// - `from`: Owner of tokens to transfer.295	/// - `to`: Recepient of transfered tokens.296	/// - `amount`: Amount of tokens to transfer.297	/// - `collection`: Collection that contains the token298	pub fn transfer(299		collection: &FungibleHandle<T>,300		from: &T::CrossAccountId,301		to: &T::CrossAccountId,302		amount: u128,303		nesting_budget: &dyn Budget,304	) -> DispatchResult {305		ensure!(306			collection.limits.transfers_enabled(),307			<CommonError<T>>::TransferNotAllowed,308		);309310		if collection.permissions.access() == AccessMode::AllowList {311			collection.check_allowlist(from)?;312			collection.check_allowlist(to)?;313		}314		<PalletCommon<T>>::ensure_correct_receiver(to)?;315316		let balance_from = <Balance<T>>::get((collection.id, from))317			.checked_sub(amount)318			.ok_or(<CommonError<T>>::TokenValueTooLow)?;319		let balance_to = if from != to {320			Some(321				<Balance<T>>::get((collection.id, to))322					.checked_add(amount)323					.ok_or(ArithmeticError::Overflow)?,324			)325		} else {326			None327		};328329		// =========330331		<PalletStructure<T>>::nest_if_sent_to_token(332			from.clone(),333			to,334			collection.id,335			TokenId::default(),336			nesting_budget,337		)?;338339		if let Some(balance_to) = balance_to {340			// from != to341			if balance_from == 0 {342				<Balance<T>>::remove((collection.id, from));343				<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());344			} else {345				<Balance<T>>::insert((collection.id, from), balance_from);346			}347			<Balance<T>>::insert((collection.id, to), balance_to);348		}349350		<PalletEvm<T>>::deposit_log(351			ERC20Events::Transfer {352				from: *from.as_eth(),353				to: *to.as_eth(),354				value: amount.into(),355			}356			.to_log(collection_id_to_address(collection.id)),357		);358		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(359			collection.id,360			TokenId::default(),361			from.clone(),362			to.clone(),363			amount,364		));365		Ok(())366	}367368	/// Minting tokens for multiple IDs.369	/// See [`create_item`][`Pallet::create_item`] for more details.370	pub fn create_multiple_items(371		collection: &FungibleHandle<T>,372		sender: &T::CrossAccountId,373		data: BTreeMap<T::CrossAccountId, u128>,374		nesting_budget: &dyn Budget,375	) -> DispatchResult {376		if !collection.is_owner_or_admin(sender) {377			ensure!(378				collection.permissions.mint_mode(),379				<CommonError<T>>::PublicMintingNotAllowed380			);381			collection.check_allowlist(sender)?;382383			for (owner, _) in data.iter() {384				collection.check_allowlist(owner)?;385			}386		}387388		let total_supply = data389			.iter()390			.map(|(_, v)| *v)391			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {392				acc.checked_add(v)393			})394			.ok_or(ArithmeticError::Overflow)?;395396		for (to, _) in data.iter() {397			<PalletStructure<T>>::check_nesting(398				sender.clone(),399				to,400				collection.id,401				TokenId::default(),402				nesting_budget,403			)?;404		}405406		let updated_balances = data407			.into_iter()408			.map(|(user, amount)| {409				let updated_balance = <Balance<T>>::get((collection.id, &user))410					.checked_add(amount)411					.ok_or(ArithmeticError::Overflow)?;412				Ok((user, amount, updated_balance))413			})414			.collect::<Result<Vec<_>, DispatchError>>()?;415416		// =========417418		<TotalSupply<T>>::insert(collection.id, total_supply);419		for (user, amount, updated_balance) in updated_balances {420			<Balance<T>>::insert((collection.id, &user), updated_balance);421			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(422				&user,423				collection.id,424				TokenId::default(),425			);426			<PalletEvm<T>>::deposit_log(427				ERC20Events::Transfer {428					from: H160::default(),429					to: *user.as_eth(),430					value: amount.into(),431				}432				.to_log(collection_id_to_address(collection.id)),433			);434			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(435				collection.id,436				TokenId::default(),437				user.clone(),438				amount,439			));440		}441442		Ok(())443	}444445	fn set_allowance_unchecked(446		collection: &FungibleHandle<T>,447		owner: &T::CrossAccountId,448		spender: &T::CrossAccountId,449		amount: u128,450	) {451		if amount == 0 {452			<Allowance<T>>::remove((collection.id, owner, spender));453		} else {454			<Allowance<T>>::insert((collection.id, owner, spender), amount);455		}456457		<PalletEvm<T>>::deposit_log(458			ERC20Events::Approval {459				owner: *owner.as_eth(),460				spender: *spender.as_eth(),461				value: amount.into(),462			}463			.to_log(collection_id_to_address(collection.id)),464		);465		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(466			collection.id,467			TokenId(0),468			owner.clone(),469			spender.clone(),470			amount,471		));472	}473474	/// Set allowance for the spender to `transfer` or `burn` owner's tokens.475	///476	/// - `collection`: Collection that contains the token477	/// - `owner`: Owner of tokens that sets the allowance.478	/// - `spender`: Recipient of the allowance rights.479	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.480	pub fn set_allowance(481		collection: &FungibleHandle<T>,482		owner: &T::CrossAccountId,483		spender: &T::CrossAccountId,484		amount: u128,485	) -> DispatchResult {486		if collection.permissions.access() == AccessMode::AllowList {487			collection.check_allowlist(owner)?;488			collection.check_allowlist(spender)?;489		}490491		if <Balance<T>>::get((collection.id, owner)) < amount {492			ensure!(493				collection.ignores_owned_amount(owner),494				<CommonError<T>>::CantApproveMoreThanOwned495			);496		}497498		// =========499500		Self::set_allowance_unchecked(collection, owner, spender, amount);501		Ok(())502	}503504	/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.505	/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.506	///507	/// - `collection`: Collection that contains the token.508	/// - `spender`: CrossAccountId who has the allowance rights.509	/// - `from`: The owner of the tokens who sets the allowance.510	/// - `amount`: Amount of tokens by which the allowance sholud be reduced.511	fn check_allowed(512		collection: &FungibleHandle<T>,513		spender: &T::CrossAccountId,514		from: &T::CrossAccountId,515		amount: u128,516		nesting_budget: &dyn Budget,517	) -> Result<Option<u128>, DispatchError> {518		if spender.conv_eq(from) {519			return Ok(None);520		}521		if collection.permissions.access() == AccessMode::AllowList {522			// `from`, `to` checked in [`transfer`]523			collection.check_allowlist(spender)?;524		}525		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {526			// TODO: should collection owner be allowed to perform this transfer?527			ensure!(528				<PalletStructure<T>>::check_indirectly_owned(529					spender.clone(),530					source.0,531					source.1,532					None,533					nesting_budget534				)?,535				<CommonError<T>>::ApprovedValueTooLow,536			);537			return Ok(None);538		}539		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);540		if allowance.is_none() {541			ensure!(542				collection.ignores_allowance(spender),543				<CommonError<T>>::ApprovedValueTooLow544			);545		}546547		Ok(allowance)548	}549550	/// Transfer fungible tokens from one account to another.551	/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.552	/// The owner should set allowance for the spender to transfer pieces.553	///	See [`set_allowance`][`Pallet::set_allowance`] for more details.554555	pub fn transfer_from(556		collection: &FungibleHandle<T>,557		spender: &T::CrossAccountId,558		from: &T::CrossAccountId,559		to: &T::CrossAccountId,560		amount: u128,561		nesting_budget: &dyn Budget,562	) -> DispatchResult {563		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;564565		// =========566567		Self::transfer(collection, from, to, amount, nesting_budget)?;568		if let Some(allowance) = allowance {569			Self::set_allowance_unchecked(collection, from, spender, allowance);570		}571		Ok(())572	}573574	/// Burn fungible tokens from the account.575	///576	/// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should577	/// set allowance for the spender to burn tokens.578	/// See [`set_allowance`][`Pallet::set_allowance`] for more details.579	pub fn burn_from(580		collection: &FungibleHandle<T>,581		spender: &T::CrossAccountId,582		from: &T::CrossAccountId,583		amount: u128,584		nesting_budget: &dyn Budget,585	) -> DispatchResult {586		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;587588		// =========589590		Self::burn(collection, from, amount)?;591		if let Some(allowance) = allowance {592			Self::set_allowance_unchecked(collection, from, spender, allowance);593		}594		Ok(())595	}596597	///	Creates fungible token.598	///599	/// The sender should be the owner/admin of the collection or collection should be configured600	/// to allow public minting.601	///602	/// - `data`: Contains user who will become the owners of the tokens and amount603	///   of tokens he will receive.604	pub fn create_item(605		collection: &FungibleHandle<T>,606		sender: &T::CrossAccountId,607		data: CreateItemData<T>,608		nesting_budget: &dyn Budget,609	) -> DispatchResult {610		Self::create_multiple_items(611			collection,612			sender,613			[(data.0, data.1)].into_iter().collect(),614			nesting_budget,615		)616	}617618	/// Returns 10 tokens owners in no particular order619	///620	/// There is no direct way to get token holders in ascending order,621	/// since `iter_prefix` returns values in no particular order.622	/// Therefore, getting the 10 largest holders with a large value of holders623	/// can lead to impact memory allocation + sorting with  `n * log (n)`.624	pub fn token_owners(625		collection: CollectionId,626		_token: TokenId,627	) -> Option<Vec<T::CrossAccountId>> {628		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))629			.map(|(owner, _amount)| owner)630			.take(10)631			.collect();632633		if res.is_empty() {634			None635		} else {636			Some(res)637		}638	}639}
after · pallets/fungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//!	- [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::{ensure};84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86	AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,87	budget::Budget,88};89use pallet_common::{90	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91	eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115	use up_data_structs::CollectionId;116	use super::weights::WeightInfo;117118	#[pallet::error]119	pub enum Error<T> {120		/// Not Fungible item data used to mint in Fungible collection.121		NotFungibleDataUsedToMintFungibleCollectionToken,122		/// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.123		FungibleItemsHaveNoId,124		/// Tried to set data for fungible item.125		FungibleItemsDontHaveData,126		/// Fungible token does not support nesting.127		FungibleDisallowsNesting,128		/// Setting item properties is not allowed.129		SettingPropertiesNotAllowed,130	}131132	#[pallet::config]133	pub trait Config:134		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config135	{136		type WeightInfo: WeightInfo;137	}138139	#[pallet::pallet]140	#[pallet::generate_store(pub(super) trait Store)]141	pub struct Pallet<T>(_);142143	/// Total amount of fungible tokens inside a collection.144	#[pallet::storage]145	pub type TotalSupply<T: Config> =146		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;147148	/// Amount of tokens owned by an account inside a collection.149	#[pallet::storage]150	pub type Balance<T: Config> = StorageNMap<151		Key = (152			Key<Twox64Concat, CollectionId>,153			Key<Blake2_128Concat, T::CrossAccountId>,154		),155		Value = u128,156		QueryKind = ValueQuery,157	>;158159	/// Storage for assets delegated to a limited extent to other users.160	#[pallet::storage]161	pub type Allowance<T: Config> = StorageNMap<162		Key = (163			Key<Twox64Concat, CollectionId>,164			Key<Blake2_128, T::CrossAccountId>,165			Key<Blake2_128Concat, T::CrossAccountId>,166		),167		Value = u128,168		QueryKind = ValueQuery,169	>;170171	/// Foreign collection flag172	#[pallet::storage]173	pub type ForeignCollection<T: Config> =174	StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = bool, QueryKind = ValueQuery>;175}176177178/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.179/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].180pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);181182/// Implementation of methods required for dispatching during runtime.183impl<T: Config> FungibleHandle<T> {184	/// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].185	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {186		Self(inner)187	}188189	/// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].190	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {191		self.0192	}193	/// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].194	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {195		&mut self.0196	}197}198impl<T: Config> WithRecorder<T> for FungibleHandle<T> {199	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {200		self.0.recorder()201	}202	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {203		self.0.into_recorder()204	}205}206impl<T: Config> Deref for FungibleHandle<T> {207	type Target = pallet_common::CollectionHandle<T>;208209	fn deref(&self) -> &Self::Target {210		&self.0211	}212}213214/// Pallet implementation for fungible assets215impl<T: Config> Pallet<T> {216	/// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.217	pub fn init_collection(218		owner: T::CrossAccountId,219		data: CreateCollectionData<T::AccountId>,220	) -> Result<CollectionId, DispatchError> {221		<PalletCommon<T>>::init_collection(owner, data, false)222	}223224	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.225	pub fn init_foreign_collection(226		owner: T::CrossAccountId,227		data: CreateCollectionData<T::AccountId>,228	) -> Result<CollectionId, DispatchError> {229		let id = <PalletCommon<T>>::init_collection(owner, data, false)?;230		<ForeignCollection<T>>::insert(id, true);231		Ok(id)232	}233234	/// Destroys a collection.235	pub fn destroy_collection(236		collection: FungibleHandle<T>,237		sender: &T::CrossAccountId,238	) -> DispatchResult {239		let id = collection.id;240241		if Self::collection_has_tokens(id) {242			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());243		}244245		// =========246247		PalletCommon::destroy_collection(collection.0, sender)?;248249		<ForeignCollection<T>>::remove(id);250		<TotalSupply<T>>::remove(id);251		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);252		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);253		Ok(())254	}255256	///Checks if collection has tokens. Return `true` if it has.257	fn collection_has_tokens(collection_id: CollectionId) -> bool {258		<TotalSupply<T>>::get(collection_id) != 0259	}260261	/// Burns the specified amount of the token. If the token balance262	/// or total supply is less than the given value,263	/// it will return [DispatchError].264	pub fn burn(265		collection: &FungibleHandle<T>,266		owner: &T::CrossAccountId,267		amount: u128,268	) -> DispatchResult {269		let total_supply = <TotalSupply<T>>::get(collection.id)270			.checked_sub(amount)271			.ok_or(<CommonError<T>>::TokenValueTooLow)?;272273		let balance = <Balance<T>>::get((collection.id, owner))274			.checked_sub(amount)275			.ok_or(<CommonError<T>>::TokenValueTooLow)?;276277		// Foreign collection check278		ensure!(279			!<ForeignCollection<T>>::get(collection.id),280			<CommonError<T>>::NoPermission281		);282283		if collection.permissions.access() == AccessMode::AllowList {284			collection.check_allowlist(owner)?;285		}286287		// =========288289		if balance == 0 {290			<Balance<T>>::remove((collection.id, owner));291			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());292		} else {293			<Balance<T>>::insert((collection.id, owner), balance);294		}295		<TotalSupply<T>>::insert(collection.id, total_supply);296297		<PalletEvm<T>>::deposit_log(298			ERC20Events::Transfer {299				from: *owner.as_eth(),300				to: H160::default(),301				value: amount.into(),302			}303			.to_log(collection_id_to_address(collection.id)),304		);305		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(306			collection.id,307			TokenId::default(),308			owner.clone(),309			amount,310		));311		Ok(())312	}313314	/// Burns the specified amount of the token.315	pub fn burn_foreign(316		collection: &FungibleHandle<T>,317		owner: &T::CrossAccountId,318		amount: u128,319	) -> DispatchResult {320		let total_supply = <TotalSupply<T>>::get(collection.id)321			.checked_sub(amount)322			.ok_or(<CommonError<T>>::TokenValueTooLow)?;323324		let balance = <Balance<T>>::get((collection.id, owner))325			.checked_sub(amount)326			.ok_or(<CommonError<T>>::TokenValueTooLow)?;327		// =========328329		if balance == 0 {330			<Balance<T>>::remove((collection.id, owner));331			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());332		} else {333			<Balance<T>>::insert((collection.id, owner), balance);334		}335		<TotalSupply<T>>::insert(collection.id, total_supply);336337		<PalletEvm<T>>::deposit_log(338			ERC20Events::Transfer {339				from: *owner.as_eth(),340				to: H160::default(),341				value: amount.into(),342			}343				.to_log(collection_id_to_address(collection.id)),344		);345		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(346			collection.id,347			TokenId::default(),348			owner.clone(),349			amount,350		));351		Ok(())352	}353354	/// Transfers the specified amount of tokens. Will check that355	/// the transfer is allowed for the token.356	///357	/// - `from`: Owner of tokens to transfer.358	/// - `to`: Recepient of transfered tokens.359	/// - `amount`: Amount of tokens to transfer.360	/// - `collection`: Collection that contains the token361	pub fn transfer(362		collection: &FungibleHandle<T>,363		from: &T::CrossAccountId,364		to: &T::CrossAccountId,365		amount: u128,366		nesting_budget: &dyn Budget,367	) -> DispatchResult {368		ensure!(369			collection.limits.transfers_enabled(),370			<CommonError<T>>::TransferNotAllowed,371		);372373		if collection.permissions.access() == AccessMode::AllowList {374			collection.check_allowlist(from)?;375			collection.check_allowlist(to)?;376		}377		<PalletCommon<T>>::ensure_correct_receiver(to)?;378379		let balance_from = <Balance<T>>::get((collection.id, from))380			.checked_sub(amount)381			.ok_or(<CommonError<T>>::TokenValueTooLow)?;382		let balance_to = if from != to {383			Some(384				<Balance<T>>::get((collection.id, to))385					.checked_add(amount)386					.ok_or(ArithmeticError::Overflow)?,387			)388		} else {389			None390		};391392		// =========393394		<PalletStructure<T>>::nest_if_sent_to_token(395			from.clone(),396			to,397			collection.id,398			TokenId::default(),399			nesting_budget,400		)?;401402		if let Some(balance_to) = balance_to {403			// from != to404			if balance_from == 0 {405				<Balance<T>>::remove((collection.id, from));406				<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());407			} else {408				<Balance<T>>::insert((collection.id, from), balance_from);409			}410			<Balance<T>>::insert((collection.id, to), balance_to);411		}412413		<PalletEvm<T>>::deposit_log(414			ERC20Events::Transfer {415				from: *from.as_eth(),416				to: *to.as_eth(),417				value: amount.into(),418			}419			.to_log(collection_id_to_address(collection.id)),420		);421		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(422			collection.id,423			TokenId::default(),424			from.clone(),425			to.clone(),426			amount,427		));428		Ok(())429	}430431	/// Minting tokens for multiple IDs.432	/// See [`create_item`][`Pallet::create_item`] for more details.433	pub fn create_multiple_items(434		collection: &FungibleHandle<T>,435		sender: &T::CrossAccountId,436		data: BTreeMap<T::CrossAccountId, u128>,437		nesting_budget: &dyn Budget,438	) -> DispatchResult {439		// Foreign collection check440		ensure!(441			!<ForeignCollection<T>>::get(collection.id),442			<CommonError<T>>::NoPermission443		);444445		if !collection.is_owner_or_admin(sender) {446			ensure!(447				collection.permissions.mint_mode(),448				<CommonError<T>>::PublicMintingNotAllowed449			);450			collection.check_allowlist(sender)?;451452			for (owner, _) in data.iter() {453				collection.check_allowlist(owner)?;454			}455		}456457		let total_supply = data458			.iter()459			.map(|(_, v)| *v)460			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {461				acc.checked_add(v)462			})463			.ok_or(ArithmeticError::Overflow)?;464465		for (to, _) in data.iter() {466			<PalletStructure<T>>::check_nesting(467				sender.clone(),468				to,469				collection.id,470				TokenId::default(),471				nesting_budget,472			)?;473		}474475		let updated_balances = data476			.into_iter()477			.map(|(user, amount)| {478				let updated_balance = <Balance<T>>::get((collection.id, &user))479					.checked_add(amount)480					.ok_or(ArithmeticError::Overflow)?;481				Ok((user, amount, updated_balance))482			})483			.collect::<Result<Vec<_>, DispatchError>>()?;484485		// =========486487		<TotalSupply<T>>::insert(collection.id, total_supply);488		for (user, amount, updated_balance) in updated_balances {489			<Balance<T>>::insert((collection.id, &user), updated_balance);490			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(491				&user,492				collection.id,493				TokenId::default(),494			);495			<PalletEvm<T>>::deposit_log(496				ERC20Events::Transfer {497					from: H160::default(),498					to: *user.as_eth(),499					value: amount.into(),500				}501				.to_log(collection_id_to_address(collection.id)),502			);503			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(504				collection.id,505				TokenId::default(),506				user.clone(),507				amount,508			));509		}510511		Ok(())512	}513514	/// Minting tokens for multiple IDs.515	/// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.516	pub fn create_multiple_items_foreign(517		collection: &FungibleHandle<T>,518		sender: &T::CrossAccountId,519		data: BTreeMap<T::CrossAccountId, u128>,520		nesting_budget: &dyn Budget,521	) -> DispatchResult {522		let total_supply = data523			.iter()524			.map(|(_, v)| *v)525			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {526				acc.checked_add(v)527			})528			.ok_or(ArithmeticError::Overflow)?;529530		let mut balances = data;531		for (k, v) in balances.iter_mut() {532			*v = <Balance<T>>::get((collection.id, &k))533				.checked_add(*v)534				.ok_or(ArithmeticError::Overflow)?;535		}536537		for (to, _) in balances.iter() {538			<PalletStructure<T>>::check_nesting(539				sender.clone(),540				to,541				collection.id,542				TokenId::default(),543				nesting_budget,544			)?;545		}546547		// =========548549		<TotalSupply<T>>::insert(collection.id, total_supply);550		for (user, amount) in balances {551			<Balance<T>>::insert((collection.id, &user), amount);552			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(553				&user,554				collection.id,555				TokenId::default(),556			);557			<PalletEvm<T>>::deposit_log(558				ERC20Events::Transfer {559					from: H160::default(),560					to: *user.as_eth(),561					value: amount.into(),562				}563					.to_log(collection_id_to_address(collection.id)),564			);565			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(566				collection.id,567				TokenId::default(),568				user.clone(),569				amount,570			));571		}572573		Ok(())574	}575576	fn set_allowance_unchecked(577		collection: &FungibleHandle<T>,578		owner: &T::CrossAccountId,579		spender: &T::CrossAccountId,580		amount: u128,581	) {582		if amount == 0 {583			<Allowance<T>>::remove((collection.id, owner, spender));584		} else {585			<Allowance<T>>::insert((collection.id, owner, spender), amount);586		}587588		<PalletEvm<T>>::deposit_log(589			ERC20Events::Approval {590				owner: *owner.as_eth(),591				spender: *spender.as_eth(),592				value: amount.into(),593			}594			.to_log(collection_id_to_address(collection.id)),595		);596		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(597			collection.id,598			TokenId(0),599			owner.clone(),600			spender.clone(),601			amount,602		));603	}604605	/// Set allowance for the spender to `transfer` or `burn` owner's tokens.606	///607	/// - `collection`: Collection that contains the token608	/// - `owner`: Owner of tokens that sets the allowance.609	/// - `spender`: Recipient of the allowance rights.610	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.611	pub fn set_allowance(612		collection: &FungibleHandle<T>,613		owner: &T::CrossAccountId,614		spender: &T::CrossAccountId,615		amount: u128,616	) -> DispatchResult {617		if collection.permissions.access() == AccessMode::AllowList {618			collection.check_allowlist(owner)?;619			collection.check_allowlist(spender)?;620		}621622		if <Balance<T>>::get((collection.id, owner)) < amount {623			ensure!(624				collection.ignores_owned_amount(owner),625				<CommonError<T>>::CantApproveMoreThanOwned626			);627		}628629		// =========630631		Self::set_allowance_unchecked(collection, owner, spender, amount);632		Ok(())633	}634635	/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.636	/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.637	///638	/// - `collection`: Collection that contains the token.639	/// - `spender`: CrossAccountId who has the allowance rights.640	/// - `from`: The owner of the tokens who sets the allowance.641	/// - `amount`: Amount of tokens by which the allowance sholud be reduced.642	fn check_allowed(643		collection: &FungibleHandle<T>,644		spender: &T::CrossAccountId,645		from: &T::CrossAccountId,646		amount: u128,647		nesting_budget: &dyn Budget,648	) -> Result<Option<u128>, DispatchError> {649		if spender.conv_eq(from) {650			return Ok(None);651		}652		if collection.permissions.access() == AccessMode::AllowList {653			// `from`, `to` checked in [`transfer`]654			collection.check_allowlist(spender)?;655		}656		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {657			// TODO: should collection owner be allowed to perform this transfer?658			ensure!(659				<PalletStructure<T>>::check_indirectly_owned(660					spender.clone(),661					source.0,662					source.1,663					None,664					nesting_budget665				)?,666				<CommonError<T>>::ApprovedValueTooLow,667			);668			return Ok(None);669		}670		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);671		if allowance.is_none() {672			ensure!(673				collection.ignores_allowance(spender),674				<CommonError<T>>::ApprovedValueTooLow675			);676		}677678		Ok(allowance)679	}680681	/// Transfer fungible tokens from one account to another.682	/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.683	/// The owner should set allowance for the spender to transfer pieces.684	///	See [`set_allowance`][`Pallet::set_allowance`] for more details.685686	pub fn transfer_from(687		collection: &FungibleHandle<T>,688		spender: &T::CrossAccountId,689		from: &T::CrossAccountId,690		to: &T::CrossAccountId,691		amount: u128,692		nesting_budget: &dyn Budget,693	) -> DispatchResult {694		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;695696		// =========697698		Self::transfer(collection, from, to, amount, nesting_budget)?;699		if let Some(allowance) = allowance {700			Self::set_allowance_unchecked(collection, from, spender, allowance);701		}702		Ok(())703	}704705	/// Burn fungible tokens from the account.706	///707	/// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should708	/// set allowance for the spender to burn tokens.709	/// See [`set_allowance`][`Pallet::set_allowance`] for more details.710	pub fn burn_from(711		collection: &FungibleHandle<T>,712		spender: &T::CrossAccountId,713		from: &T::CrossAccountId,714		amount: u128,715		nesting_budget: &dyn Budget,716	) -> DispatchResult {717		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;718719		// =========720721		Self::burn(collection, from, amount)?;722		if let Some(allowance) = allowance {723			Self::set_allowance_unchecked(collection, from, spender, allowance);724		}725		Ok(())726	}727728	///	Creates fungible token.729	///730	/// The sender should be the owner/admin of the collection or collection should be configured731	/// to allow public minting.732	///733	/// - `data`: Contains user who will become the owners of the tokens and amount734	///   of tokens he will receive.735	pub fn create_item(736		collection: &FungibleHandle<T>,737		sender: &T::CrossAccountId,738		data: CreateItemData<T>,739		nesting_budget: &dyn Budget,740	) -> DispatchResult {741		Self::create_multiple_items(742			collection,743			sender,744			[(data.0, data.1)].into_iter().collect(),745			nesting_budget,746		)747	}748749	///	Creates fungible token.750	///751	/// - `data`: Contains user who will become the owners of the tokens and amount752	///   of tokens he will receive.753	pub fn create_item_foreign(754		collection: &FungibleHandle<T>,755		sender: &T::CrossAccountId,756		data: CreateItemData<T>,757		nesting_budget: &dyn Budget,758	) -> DispatchResult {759		Self::create_multiple_items_foreign(760			collection,761			sender,762			[(data.0, data.1)].into_iter().collect(),763			nesting_budget,764		)765	}766767	/// Returns 10 tokens owners in no particular order768	///769	/// There is no direct way to get token holders in ascending order,770	/// since `iter_prefix` returns values in no particular order.771	/// Therefore, getting the 10 largest holders with a large value of holders772	/// can lead to impact memory allocation + sorting with  `n * log (n)`.773	pub fn token_owners(774		collection: CollectionId,775		_token: TokenId,776	) -> Option<Vec<T::CrossAccountId>> {777		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))778			.map(|(owner, _amount)| owner)779			.take(10)780			.collect();781782		if res.is_empty() {783			None784		} else {785			Some(res)786		}787	}788}
addedruntime/common/config/pallets/foreign_asset.rsdiffbeforeafterboth
--- /dev/null
+++ b/runtime/common/config/pallets/foreign_asset.rs
@@ -0,0 +1,9 @@
+use crate::{Runtime, Event, Balances};
+use up_common::types::AccountId;
+
+impl pallet_foreing_assets::Config for Runtime {
+    type Event = Event;
+    type Currency = Balances;
+    type RegisterOrigin = frame_system::EnsureRoot<AccountId>;
+    type WeightInfo = ();
+}
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -40,6 +40,9 @@
 #[cfg(feature = "scheduler")]
 pub mod scheduler;
 
+#[cfg(feature = "foreign-asset")]
+pub mod foreign_asset;
+
 parameter_types! {
 	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account_truncating();
 	pub const CollectionCreationPrice: Balance = 2 * UNIQUE;
modifiedruntime/common/construct_runtime/mod.rsdiffbeforeafterboth
--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -42,6 +42,8 @@
                 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,
                 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,
                 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,
+                XTokens: orml_xtokens = 38,
+                Tokens: orml_tokens = 39,
                 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,
                 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,
 
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -120,13 +120,18 @@
     'up-sponsorship/std',
 
     "orml-vesting/std",
+    "orml-tokens/std",
+    "orml-xtokens/std",
+    "orml-traits/std",
+    "pallet-foreing-assets/std"
 ]
 limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
-opal-runtime = ['refungible', 'scheduler', 'rmrk']
+opal-runtime = ['refungible', 'scheduler', 'rmrk', 'foreign-asset']
 
 refungible = []
 scheduler = []
 rmrk = []
+foreign-asset = []
 
 ################################################################################
 # Substrate Dependencies
@@ -399,6 +404,24 @@
 version = "0.4.1-dev"
 default-features = false
 
+[dependencies.orml-xtokens]
+git = "https://github.com/open-web3-stack/open-runtime-module-library"
+branch = "polkadot-v0.9.27"
+version = "0.4.1-dev"
+default-features = false
+
+[dependencies.orml-tokens]
+git = "https://github.com/open-web3-stack/open-runtime-module-library"
+branch = "polkadot-v0.9.27"
+version = "0.4.1-dev"
+default-features = false
+
+[dependencies.orml-traits]
+git = "https://github.com/open-web3-stack/open-runtime-module-library"
+branch = "polkadot-v0.9.27"
+version = "0.4.1-dev"
+default-features = false
+
 ################################################################################
 # local dependencies
 
@@ -437,6 +460,7 @@
 fp-self-contained = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.27" }
 evm-coder = { default-features = false, path = '../../crates/evm-coder' }
 up-sponsorship = { default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = 'polkadot-v0.9.27' }
+pallet-foreing-assets = { default-features = false, path = "../../pallets/foreing-assets" }
 
 ################################################################################
 # Build Dependencies
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -35,6 +35,8 @@
 #[path = "../../common/mod.rs"]
 mod runtime_common;
 
+pub mod xcm_config;
+
 pub use runtime_common::*;
 
 pub const RUNTIME_NAME: &str = "opal";