difftreelog
chore fix code review requests
in: master
3 files changed
pallets/fungible/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//! # 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, CollectionFlags, TokenId, CreateCollectionData,87 mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,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::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 /// Setting allowance for all is not allowed.131 SettingAllowanceForAllNotAllowed,132 /// Only a fungible collection could be possibly broken; any fungible token is valid.133 FungibleTokensAreAlwaysValid,134 }135136 #[pallet::config]137 pub trait Config:138 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config139 {140 type WeightInfo: WeightInfo;141 }142143 #[pallet::pallet]144 #[pallet::generate_store(pub(super) trait Store)]145 pub struct Pallet<T>(_);146147 /// Total amount of fungible tokens inside a collection.148 #[pallet::storage]149 pub type TotalSupply<T: Config> =150 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;151152 /// Amount of tokens owned by an account inside a collection.153 #[pallet::storage]154 pub type Balance<T: Config> = StorageNMap<155 Key = (156 Key<Twox64Concat, CollectionId>,157 Key<Blake2_128Concat, T::CrossAccountId>,158 ),159 Value = u128,160 QueryKind = ValueQuery,161 >;162163 /// Storage for assets delegated to a limited extent to other users.164 #[pallet::storage]165 pub type Allowance<T: Config> = StorageNMap<166 Key = (167 Key<Twox64Concat, CollectionId>,168 Key<Blake2_128, T::CrossAccountId>,169 Key<Blake2_128Concat, T::CrossAccountId>,170 ),171 Value = u128,172 QueryKind = ValueQuery,173 >;174}175176/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.177/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].178pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);179180/// Implementation of methods required for dispatching during runtime.181impl<T: Config> FungibleHandle<T> {182 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].183 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {184 Self(inner)185 }186187 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].188 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {189 self.0190 }191 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].192 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {193 &mut self.0194 }195}196impl<T: Config> WithRecorder<T> for FungibleHandle<T> {197 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {198 self.0.recorder()199 }200 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {201 self.0.into_recorder()202 }203}204impl<T: Config> Deref for FungibleHandle<T> {205 type Target = pallet_common::CollectionHandle<T>;206207 fn deref(&self) -> &Self::Target {208 &self.0209 }210}211212/// Pallet implementation for fungible assets213impl<T: Config> Pallet<T> {214 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.215 pub fn init_collection(216 owner: T::CrossAccountId,217 payer: T::CrossAccountId,218 data: CreateCollectionData<T::AccountId>,219 flags: CollectionFlags,220 ) -> Result<CollectionId, DispatchError> {221 <PalletCommon<T>>::init_collection(owner, payer, data, flags)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 payer: T::CrossAccountId,228 data: CreateCollectionData<T::AccountId>,229 ) -> Result<CollectionId, DispatchError> {230 let id = <PalletCommon<T>>::init_collection(231 owner,232 payer,233 data,234 CollectionFlags {235 foreign: true,236 ..Default::default()237 },238 )?;239 Ok(id)240 }241242 /// Destroys a collection.243 pub fn destroy_collection(244 collection: FungibleHandle<T>,245 sender: &T::CrossAccountId,246 ) -> DispatchResult {247 let id = collection.id;248249 if Self::collection_has_tokens(id) {250 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());251 }252253 // =========254255 PalletCommon::destroy_collection(collection.0, sender)?;256257 <TotalSupply<T>>::remove(id);258 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);259 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);260 Ok(())261 }262263 /// Add properties to the collection.264 pub fn set_collection_properties(265 collection: &FungibleHandle<T>,266 sender: &T::CrossAccountId,267 properties: Vec<Property>,268 ) -> DispatchResult {269 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)270 }271272 /// Delete properties of the collection, associated with the provided keys.273 pub fn delete_collection_properties(274 collection: &FungibleHandle<T>,275 sender: &T::CrossAccountId,276 property_keys: Vec<PropertyKey>,277 ) -> DispatchResult {278 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)279 }280281 /// Checks if collection has tokens. Return `true` if it has.282 fn collection_has_tokens(collection_id: CollectionId) -> bool {283 <TotalSupply<T>>::get(collection_id) != 0284 }285286 /// Burns the specified amount of the token. If the token balance287 /// or total supply is less than the given value,288 /// it will return [DispatchError].289 pub fn burn(290 collection: &FungibleHandle<T>,291 owner: &T::CrossAccountId,292 amount: u128,293 ) -> DispatchResult {294 let total_supply = <TotalSupply<T>>::get(collection.id)295 .checked_sub(amount)296 .ok_or(<CommonError<T>>::TokenValueTooLow)?;297298 let balance = <Balance<T>>::get((collection.id, owner))299 .checked_sub(amount)300 .ok_or(<CommonError<T>>::TokenValueTooLow)?;301302 // Foreign collection check303 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);304305 if collection.permissions.access() == AccessMode::AllowList {306 collection.check_allowlist(owner)?;307 }308309 // =========310311 if balance == 0 {312 <Balance<T>>::remove((collection.id, owner));313 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());314 } else {315 <Balance<T>>::insert((collection.id, owner), balance);316 }317 <TotalSupply<T>>::insert(collection.id, total_supply);318319 <PalletEvm<T>>::deposit_log(320 ERC20Events::Transfer {321 from: *owner.as_eth(),322 to: H160::default(),323 value: amount.into(),324 }325 .to_log(collection_id_to_address(collection.id)),326 );327 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(328 collection.id,329 TokenId::default(),330 owner.clone(),331 amount,332 ));333 Ok(())334 }335336 /// Burns the specified amount of the token.337 pub fn burn_foreign(338 collection: &FungibleHandle<T>,339 owner: &T::CrossAccountId,340 amount: u128,341 ) -> DispatchResult {342 let total_supply = <TotalSupply<T>>::get(collection.id)343 .checked_sub(amount)344 .ok_or(<CommonError<T>>::TokenValueTooLow)?;345346 let balance = <Balance<T>>::get((collection.id, owner))347 .checked_sub(amount)348 .ok_or(<CommonError<T>>::TokenValueTooLow)?;349 // =========350351 if balance == 0 {352 <Balance<T>>::remove((collection.id, owner));353 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());354 } else {355 <Balance<T>>::insert((collection.id, owner), balance);356 }357 <TotalSupply<T>>::insert(collection.id, total_supply);358359 <PalletEvm<T>>::deposit_log(360 ERC20Events::Transfer {361 from: *owner.as_eth(),362 to: H160::default(),363 value: amount.into(),364 }365 .to_log(collection_id_to_address(collection.id)),366 );367 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(368 collection.id,369 TokenId::default(),370 owner.clone(),371 amount,372 ));373 Ok(())374 }375376 /// Transfers the specified amount of tokens. Will check that377 /// the transfer is allowed for the token.378 ///379 /// - `from`: Owner of tokens to transfer.380 /// - `to`: Recepient of transfered tokens.381 /// - `amount`: Amount of tokens to transfer.382 /// - `collection`: Collection that contains the token383 pub fn transfer(384 collection: &FungibleHandle<T>,385 from: &T::CrossAccountId,386 to: &T::CrossAccountId,387 amount: u128,388 nesting_budget: &dyn Budget,389 ) -> DispatchResult {390 ensure!(391 collection.limits.transfers_enabled(),392 <CommonError<T>>::TransferNotAllowed,393 );394395 if collection.permissions.access() == AccessMode::AllowList {396 collection.check_allowlist(from)?;397 collection.check_allowlist(to)?;398 }399 <PalletCommon<T>>::ensure_correct_receiver(to)?;400401 let balance_from = <Balance<T>>::get((collection.id, from))402 .checked_sub(amount)403 .ok_or(<CommonError<T>>::TokenValueTooLow)?;404 let balance_to = if from != to && amount != 0 {405 Some(406 <Balance<T>>::get((collection.id, to))407 .checked_add(amount)408 .ok_or(ArithmeticError::Overflow)?,409 )410 } else {411 None412 };413414 // =========415416 if let Some(balance_to) = balance_to {417 // from != to && amount != 0418419 <PalletStructure<T>>::nest_if_sent_to_token(420 from.clone(),421 to,422 collection.id,423 TokenId::default(),424 nesting_budget,425 )?;426427 if balance_from == 0 {428 <Balance<T>>::remove((collection.id, from));429 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());430 } else {431 <Balance<T>>::insert((collection.id, from), balance_from);432 }433 <Balance<T>>::insert((collection.id, to), balance_to);434 }435436 <PalletEvm<T>>::deposit_log(437 ERC20Events::Transfer {438 from: *from.as_eth(),439 to: *to.as_eth(),440 value: amount.into(),441 }442 .to_log(collection_id_to_address(collection.id)),443 );444 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(445 collection.id,446 TokenId::default(),447 from.clone(),448 to.clone(),449 amount,450 ));451 Ok(())452 }453454 /// Minting tokens for multiple IDs.455 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]456 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]457 pub fn create_multiple_items_common(458 collection: &FungibleHandle<T>,459 sender: &T::CrossAccountId,460 data: BTreeMap<T::CrossAccountId, u128>,461 nesting_budget: &dyn Budget,462 ) -> DispatchResult {463 let total_supply = data464 .iter()465 .map(|(_, v)| *v)466 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {467 acc.checked_add(v)468 })469 .ok_or(ArithmeticError::Overflow)?;470471 for (to, _) in data.iter() {472 <PalletStructure<T>>::check_nesting(473 sender.clone(),474 to,475 collection.id,476 TokenId::default(),477 nesting_budget,478 )?;479 }480481 let updated_balances = data482 .into_iter()483 .map(|(user, amount)| {484 let updated_balance = <Balance<T>>::get((collection.id, &user))485 .checked_add(amount)486 .ok_or(ArithmeticError::Overflow)?;487 Ok((user, amount, updated_balance))488 })489 .collect::<Result<Vec<_>, DispatchError>>()?;490491 // =========492493 <TotalSupply<T>>::insert(collection.id, total_supply);494 for (user, amount, updated_balance) in updated_balances {495 <Balance<T>>::insert((collection.id, &user), updated_balance);496 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(497 &user,498 collection.id,499 TokenId::default(),500 );501 <PalletEvm<T>>::deposit_log(502 ERC20Events::Transfer {503 from: H160::default(),504 to: *user.as_eth(),505 value: amount.into(),506 }507 .to_log(collection_id_to_address(collection.id)),508 );509 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(510 collection.id,511 TokenId::default(),512 user.clone(),513 amount,514 ));515 }516517 Ok(())518 }519520 /// Minting tokens for multiple IDs.521 /// See [`create_item`][`Pallet::create_item`] for more details.522 pub fn create_multiple_items(523 collection: &FungibleHandle<T>,524 sender: &T::CrossAccountId,525 data: BTreeMap<T::CrossAccountId, u128>,526 nesting_budget: &dyn Budget,527 ) -> DispatchResult {528 // Foreign collection check529 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);530531 if !collection.is_owner_or_admin(sender) {532 ensure!(533 collection.permissions.mint_mode(),534 <CommonError<T>>::PublicMintingNotAllowed535 );536 collection.check_allowlist(sender)?;537538 for (owner, _) in data.iter() {539 collection.check_allowlist(owner)?;540 }541 }542543 Self::create_multiple_items_common(collection, sender, data, nesting_budget)544 }545546 /// Minting tokens for multiple IDs.547 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.548 pub fn create_multiple_items_foreign(549 collection: &FungibleHandle<T>,550 sender: &T::CrossAccountId,551 data: BTreeMap<T::CrossAccountId, u128>,552 nesting_budget: &dyn Budget,553 ) -> DispatchResult {554 Self::create_multiple_items_common(collection, sender, data, nesting_budget)555 }556557 fn set_allowance_unchecked(558 collection: &FungibleHandle<T>,559 owner: &T::CrossAccountId,560 spender: &T::CrossAccountId,561 amount: u128,562 ) {563 if amount == 0 {564 <Allowance<T>>::remove((collection.id, owner, spender));565 } else {566 <Allowance<T>>::insert((collection.id, owner, spender), amount);567 }568569 <PalletEvm<T>>::deposit_log(570 ERC20Events::Approval {571 owner: *owner.as_eth(),572 spender: *spender.as_eth(),573 value: amount.into(),574 }575 .to_log(collection_id_to_address(collection.id)),576 );577 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(578 collection.id,579 TokenId(0),580 owner.clone(),581 spender.clone(),582 amount,583 ));584 }585586 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.587 ///588 /// - `collection`: Collection that contains the token589 /// - `owner`: Owner of tokens that sets the allowance.590 /// - `spender`: Recipient of the allowance rights.591 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.592 pub fn set_allowance(593 collection: &FungibleHandle<T>,594 owner: &T::CrossAccountId,595 spender: &T::CrossAccountId,596 amount: u128,597 ) -> DispatchResult {598 if collection.permissions.access() == AccessMode::AllowList {599 collection.check_allowlist(owner)?;600 collection.check_allowlist(spender)?;601 }602603 if <Balance<T>>::get((collection.id, owner)) < amount {604 ensure!(605 collection.ignores_owned_amount(owner),606 <CommonError<T>>::CantApproveMoreThanOwned607 );608 }609610 // =========611612 Self::set_allowance_unchecked(collection, owner, spender, amount);613 Ok(())614 }615616 /// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.617 ///618 /// - `collection`: Collection that contains the token619 /// - `sender`: Owner of tokens that sets the allowance.620 /// - `from`: Owner's eth mirror.621 /// - `to`: Recipient of the allowance rights.622 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.623 pub fn set_allowance_from(624 collection: &FungibleHandle<T>,625 sender: &T::CrossAccountId,626 from: &T::CrossAccountId,627 to: &T::CrossAccountId,628 amount: u128,629 ) -> DispatchResult {630 if collection.permissions.access() == AccessMode::AllowList {631 collection.check_allowlist(sender)?;632 collection.check_allowlist(from)?;633 collection.check_allowlist(to)?;634 }635636 ensure!(637 *sender.as_eth() == *from.as_eth(),638 <CommonError<T>>::AddressIsNotEthMirror639 );640641 if <Balance<T>>::get((collection.id, from)) < amount {642 ensure!(643 collection.limits.owner_can_transfer()644 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),645 <CommonError<T>>::CantApproveMoreThanOwned646 );647 }648649 // =========650651 Self::set_allowance_unchecked(collection, from, to, amount);652 Ok(())653 }654655 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.656 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.657 ///658 /// - `collection`: Collection that contains the token.659 /// - `spender`: CrossAccountId who has the allowance rights.660 /// - `from`: The owner of the tokens who sets the allowance.661 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.662 fn check_allowed(663 collection: &FungibleHandle<T>,664 spender: &T::CrossAccountId,665 from: &T::CrossAccountId,666 amount: u128,667 nesting_budget: &dyn Budget,668 ) -> Result<Option<u128>, DispatchError> {669 if spender.conv_eq(from) {670 return Ok(None);671 }672 if collection.permissions.access() == AccessMode::AllowList {673 // `from`, `to` checked in [`transfer`]674 collection.check_allowlist(spender)?;675 }676 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {677 // TODO: should collection owner be allowed to perform this transfer?678 ensure!(679 <PalletStructure<T>>::check_indirectly_owned(680 spender.clone(),681 source.0,682 source.1,683 None,684 nesting_budget685 )?,686 <CommonError<T>>::ApprovedValueTooLow,687 );688 return Ok(None);689 }690 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);691 if allowance.is_none() {692 ensure!(693 collection.ignores_allowance(spender),694 <CommonError<T>>::ApprovedValueTooLow695 );696 }697698 Ok(allowance)699 }700701 /// Transfer fungible tokens from one account to another.702 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.703 /// The owner should set allowance for the spender to transfer pieces.704 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.705706 pub fn transfer_from(707 collection: &FungibleHandle<T>,708 spender: &T::CrossAccountId,709 from: &T::CrossAccountId,710 to: &T::CrossAccountId,711 amount: u128,712 nesting_budget: &dyn Budget,713 ) -> DispatchResult {714 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;715716 // =========717718 Self::transfer(collection, from, to, amount, nesting_budget)?;719 if let Some(allowance) = allowance {720 Self::set_allowance_unchecked(collection, from, spender, allowance);721 }722 Ok(())723 }724725 /// Burn fungible tokens from the account.726 ///727 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should728 /// set allowance for the spender to burn tokens.729 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.730 pub fn burn_from(731 collection: &FungibleHandle<T>,732 spender: &T::CrossAccountId,733 from: &T::CrossAccountId,734 amount: u128,735 nesting_budget: &dyn Budget,736 ) -> DispatchResult {737 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;738739 // =========740741 Self::burn(collection, from, amount)?;742 if let Some(allowance) = allowance {743 Self::set_allowance_unchecked(collection, from, spender, allowance);744 }745 Ok(())746 }747748 /// Creates fungible token.749 ///750 /// The sender should be the owner/admin of the collection or collection should be configured751 /// to allow public minting.752 ///753 /// - `data`: Contains user who will become the owners of the tokens and amount754 /// of tokens he will receive.755 pub fn create_item(756 collection: &FungibleHandle<T>,757 sender: &T::CrossAccountId,758 data: CreateItemData<T>,759 nesting_budget: &dyn Budget,760 ) -> DispatchResult {761 Self::create_multiple_items(762 collection,763 sender,764 [(data.0, data.1)].into_iter().collect(),765 nesting_budget,766 )767 }768769 /// Creates fungible token.770 ///771 /// - `data`: Contains user who will become the owners of the tokens and amount772 /// of tokens he will receive.773 pub fn create_item_foreign(774 collection: &FungibleHandle<T>,775 sender: &T::CrossAccountId,776 data: CreateItemData<T>,777 nesting_budget: &dyn Budget,778 ) -> DispatchResult {779 Self::create_multiple_items_foreign(780 collection,781 sender,782 [(data.0, data.1)].into_iter().collect(),783 nesting_budget,784 )785 }786787 /// Returns 10 tokens owners in no particular order788 ///789 /// There is no direct way to get token holders in ascending order,790 /// since `iter_prefix` returns values in no particular order.791 /// Therefore, getting the 10 largest holders with a large value of holders792 /// can lead to impact memory allocation + sorting with `n * log (n)`.793 pub fn token_owners(794 collection: CollectionId,795 _token: TokenId,796 ) -> Option<Vec<T::CrossAccountId>> {797 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))798 .map(|(owner, _amount)| owner)799 .take(10)800 .collect();801802 if res.is_empty() {803 None804 } else {805 Some(res)806 }807 }808}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, CollectionFlags, TokenId, CreateCollectionData,87 mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,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::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 /// Setting allowance for all is not allowed.131 SettingAllowanceForAllNotAllowed,132 /// Only a fungible collection could be possibly broken; any fungible token is valid.133 FungibleTokensAreAlwaysValid,134 }135136 #[pallet::config]137 pub trait Config:138 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config139 {140 type WeightInfo: WeightInfo;141 }142143 #[pallet::pallet]144 #[pallet::generate_store(pub(super) trait Store)]145 pub struct Pallet<T>(_);146147 /// Total amount of fungible tokens inside a collection.148 #[pallet::storage]149 pub type TotalSupply<T: Config> =150 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;151152 /// Amount of tokens owned by an account inside a collection.153 #[pallet::storage]154 pub type Balance<T: Config> = StorageNMap<155 Key = (156 Key<Twox64Concat, CollectionId>,157 Key<Blake2_128Concat, T::CrossAccountId>,158 ),159 Value = u128,160 QueryKind = ValueQuery,161 >;162163 /// Storage for assets delegated to a limited extent to other users.164 #[pallet::storage]165 pub type Allowance<T: Config> = StorageNMap<166 Key = (167 Key<Twox64Concat, CollectionId>,168 Key<Blake2_128, T::CrossAccountId>,169 Key<Blake2_128Concat, T::CrossAccountId>,170 ),171 Value = u128,172 QueryKind = ValueQuery,173 >;174}175176/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.177/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].178pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);179180/// Implementation of methods required for dispatching during runtime.181impl<T: Config> FungibleHandle<T> {182 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].183 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {184 Self(inner)185 }186187 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].188 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {189 self.0190 }191 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].192 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {193 &mut self.0194 }195}196impl<T: Config> WithRecorder<T> for FungibleHandle<T> {197 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {198 self.0.recorder()199 }200 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {201 self.0.into_recorder()202 }203}204impl<T: Config> Deref for FungibleHandle<T> {205 type Target = pallet_common::CollectionHandle<T>;206207 fn deref(&self) -> &Self::Target {208 &self.0209 }210}211212/// Pallet implementation for fungible assets213impl<T: Config> Pallet<T> {214 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.215 pub fn init_collection(216 owner: T::CrossAccountId,217 payer: T::CrossAccountId,218 data: CreateCollectionData<T::AccountId>,219 flags: CollectionFlags,220 ) -> Result<CollectionId, DispatchError> {221 <PalletCommon<T>>::init_collection(owner, payer, data, flags)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 payer: T::CrossAccountId,228 data: CreateCollectionData<T::AccountId>,229 ) -> Result<CollectionId, DispatchError> {230 let id = <PalletCommon<T>>::init_collection(231 owner,232 payer,233 data,234 CollectionFlags {235 foreign: true,236 ..Default::default()237 },238 )?;239 Ok(id)240 }241242 /// Destroys a collection.243 pub fn destroy_collection(244 collection: FungibleHandle<T>,245 sender: &T::CrossAccountId,246 ) -> DispatchResult {247 let id = collection.id;248249 if Self::collection_has_tokens(id) {250 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());251 }252253 // =========254255 PalletCommon::destroy_collection(collection.0, sender)?;256257 <TotalSupply<T>>::remove(id);258 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);259 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);260 Ok(())261 }262263 /// Add properties to the collection.264 pub fn set_collection_properties(265 collection: &FungibleHandle<T>,266 sender: &T::CrossAccountId,267 properties: Vec<Property>,268 ) -> DispatchResult {269 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)270 }271272 /// Delete properties of the collection, associated with the provided keys.273 pub fn delete_collection_properties(274 collection: &FungibleHandle<T>,275 sender: &T::CrossAccountId,276 property_keys: Vec<PropertyKey>,277 ) -> DispatchResult {278 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)279 }280281 /// Checks if collection has tokens. Return `true` if it has.282 fn collection_has_tokens(collection_id: CollectionId) -> bool {283 <TotalSupply<T>>::get(collection_id) != 0284 }285286 /// Burns the specified amount of the token. If the token balance287 /// or total supply is less than the given value,288 /// it will return [DispatchError].289 pub fn burn(290 collection: &FungibleHandle<T>,291 owner: &T::CrossAccountId,292 amount: u128,293 ) -> DispatchResult {294 let total_supply = <TotalSupply<T>>::get(collection.id)295 .checked_sub(amount)296 .ok_or(<CommonError<T>>::TokenValueTooLow)?;297298 let balance = <Balance<T>>::get((collection.id, owner))299 .checked_sub(amount)300 .ok_or(<CommonError<T>>::TokenValueTooLow)?;301302 // Foreign collection check303 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);304305 if collection.permissions.access() == AccessMode::AllowList {306 collection.check_allowlist(owner)?;307 }308309 // =========310311 if balance == 0 {312 <Balance<T>>::remove((collection.id, owner));313 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());314 } else {315 <Balance<T>>::insert((collection.id, owner), balance);316 }317 <TotalSupply<T>>::insert(collection.id, total_supply);318319 <PalletEvm<T>>::deposit_log(320 ERC20Events::Transfer {321 from: *owner.as_eth(),322 to: H160::default(),323 value: amount.into(),324 }325 .to_log(collection_id_to_address(collection.id)),326 );327 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(328 collection.id,329 TokenId::default(),330 owner.clone(),331 amount,332 ));333 Ok(())334 }335336 /// Burns the specified amount of the token.337 pub fn burn_foreign(338 collection: &FungibleHandle<T>,339 owner: &T::CrossAccountId,340 amount: u128,341 ) -> DispatchResult {342 let total_supply = <TotalSupply<T>>::get(collection.id)343 .checked_sub(amount)344 .ok_or(<CommonError<T>>::TokenValueTooLow)?;345346 let balance = <Balance<T>>::get((collection.id, owner))347 .checked_sub(amount)348 .ok_or(<CommonError<T>>::TokenValueTooLow)?;349 // =========350351 if balance == 0 {352 <Balance<T>>::remove((collection.id, owner));353 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());354 } else {355 <Balance<T>>::insert((collection.id, owner), balance);356 }357 <TotalSupply<T>>::insert(collection.id, total_supply);358359 <PalletEvm<T>>::deposit_log(360 ERC20Events::Transfer {361 from: *owner.as_eth(),362 to: H160::default(),363 value: amount.into(),364 }365 .to_log(collection_id_to_address(collection.id)),366 );367 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(368 collection.id,369 TokenId::default(),370 owner.clone(),371 amount,372 ));373 Ok(())374 }375376 /// Transfers the specified amount of tokens. Will check that377 /// the transfer is allowed for the token.378 ///379 /// - `from`: Owner of tokens to transfer.380 /// - `to`: Recepient of transfered tokens.381 /// - `amount`: Amount of tokens to transfer.382 /// - `collection`: Collection that contains the token383 pub fn transfer(384 collection: &FungibleHandle<T>,385 from: &T::CrossAccountId,386 to: &T::CrossAccountId,387 amount: u128,388 nesting_budget: &dyn Budget,389 ) -> DispatchResult {390 ensure!(391 collection.limits.transfers_enabled(),392 <CommonError<T>>::TransferNotAllowed,393 );394395 if collection.permissions.access() == AccessMode::AllowList {396 collection.check_allowlist(from)?;397 collection.check_allowlist(to)?;398 }399 <PalletCommon<T>>::ensure_correct_receiver(to)?;400401 let balance_from = <Balance<T>>::get((collection.id, from))402 .checked_sub(amount)403 .ok_or(<CommonError<T>>::TokenValueTooLow)?;404 let balance_to = if from != to && amount != 0 {405 Some(406 <Balance<T>>::get((collection.id, to))407 .checked_add(amount)408 .ok_or(ArithmeticError::Overflow)?,409 )410 } else {411 None412 };413414 // =========415416 if let Some(balance_to) = balance_to {417 // from != to && amount != 0418419 <PalletStructure<T>>::nest_if_sent_to_token(420 from.clone(),421 to,422 collection.id,423 TokenId::default(),424 nesting_budget,425 )?;426427 if balance_from == 0 {428 <Balance<T>>::remove((collection.id, from));429 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());430 } else {431 <Balance<T>>::insert((collection.id, from), balance_from);432 }433 <Balance<T>>::insert((collection.id, to), balance_to);434 }435436 <PalletEvm<T>>::deposit_log(437 ERC20Events::Transfer {438 from: *from.as_eth(),439 to: *to.as_eth(),440 value: amount.into(),441 }442 .to_log(collection_id_to_address(collection.id)),443 );444 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(445 collection.id,446 TokenId::default(),447 from.clone(),448 to.clone(),449 amount,450 ));451 Ok(())452 }453454 /// Minting tokens for multiple IDs.455 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]456 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]457 pub fn create_multiple_items_common(458 collection: &FungibleHandle<T>,459 sender: &T::CrossAccountId,460 data: BTreeMap<T::CrossAccountId, u128>,461 nesting_budget: &dyn Budget,462 ) -> DispatchResult {463 let total_supply = data464 .iter()465 .map(|(_, v)| *v)466 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {467 acc.checked_add(v)468 })469 .ok_or(ArithmeticError::Overflow)?;470471 for (to, _) in data.iter() {472 <PalletStructure<T>>::check_nesting(473 sender.clone(),474 to,475 collection.id,476 TokenId::default(),477 nesting_budget,478 )?;479 }480481 let updated_balances = data482 .into_iter()483 .map(|(user, amount)| {484 let updated_balance = <Balance<T>>::get((collection.id, &user))485 .checked_add(amount)486 .ok_or(ArithmeticError::Overflow)?;487 Ok((user, amount, updated_balance))488 })489 .collect::<Result<Vec<_>, DispatchError>>()?;490491 // =========492493 <TotalSupply<T>>::insert(collection.id, total_supply);494 for (user, amount, updated_balance) in updated_balances {495 <Balance<T>>::insert((collection.id, &user), updated_balance);496 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(497 &user,498 collection.id,499 TokenId::default(),500 );501 <PalletEvm<T>>::deposit_log(502 ERC20Events::Transfer {503 from: H160::default(),504 to: *user.as_eth(),505 value: amount.into(),506 }507 .to_log(collection_id_to_address(collection.id)),508 );509 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(510 collection.id,511 TokenId::default(),512 user.clone(),513 amount,514 ));515 }516517 Ok(())518 }519520 /// Minting tokens for multiple IDs.521 /// See [`create_item`][`Pallet::create_item`] for more details.522 pub fn create_multiple_items(523 collection: &FungibleHandle<T>,524 sender: &T::CrossAccountId,525 data: BTreeMap<T::CrossAccountId, u128>,526 nesting_budget: &dyn Budget,527 ) -> DispatchResult {528 // Foreign collection check529 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);530531 if !collection.is_owner_or_admin(sender) {532 ensure!(533 collection.permissions.mint_mode(),534 <CommonError<T>>::PublicMintingNotAllowed535 );536 collection.check_allowlist(sender)?;537538 for (owner, _) in data.iter() {539 collection.check_allowlist(owner)?;540 }541 }542543 Self::create_multiple_items_common(collection, sender, data, nesting_budget)544 }545546 /// Minting tokens for multiple IDs.547 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.548 pub fn create_multiple_items_foreign(549 collection: &FungibleHandle<T>,550 sender: &T::CrossAccountId,551 data: BTreeMap<T::CrossAccountId, u128>,552 nesting_budget: &dyn Budget,553 ) -> DispatchResult {554 Self::create_multiple_items_common(collection, sender, data, nesting_budget)555 }556557 fn set_allowance_unchecked(558 collection: &FungibleHandle<T>,559 owner: &T::CrossAccountId,560 spender: &T::CrossAccountId,561 amount: u128,562 ) {563 if amount == 0 {564 <Allowance<T>>::remove((collection.id, owner, spender));565 } else {566 <Allowance<T>>::insert((collection.id, owner, spender), amount);567 }568569 <PalletEvm<T>>::deposit_log(570 ERC20Events::Approval {571 owner: *owner.as_eth(),572 spender: *spender.as_eth(),573 value: amount.into(),574 }575 .to_log(collection_id_to_address(collection.id)),576 );577 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(578 collection.id,579 TokenId(0),580 owner.clone(),581 spender.clone(),582 amount,583 ));584 }585586 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.587 ///588 /// - `collection`: Collection that contains the token589 /// - `owner`: Owner of tokens that sets the allowance.590 /// - `spender`: Recipient of the allowance rights.591 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.592 pub fn set_allowance(593 collection: &FungibleHandle<T>,594 owner: &T::CrossAccountId,595 spender: &T::CrossAccountId,596 amount: u128,597 ) -> DispatchResult {598 if collection.permissions.access() == AccessMode::AllowList {599 collection.check_allowlist(owner)?;600 collection.check_allowlist(spender)?;601 }602603 if <Balance<T>>::get((collection.id, owner)) < amount {604 ensure!(605 collection.ignores_owned_amount(owner),606 <CommonError<T>>::CantApproveMoreThanOwned607 );608 }609610 // =========611612 Self::set_allowance_unchecked(collection, owner, spender, amount);613 Ok(())614 }615616 /// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.617 ///618 /// - `collection`: Collection that contains the token619 /// - `sender`: Owner of tokens that sets the allowance.620 /// - `from`: Owner's eth mirror.621 /// - `to`: Recipient of the allowance rights.622 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.623 pub fn set_allowance_from(624 collection: &FungibleHandle<T>,625 sender: &T::CrossAccountId,626 from: &T::CrossAccountId,627 to: &T::CrossAccountId,628 amount: u128,629 ) -> DispatchResult {630 if collection.permissions.access() == AccessMode::AllowList {631 collection.check_allowlist(sender)?;632 collection.check_allowlist(from)?;633 collection.check_allowlist(to)?;634 }635636 ensure!(637 sender.conv_eq(from),638 <CommonError<T>>::AddressIsNotEthMirror639 );640641 if <Balance<T>>::get((collection.id, from)) < amount {642 ensure!(643 collection.limits.owner_can_transfer()644 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),645 <CommonError<T>>::CantApproveMoreThanOwned646 );647 }648649 // =========650651 Self::set_allowance_unchecked(collection, from, to, amount);652 Ok(())653 }654655 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.656 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.657 ///658 /// - `collection`: Collection that contains the token.659 /// - `spender`: CrossAccountId who has the allowance rights.660 /// - `from`: The owner of the tokens who sets the allowance.661 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.662 fn check_allowed(663 collection: &FungibleHandle<T>,664 spender: &T::CrossAccountId,665 from: &T::CrossAccountId,666 amount: u128,667 nesting_budget: &dyn Budget,668 ) -> Result<Option<u128>, DispatchError> {669 if spender.conv_eq(from) {670 return Ok(None);671 }672 if collection.permissions.access() == AccessMode::AllowList {673 // `from`, `to` checked in [`transfer`]674 collection.check_allowlist(spender)?;675 }676 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {677 // TODO: should collection owner be allowed to perform this transfer?678 ensure!(679 <PalletStructure<T>>::check_indirectly_owned(680 spender.clone(),681 source.0,682 source.1,683 None,684 nesting_budget685 )?,686 <CommonError<T>>::ApprovedValueTooLow,687 );688 return Ok(None);689 }690 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);691 if allowance.is_none() {692 ensure!(693 collection.ignores_allowance(spender),694 <CommonError<T>>::ApprovedValueTooLow695 );696 }697698 Ok(allowance)699 }700701 /// Transfer fungible tokens from one account to another.702 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.703 /// The owner should set allowance for the spender to transfer pieces.704 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.705706 pub fn transfer_from(707 collection: &FungibleHandle<T>,708 spender: &T::CrossAccountId,709 from: &T::CrossAccountId,710 to: &T::CrossAccountId,711 amount: u128,712 nesting_budget: &dyn Budget,713 ) -> DispatchResult {714 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;715716 // =========717718 Self::transfer(collection, from, to, amount, nesting_budget)?;719 if let Some(allowance) = allowance {720 Self::set_allowance_unchecked(collection, from, spender, allowance);721 }722 Ok(())723 }724725 /// Burn fungible tokens from the account.726 ///727 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should728 /// set allowance for the spender to burn tokens.729 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.730 pub fn burn_from(731 collection: &FungibleHandle<T>,732 spender: &T::CrossAccountId,733 from: &T::CrossAccountId,734 amount: u128,735 nesting_budget: &dyn Budget,736 ) -> DispatchResult {737 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;738739 // =========740741 Self::burn(collection, from, amount)?;742 if let Some(allowance) = allowance {743 Self::set_allowance_unchecked(collection, from, spender, allowance);744 }745 Ok(())746 }747748 /// Creates fungible token.749 ///750 /// The sender should be the owner/admin of the collection or collection should be configured751 /// to allow public minting.752 ///753 /// - `data`: Contains user who will become the owners of the tokens and amount754 /// of tokens he will receive.755 pub fn create_item(756 collection: &FungibleHandle<T>,757 sender: &T::CrossAccountId,758 data: CreateItemData<T>,759 nesting_budget: &dyn Budget,760 ) -> DispatchResult {761 Self::create_multiple_items(762 collection,763 sender,764 [(data.0, data.1)].into_iter().collect(),765 nesting_budget,766 )767 }768769 /// Creates fungible token.770 ///771 /// - `data`: Contains user who will become the owners of the tokens and amount772 /// of tokens he will receive.773 pub fn create_item_foreign(774 collection: &FungibleHandle<T>,775 sender: &T::CrossAccountId,776 data: CreateItemData<T>,777 nesting_budget: &dyn Budget,778 ) -> DispatchResult {779 Self::create_multiple_items_foreign(780 collection,781 sender,782 [(data.0, data.1)].into_iter().collect(),783 nesting_budget,784 )785 }786787 /// Returns 10 tokens owners in no particular order788 ///789 /// There is no direct way to get token holders in ascending order,790 /// since `iter_prefix` returns values in no particular order.791 /// Therefore, getting the 10 largest holders with a large value of holders792 /// can lead to impact memory allocation + sorting with `n * log (n)`.793 pub fn token_owners(794 collection: CollectionId,795 _token: TokenId,796 ) -> Option<Vec<T::CrossAccountId>> {797 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))798 .map(|(owner, _amount)| owner)799 .take(10)800 .collect();801802 if res.is_empty() {803 None804 } else {805 Some(res)806 }807 }808}pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -1196,7 +1196,7 @@
}
ensure!(
- *sender.as_eth() == *from.as_eth(),
+ sender.conv_eq(from),
<CommonError<T>>::AddressIsNotEthMirror
);
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1124,7 +1124,7 @@
<PalletCommon<T>>::ensure_correct_receiver(to)?;
ensure!(
- *sender.as_eth() == *from.as_eth(),
+ sender.conv_eq(from),
<CommonError<T>>::AddressIsNotEthMirror
);