difftreelog
fix PR
in: master
4 files changed
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -6,7 +6,7 @@
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
-// Unique Network is disaddress: tod in the hope that it will be useful,
+// Unique Network is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
@@ -28,6 +28,7 @@
use pallet_common::{
CollectionHandle,
erc::{CommonEvmHandler, PrecompileResult, CollectionCall},
+ eth::CrossAddress,
};
use sp_std::vec::Vec;
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
@@ -172,11 +173,7 @@
/// @param owner crossAddress The address which owns the funds.
/// @param spender crossAddress The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
- fn allowance_cross(
- &self,
- owner: pallet_common::eth::CrossAddress,
- spender: pallet_common::eth::CrossAddress,
- ) -> Result<U256> {
+ fn allowance_cross(&self, owner: CrossAddress, spender: CrossAddress) -> Result<U256> {
let owner = owner.into_sub_cross_account::<T>()?;
let spender = spender.into_sub_cross_account::<T>()?;
@@ -191,12 +188,7 @@
}
#[weight(<SelfWeightOf<T>>::create_item())]
- fn mint_cross(
- &mut self,
- caller: Caller,
- to: pallet_common::eth::CrossAddress,
- amount: U256,
- ) -> Result<bool> {
+ fn mint_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = to.into_sub_cross_account::<T>()?;
let amount = amount.try_into().map_err(|_| "amount overflow")?;
@@ -212,7 +204,7 @@
fn approve_cross(
&mut self,
caller: Caller,
- spender: pallet_common::eth::CrossAddress,
+ spender: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -253,7 +245,7 @@
fn burn_from_cross(
&mut self,
caller: Caller,
- from: pallet_common::eth::CrossAddress,
+ from: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -292,12 +284,7 @@
}
#[weight(<SelfWeightOf<T>>::transfer())]
- fn transfer_cross(
- &mut self,
- caller: Caller,
- to: pallet_common::eth::CrossAddress,
- amount: U256,
- ) -> Result<bool> {
+ fn transfer_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = to.into_sub_cross_account::<T>()?;
let amount = amount.try_into().map_err(|_| "amount overflow")?;
@@ -313,8 +300,8 @@
fn transfer_from_cross(
&mut self,
caller: Caller,
- from: pallet_common::eth::CrossAddress,
- to: pallet_common::eth::CrossAddress,
+ from: CrossAddress,
+ to: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
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.into_iter())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(279 collection,280 sender,281 property_keys.into_iter(),282 )283 }284285 /// Checks if collection has tokens. Return `true` if it has.286 fn collection_has_tokens(collection_id: CollectionId) -> bool {287 <TotalSupply<T>>::get(collection_id) != 0288 }289290 /// Burns the specified amount of the token. If the token balance291 /// or total supply is less than the given value,292 /// it will return [DispatchError].293 pub fn burn(294 collection: &FungibleHandle<T>,295 owner: &T::CrossAccountId,296 amount: u128,297 ) -> DispatchResult {298 let total_supply = <TotalSupply<T>>::get(collection.id)299 .checked_sub(amount)300 .ok_or(<CommonError<T>>::TokenValueTooLow)?;301302 let balance = <Balance<T>>::get((collection.id, owner))303 .checked_sub(amount)304 .ok_or(<CommonError<T>>::TokenValueTooLow)?;305306 // Foreign collection check307 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);308309 if collection.permissions.access() == AccessMode::AllowList {310 collection.check_allowlist(owner)?;311 }312313 // =========314315 if balance == 0 {316 <Balance<T>>::remove((collection.id, owner));317 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());318 } else {319 <Balance<T>>::insert((collection.id, owner), balance);320 }321 <TotalSupply<T>>::insert(collection.id, total_supply);322323 <PalletEvm<T>>::deposit_log(324 ERC20Events::Transfer {325 from: *owner.as_eth(),326 to: H160::default(),327 value: amount.into(),328 }329 .to_log(collection_id_to_address(collection.id)),330 );331 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(332 collection.id,333 TokenId::default(),334 owner.clone(),335 amount,336 ));337 Ok(())338 }339340 /// Burns the specified amount of the token.341 pub fn burn_foreign(342 collection: &FungibleHandle<T>,343 owner: &T::CrossAccountId,344 amount: u128,345 ) -> DispatchResult {346 let total_supply = <TotalSupply<T>>::get(collection.id)347 .checked_sub(amount)348 .ok_or(<CommonError<T>>::TokenValueTooLow)?;349350 let balance = <Balance<T>>::get((collection.id, owner))351 .checked_sub(amount)352 .ok_or(<CommonError<T>>::TokenValueTooLow)?;353 // =========354355 if balance == 0 {356 <Balance<T>>::remove((collection.id, owner));357 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());358 } else {359 <Balance<T>>::insert((collection.id, owner), balance);360 }361 <TotalSupply<T>>::insert(collection.id, total_supply);362363 <PalletEvm<T>>::deposit_log(364 ERC20Events::Transfer {365 from: *owner.as_eth(),366 to: H160::default(),367 value: amount.into(),368 }369 .to_log(collection_id_to_address(collection.id)),370 );371 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(372 collection.id,373 TokenId::default(),374 owner.clone(),375 amount,376 ));377 Ok(())378 }379380 /// Transfers the specified amount of tokens. Will check that381 /// the transfer is allowed for the token.382 ///383 /// - `from`: Owner of tokens to transfer.384 /// - `to`: Recepient of transfered tokens.385 /// - `amount`: Amount of tokens to transfer.386 /// - `collection`: Collection that contains the token387 pub fn transfer(388 collection: &FungibleHandle<T>,389 from: &T::CrossAccountId,390 to: &T::CrossAccountId,391 amount: u128,392 nesting_budget: &dyn Budget,393 ) -> DispatchResult {394 ensure!(395 collection.limits.transfers_enabled(),396 <CommonError<T>>::TransferNotAllowed,397 );398399 if collection.permissions.access() == AccessMode::AllowList {400 collection.check_allowlist(from)?;401 collection.check_allowlist(to)?;402 }403 <PalletCommon<T>>::ensure_correct_receiver(to)?;404405 let balance_from = <Balance<T>>::get((collection.id, from))406 .checked_sub(amount)407 .ok_or(<CommonError<T>>::TokenValueTooLow)?;408 let balance_to = if from != to && amount != 0 {409 Some(410 <Balance<T>>::get((collection.id, to))411 .checked_add(amount)412 .ok_or(ArithmeticError::Overflow)?,413 )414 } else {415 None416 };417418 // =========419420 if let Some(balance_to) = balance_to {421 // from != to && amount != 0422423 <PalletStructure<T>>::nest_if_sent_to_token(424 from.clone(),425 to,426 collection.id,427 TokenId::default(),428 nesting_budget,429 )?;430431 if balance_from == 0 {432 <Balance<T>>::remove((collection.id, from));433 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());434 } else {435 <Balance<T>>::insert((collection.id, from), balance_from);436 }437 <Balance<T>>::insert((collection.id, to), balance_to);438 }439440 <PalletEvm<T>>::deposit_log(441 ERC20Events::Transfer {442 from: *from.as_eth(),443 to: *to.as_eth(),444 value: amount.into(),445 }446 .to_log(collection_id_to_address(collection.id)),447 );448 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(449 collection.id,450 TokenId::default(),451 from.clone(),452 to.clone(),453 amount,454 ));455 Ok(())456 }457458 /// Minting tokens for multiple IDs.459 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]460 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]461 pub fn create_multiple_items_common(462 collection: &FungibleHandle<T>,463 sender: &T::CrossAccountId,464 data: BTreeMap<T::CrossAccountId, u128>,465 nesting_budget: &dyn Budget,466 ) -> DispatchResult {467 let total_supply = data468 .iter()469 .map(|(_, v)| *v)470 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {471 acc.checked_add(v)472 })473 .ok_or(ArithmeticError::Overflow)?;474475 for (to, _) in data.iter() {476 <PalletStructure<T>>::check_nesting(477 sender.clone(),478 to,479 collection.id,480 TokenId::default(),481 nesting_budget,482 )?;483 }484485 let updated_balances = data486 .into_iter()487 .map(|(user, amount)| {488 let updated_balance = <Balance<T>>::get((collection.id, &user))489 .checked_add(amount)490 .ok_or(ArithmeticError::Overflow)?;491 Ok((user, amount, updated_balance))492 })493 .collect::<Result<Vec<_>, DispatchError>>()?;494495 // =========496497 <TotalSupply<T>>::insert(collection.id, total_supply);498 for (user, amount, updated_balance) in updated_balances {499 <Balance<T>>::insert((collection.id, &user), updated_balance);500 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(501 &user,502 collection.id,503 TokenId::default(),504 );505 <PalletEvm<T>>::deposit_log(506 ERC20Events::Transfer {507 from: H160::default(),508 to: *user.as_eth(),509 value: amount.into(),510 }511 .to_log(collection_id_to_address(collection.id)),512 );513 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(514 collection.id,515 TokenId::default(),516 user.clone(),517 amount,518 ));519 }520521 Ok(())522 }523524 /// Minting tokens for multiple IDs.525 /// See [`create_item`][`Pallet::create_item`] for more details.526 pub fn create_multiple_items(527 collection: &FungibleHandle<T>,528 sender: &T::CrossAccountId,529 data: BTreeMap<T::CrossAccountId, u128>,530 nesting_budget: &dyn Budget,531 ) -> DispatchResult {532 // Foreign collection check533 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);534535 if !collection.is_owner_or_admin(sender) {536 ensure!(537 collection.permissions.mint_mode(),538 <CommonError<T>>::PublicMintingNotAllowed539 );540 collection.check_allowlist(sender)?;541542 for (owner, _) in data.iter() {543 collection.check_allowlist(owner)?;544 }545 }546547 Self::create_multiple_items_common(collection, sender, data, nesting_budget)548 }549550 /// Minting tokens for multiple IDs.551 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.552 pub fn create_multiple_items_foreign(553 collection: &FungibleHandle<T>,554 sender: &T::CrossAccountId,555 data: BTreeMap<T::CrossAccountId, u128>,556 nesting_budget: &dyn Budget,557 ) -> DispatchResult {558 Self::create_multiple_items_common(collection, sender, data, nesting_budget)559 }560561 fn set_allowance_unchecked(562 collection: &FungibleHandle<T>,563 owner: &T::CrossAccountId,564 spender: &T::CrossAccountId,565 amount: u128,566 ) {567 if amount == 0 {568 <Allowance<T>>::remove((collection.id, owner, spender));569 } else {570 <Allowance<T>>::insert((collection.id, owner, spender), amount);571 }572573 <PalletEvm<T>>::deposit_log(574 ERC20Events::Approval {575 owner: *owner.as_eth(),576 spender: *spender.as_eth(),577 value: amount.into(),578 }579 .to_log(collection_id_to_address(collection.id)),580 );581 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(582 collection.id,583 TokenId(0),584 owner.clone(),585 spender.clone(),586 amount,587 ));588 }589590 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.591 ///592 /// - `collection`: Collection that contains the token593 /// - `owner`: Owner of tokens that sets the allowance.594 /// - `spender`: Recipient of the allowance rights.595 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.596 pub fn set_allowance(597 collection: &FungibleHandle<T>,598 owner: &T::CrossAccountId,599 spender: &T::CrossAccountId,600 amount: u128,601 ) -> DispatchResult {602 if collection.permissions.access() == AccessMode::AllowList {603 collection.check_allowlist(owner)?;604 collection.check_allowlist(spender)?;605 }606607 if <Balance<T>>::get((collection.id, owner)) < amount {608 ensure!(609 collection.ignores_owned_amount(owner),610 <CommonError<T>>::CantApproveMoreThanOwned611 );612 }613614 // =========615616 Self::set_allowance_unchecked(collection, owner, spender, amount);617 Ok(())618 }619620 /// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.621 ///622 /// - `collection`: Collection that contains the token623 /// - `sender`: Owner of tokens that sets the allowance.624 /// - `from`: Owner's eth mirror.625 /// - `to`: Recipient of the allowance rights.626 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.627 pub fn set_allowance_from(628 collection: &FungibleHandle<T>,629 sender: &T::CrossAccountId,630 from: &T::CrossAccountId,631 to: &T::CrossAccountId,632 amount: u128,633 ) -> DispatchResult {634 if collection.permissions.access() == AccessMode::AllowList {635 collection.check_allowlist(sender)?;636 collection.check_allowlist(from)?;637 collection.check_allowlist(to)?;638 }639640 ensure!(641 sender.conv_eq(from),642 <CommonError<T>>::AddressIsNotEthMirror643 );644645 if <Balance<T>>::get((collection.id, from)) < amount {646 ensure!(647 collection.limits.owner_can_transfer()648 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),649 <CommonError<T>>::CantApproveMoreThanOwned650 );651 }652653 // =========654655 Self::set_allowance_unchecked(collection, from, to, amount);656 Ok(())657 }658659 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.660 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.661 ///662 /// - `collection`: Collection that contains the token.663 /// - `spender`: CrossAccountId who has the allowance rights.664 /// - `from`: The owner of the tokens who sets the allowance.665 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.666 fn check_allowed(667 collection: &FungibleHandle<T>,668 spender: &T::CrossAccountId,669 from: &T::CrossAccountId,670 amount: u128,671 nesting_budget: &dyn Budget,672 ) -> Result<Option<u128>, DispatchError> {673 if spender.conv_eq(from) {674 return Ok(None);675 }676 if collection.permissions.access() == AccessMode::AllowList {677 // `from`, `to` checked in [`transfer`]678 collection.check_allowlist(spender)?;679 }680681 if collection.ignores_token_restrictions(spender) {682 return Ok(Self::compute_allowance_decrease(683 collection, from, spender, amount,684 ));685 }686687 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {688 ensure!(689 <PalletStructure<T>>::check_indirectly_owned(690 spender.clone(),691 source.0,692 source.1,693 None,694 nesting_budget695 )?,696 <CommonError<T>>::ApprovedValueTooLow,697 );698 return Ok(None);699 }700701 let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);702 ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);703704 Ok(allowance)705 }706707 /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.708 /// Otherwise, it returns `None`.709 fn compute_allowance_decrease(710 collection: &FungibleHandle<T>,711 from: &T::CrossAccountId,712 spender: &T::CrossAccountId,713 amount: u128,714 ) -> Option<u128> {715 <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)716 }717718 /// Transfer fungible tokens from one account to another.719 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.720 /// The owner should set allowance for the spender to transfer pieces.721 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.722723 pub fn transfer_from(724 collection: &FungibleHandle<T>,725 spender: &T::CrossAccountId,726 from: &T::CrossAccountId,727 to: &T::CrossAccountId,728 amount: u128,729 nesting_budget: &dyn Budget,730 ) -> DispatchResult {731 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;732733 // =========734735 Self::transfer(collection, from, to, amount, nesting_budget)?;736 if let Some(allowance) = allowance {737 Self::set_allowance_unchecked(collection, from, spender, allowance);738 }739 Ok(())740 }741742 /// Burn fungible tokens from the account.743 ///744 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should745 /// set allowance for the spender to burn tokens.746 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.747 pub fn burn_from(748 collection: &FungibleHandle<T>,749 spender: &T::CrossAccountId,750 from: &T::CrossAccountId,751 amount: u128,752 nesting_budget: &dyn Budget,753 ) -> DispatchResult {754 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;755756 // =========757758 Self::burn(collection, from, amount)?;759 if let Some(allowance) = allowance {760 Self::set_allowance_unchecked(collection, from, spender, allowance);761 }762 Ok(())763 }764765 /// Creates fungible token.766 ///767 /// The sender should be the owner/admin of the collection or collection should be configured768 /// to allow public minting.769 ///770 /// - `data`: Contains user who will become the owners of the tokens and amount771 /// of tokens he will receive.772 pub fn create_item(773 collection: &FungibleHandle<T>,774 sender: &T::CrossAccountId,775 data: CreateItemData<T>,776 nesting_budget: &dyn Budget,777 ) -> DispatchResult {778 Self::create_multiple_items(779 collection,780 sender,781 [(data.0, data.1)].into_iter().collect(),782 nesting_budget,783 )784 }785786 /// Creates fungible token.787 ///788 /// - `data`: Contains user who will become the owners of the tokens and amount789 /// of tokens he will receive.790 pub fn create_item_foreign(791 collection: &FungibleHandle<T>,792 sender: &T::CrossAccountId,793 data: CreateItemData<T>,794 nesting_budget: &dyn Budget,795 ) -> DispatchResult {796 Self::create_multiple_items_foreign(797 collection,798 sender,799 [(data.0, data.1)].into_iter().collect(),800 nesting_budget,801 )802 }803804 /// Returns 10 tokens owners in no particular order805 ///806 /// There is no direct way to get token holders in ascending order,807 /// since `iter_prefix` returns values in no particular order.808 /// Therefore, getting the 10 largest holders with a large value of holders809 /// can lead to impact memory allocation + sorting with `n * log (n)`.810 pub fn token_owners(811 collection: CollectionId,812 _token: TokenId,813 ) -> Option<Vec<T::CrossAccountId>> {814 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))815 .map(|(owner, _amount)| owner)816 .take(10)817 .collect();818819 if res.is_empty() {820 None821 } else {822 Some(res)823 }824 }825}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>, // Owner169 Key<Blake2_128Concat, T::CrossAccountId>, // Spender170 ),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.into_iter())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(279 collection,280 sender,281 property_keys.into_iter(),282 )283 }284285 /// Checks if collection has tokens. Return `true` if it has.286 fn collection_has_tokens(collection_id: CollectionId) -> bool {287 <TotalSupply<T>>::get(collection_id) != 0288 }289290 /// Burns the specified amount of the token. If the token balance291 /// or total supply is less than the given value,292 /// it will return [DispatchError].293 pub fn burn(294 collection: &FungibleHandle<T>,295 owner: &T::CrossAccountId,296 amount: u128,297 ) -> DispatchResult {298 let total_supply = <TotalSupply<T>>::get(collection.id)299 .checked_sub(amount)300 .ok_or(<CommonError<T>>::TokenValueTooLow)?;301302 let balance = <Balance<T>>::get((collection.id, owner))303 .checked_sub(amount)304 .ok_or(<CommonError<T>>::TokenValueTooLow)?;305306 // Foreign collection check307 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);308309 if collection.permissions.access() == AccessMode::AllowList {310 collection.check_allowlist(owner)?;311 }312313 // =========314315 if balance == 0 {316 <Balance<T>>::remove((collection.id, owner));317 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());318 } else {319 <Balance<T>>::insert((collection.id, owner), balance);320 }321 <TotalSupply<T>>::insert(collection.id, total_supply);322323 <PalletEvm<T>>::deposit_log(324 ERC20Events::Transfer {325 from: *owner.as_eth(),326 to: H160::default(),327 value: amount.into(),328 }329 .to_log(collection_id_to_address(collection.id)),330 );331 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(332 collection.id,333 TokenId::default(),334 owner.clone(),335 amount,336 ));337 Ok(())338 }339340 /// Burns the specified amount of the token.341 pub fn burn_foreign(342 collection: &FungibleHandle<T>,343 owner: &T::CrossAccountId,344 amount: u128,345 ) -> DispatchResult {346 let total_supply = <TotalSupply<T>>::get(collection.id)347 .checked_sub(amount)348 .ok_or(<CommonError<T>>::TokenValueTooLow)?;349350 let balance = <Balance<T>>::get((collection.id, owner))351 .checked_sub(amount)352 .ok_or(<CommonError<T>>::TokenValueTooLow)?;353 // =========354355 if balance == 0 {356 <Balance<T>>::remove((collection.id, owner));357 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());358 } else {359 <Balance<T>>::insert((collection.id, owner), balance);360 }361 <TotalSupply<T>>::insert(collection.id, total_supply);362363 <PalletEvm<T>>::deposit_log(364 ERC20Events::Transfer {365 from: *owner.as_eth(),366 to: H160::default(),367 value: amount.into(),368 }369 .to_log(collection_id_to_address(collection.id)),370 );371 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(372 collection.id,373 TokenId::default(),374 owner.clone(),375 amount,376 ));377 Ok(())378 }379380 /// Transfers the specified amount of tokens. Will check that381 /// the transfer is allowed for the token.382 ///383 /// - `from`: Owner of tokens to transfer.384 /// - `to`: Recepient of transfered tokens.385 /// - `amount`: Amount of tokens to transfer.386 /// - `collection`: Collection that contains the token387 pub fn transfer(388 collection: &FungibleHandle<T>,389 from: &T::CrossAccountId,390 to: &T::CrossAccountId,391 amount: u128,392 nesting_budget: &dyn Budget,393 ) -> DispatchResult {394 ensure!(395 collection.limits.transfers_enabled(),396 <CommonError<T>>::TransferNotAllowed,397 );398399 if collection.permissions.access() == AccessMode::AllowList {400 collection.check_allowlist(from)?;401 collection.check_allowlist(to)?;402 }403 <PalletCommon<T>>::ensure_correct_receiver(to)?;404405 let balance_from = <Balance<T>>::get((collection.id, from))406 .checked_sub(amount)407 .ok_or(<CommonError<T>>::TokenValueTooLow)?;408 let balance_to = if from != to && amount != 0 {409 Some(410 <Balance<T>>::get((collection.id, to))411 .checked_add(amount)412 .ok_or(ArithmeticError::Overflow)?,413 )414 } else {415 None416 };417418 // =========419420 if let Some(balance_to) = balance_to {421 // from != to && amount != 0422423 <PalletStructure<T>>::nest_if_sent_to_token(424 from.clone(),425 to,426 collection.id,427 TokenId::default(),428 nesting_budget,429 )?;430431 if balance_from == 0 {432 <Balance<T>>::remove((collection.id, from));433 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());434 } else {435 <Balance<T>>::insert((collection.id, from), balance_from);436 }437 <Balance<T>>::insert((collection.id, to), balance_to);438 }439440 <PalletEvm<T>>::deposit_log(441 ERC20Events::Transfer {442 from: *from.as_eth(),443 to: *to.as_eth(),444 value: amount.into(),445 }446 .to_log(collection_id_to_address(collection.id)),447 );448 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(449 collection.id,450 TokenId::default(),451 from.clone(),452 to.clone(),453 amount,454 ));455 Ok(())456 }457458 /// Minting tokens for multiple IDs.459 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]460 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]461 pub fn create_multiple_items_common(462 collection: &FungibleHandle<T>,463 sender: &T::CrossAccountId,464 data: BTreeMap<T::CrossAccountId, u128>,465 nesting_budget: &dyn Budget,466 ) -> DispatchResult {467 let total_supply = data468 .iter()469 .map(|(_, v)| *v)470 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {471 acc.checked_add(v)472 })473 .ok_or(ArithmeticError::Overflow)?;474475 for (to, _) in data.iter() {476 <PalletStructure<T>>::check_nesting(477 sender.clone(),478 to,479 collection.id,480 TokenId::default(),481 nesting_budget,482 )?;483 }484485 let updated_balances = data486 .into_iter()487 .map(|(user, amount)| {488 let updated_balance = <Balance<T>>::get((collection.id, &user))489 .checked_add(amount)490 .ok_or(ArithmeticError::Overflow)?;491 Ok((user, amount, updated_balance))492 })493 .collect::<Result<Vec<_>, DispatchError>>()?;494495 // =========496497 <TotalSupply<T>>::insert(collection.id, total_supply);498 for (user, amount, updated_balance) in updated_balances {499 <Balance<T>>::insert((collection.id, &user), updated_balance);500 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(501 &user,502 collection.id,503 TokenId::default(),504 );505 <PalletEvm<T>>::deposit_log(506 ERC20Events::Transfer {507 from: H160::default(),508 to: *user.as_eth(),509 value: amount.into(),510 }511 .to_log(collection_id_to_address(collection.id)),512 );513 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(514 collection.id,515 TokenId::default(),516 user.clone(),517 amount,518 ));519 }520521 Ok(())522 }523524 /// Minting tokens for multiple IDs.525 /// See [`create_item`][`Pallet::create_item`] for more details.526 pub fn create_multiple_items(527 collection: &FungibleHandle<T>,528 sender: &T::CrossAccountId,529 data: BTreeMap<T::CrossAccountId, u128>,530 nesting_budget: &dyn Budget,531 ) -> DispatchResult {532 // Foreign collection check533 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);534535 if !collection.is_owner_or_admin(sender) {536 ensure!(537 collection.permissions.mint_mode(),538 <CommonError<T>>::PublicMintingNotAllowed539 );540 collection.check_allowlist(sender)?;541542 for (owner, _) in data.iter() {543 collection.check_allowlist(owner)?;544 }545 }546547 Self::create_multiple_items_common(collection, sender, data, nesting_budget)548 }549550 /// Minting tokens for multiple IDs.551 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.552 pub fn create_multiple_items_foreign(553 collection: &FungibleHandle<T>,554 sender: &T::CrossAccountId,555 data: BTreeMap<T::CrossAccountId, u128>,556 nesting_budget: &dyn Budget,557 ) -> DispatchResult {558 Self::create_multiple_items_common(collection, sender, data, nesting_budget)559 }560561 fn set_allowance_unchecked(562 collection: &FungibleHandle<T>,563 owner: &T::CrossAccountId,564 spender: &T::CrossAccountId,565 amount: u128,566 ) {567 if amount == 0 {568 <Allowance<T>>::remove((collection.id, owner, spender));569 } else {570 <Allowance<T>>::insert((collection.id, owner, spender), amount);571 }572573 <PalletEvm<T>>::deposit_log(574 ERC20Events::Approval {575 owner: *owner.as_eth(),576 spender: *spender.as_eth(),577 value: amount.into(),578 }579 .to_log(collection_id_to_address(collection.id)),580 );581 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(582 collection.id,583 TokenId(0),584 owner.clone(),585 spender.clone(),586 amount,587 ));588 }589590 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.591 ///592 /// - `collection`: Collection that contains the token593 /// - `owner`: Owner of tokens that sets the allowance.594 /// - `spender`: Recipient of the allowance rights.595 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.596 pub fn set_allowance(597 collection: &FungibleHandle<T>,598 owner: &T::CrossAccountId,599 spender: &T::CrossAccountId,600 amount: u128,601 ) -> DispatchResult {602 if collection.permissions.access() == AccessMode::AllowList {603 collection.check_allowlist(owner)?;604 collection.check_allowlist(spender)?;605 }606607 if <Balance<T>>::get((collection.id, owner)) < amount {608 ensure!(609 collection.ignores_owned_amount(owner),610 <CommonError<T>>::CantApproveMoreThanOwned611 );612 }613614 // =========615616 Self::set_allowance_unchecked(collection, owner, spender, amount);617 Ok(())618 }619620 /// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.621 ///622 /// - `collection`: Collection that contains the token623 /// - `sender`: Owner of tokens that sets the allowance.624 /// - `from`: Owner's eth mirror.625 /// - `to`: Recipient of the allowance rights.626 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.627 pub fn set_allowance_from(628 collection: &FungibleHandle<T>,629 sender: &T::CrossAccountId,630 from: &T::CrossAccountId,631 to: &T::CrossAccountId,632 amount: u128,633 ) -> DispatchResult {634 if collection.permissions.access() == AccessMode::AllowList {635 collection.check_allowlist(sender)?;636 collection.check_allowlist(from)?;637 collection.check_allowlist(to)?;638 }639640 ensure!(641 sender.conv_eq(from),642 <CommonError<T>>::AddressIsNotEthMirror643 );644645 if <Balance<T>>::get((collection.id, from)) < amount {646 ensure!(647 collection.limits.owner_can_transfer()648 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),649 <CommonError<T>>::CantApproveMoreThanOwned650 );651 }652653 // =========654655 Self::set_allowance_unchecked(collection, from, to, amount);656 Ok(())657 }658659 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.660 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.661 ///662 /// - `collection`: Collection that contains the token.663 /// - `spender`: CrossAccountId who has the allowance rights.664 /// - `from`: The owner of the tokens who sets the allowance.665 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.666 fn check_allowed(667 collection: &FungibleHandle<T>,668 spender: &T::CrossAccountId,669 from: &T::CrossAccountId,670 amount: u128,671 nesting_budget: &dyn Budget,672 ) -> Result<Option<u128>, DispatchError> {673 if spender.conv_eq(from) {674 return Ok(None);675 }676 if collection.permissions.access() == AccessMode::AllowList {677 // `from`, `to` checked in [`transfer`]678 collection.check_allowlist(spender)?;679 }680681 if collection.ignores_token_restrictions(spender) {682 return Ok(Self::compute_allowance_decrease(683 collection, from, spender, amount,684 ));685 }686687 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {688 ensure!(689 <PalletStructure<T>>::check_indirectly_owned(690 spender.clone(),691 source.0,692 source.1,693 None,694 nesting_budget695 )?,696 <CommonError<T>>::ApprovedValueTooLow,697 );698 return Ok(None);699 }700701 let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);702 ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);703704 Ok(allowance)705 }706707 /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.708 /// Otherwise, it returns `None`.709 fn compute_allowance_decrease(710 collection: &FungibleHandle<T>,711 from: &T::CrossAccountId,712 spender: &T::CrossAccountId,713 amount: u128,714 ) -> Option<u128> {715 <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)716 }717718 /// Transfer fungible tokens from one account to another.719 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.720 /// The owner should set allowance for the spender to transfer pieces.721 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.722723 pub fn transfer_from(724 collection: &FungibleHandle<T>,725 spender: &T::CrossAccountId,726 from: &T::CrossAccountId,727 to: &T::CrossAccountId,728 amount: u128,729 nesting_budget: &dyn Budget,730 ) -> DispatchResult {731 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;732733 // =========734735 Self::transfer(collection, from, to, amount, nesting_budget)?;736 if let Some(allowance) = allowance {737 Self::set_allowance_unchecked(collection, from, spender, allowance);738 }739 Ok(())740 }741742 /// Burn fungible tokens from the account.743 ///744 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should745 /// set allowance for the spender to burn tokens.746 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.747 pub fn burn_from(748 collection: &FungibleHandle<T>,749 spender: &T::CrossAccountId,750 from: &T::CrossAccountId,751 amount: u128,752 nesting_budget: &dyn Budget,753 ) -> DispatchResult {754 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;755756 // =========757758 Self::burn(collection, from, amount)?;759 if let Some(allowance) = allowance {760 Self::set_allowance_unchecked(collection, from, spender, allowance);761 }762 Ok(())763 }764765 /// Creates fungible token.766 ///767 /// The sender should be the owner/admin of the collection or collection should be configured768 /// to allow public minting.769 ///770 /// - `data`: Contains user who will become the owners of the tokens and amount771 /// of tokens he will receive.772 pub fn create_item(773 collection: &FungibleHandle<T>,774 sender: &T::CrossAccountId,775 data: CreateItemData<T>,776 nesting_budget: &dyn Budget,777 ) -> DispatchResult {778 Self::create_multiple_items(779 collection,780 sender,781 [(data.0, data.1)].into_iter().collect(),782 nesting_budget,783 )784 }785786 /// Creates fungible token.787 ///788 /// - `data`: Contains user who will become the owners of the tokens and amount789 /// of tokens he will receive.790 pub fn create_item_foreign(791 collection: &FungibleHandle<T>,792 sender: &T::CrossAccountId,793 data: CreateItemData<T>,794 nesting_budget: &dyn Budget,795 ) -> DispatchResult {796 Self::create_multiple_items_foreign(797 collection,798 sender,799 [(data.0, data.1)].into_iter().collect(),800 nesting_budget,801 )802 }803804 /// Returns 10 tokens owners in no particular order805 ///806 /// There is no direct way to get token holders in ascending order,807 /// since `iter_prefix` returns values in no particular order.808 /// Therefore, getting the 10 largest holders with a large value of holders809 /// can lead to impact memory allocation + sorting with `n * log (n)`.810 pub fn token_owners(811 collection: CollectionId,812 _token: TokenId,813 ) -> Option<Vec<T::CrossAccountId>> {814 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))815 .map(|(owner, _amount)| owner)816 .take(10)817 .collect();818819 if res.is_empty() {820 None821 } else {822 Some(res)823 }824 }825}pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -31,7 +31,7 @@
use pallet_common::{
CommonWeightInfo,
erc::{CommonEvmHandler, PrecompileResult},
- eth::collection_id_to_address,
+ eth::{collection_id_to_address, CrossAddress},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
@@ -207,11 +207,7 @@
/// @param owner crossAddress The address which owns the funds.
/// @param spender crossAddress The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
- fn allowance_cross(
- &self,
- owner: pallet_common::eth::CrossAddress,
- spender: pallet_common::eth::CrossAddress,
- ) -> Result<U256> {
+ fn allowance_cross(&self, owner: CrossAddress, spender: CrossAddress) -> Result<U256> {
let owner = owner.into_sub_cross_account::<T>()?;
let spender = spender.into_sub_cross_account::<T>()?;
@@ -245,7 +241,7 @@
fn burn_from_cross(
&mut self,
caller: Caller,
- from: pallet_common::eth::CrossAddress,
+ from: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -271,7 +267,7 @@
fn approve_cross(
&mut self,
caller: Caller,
- spender: pallet_common::eth::CrossAddress,
+ spender: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -298,12 +294,7 @@
/// @param to The crossaccount to transfer to.
/// @param amount The amount to be transferred.
#[weight(<CommonWeights<T>>::transfer())]
- fn transfer_cross(
- &mut self,
- caller: Caller,
- to: pallet_common::eth::CrossAddress,
- amount: U256,
- ) -> Result<bool> {
+ fn transfer_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = to.into_sub_cross_account::<T>()?;
let amount = amount.try_into().map_err(|_| "amount overflow")?;
@@ -324,8 +315,8 @@
fn transfer_from_cross(
&mut self,
caller: Caller,
- from: pallet_common::eth::CrossAddress,
- to: pallet_common::eth::CrossAddress,
+ from: CrossAddress,
+ to: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -240,13 +240,13 @@
QueryKind = ValueQuery,
>;
- /// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.
+ /// Spender set by a wallet owner that could perform certain transactions on all tokens in the wallet.
#[pallet::storage]
pub type CollectionAllowance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
Key<Blake2_128Concat, T::CrossAccountId>, // Owner
- Key<Blake2_128Concat, T::CrossAccountId>, // Operator
+ Key<Blake2_128Concat, T::CrossAccountId>, // Spender
),
Value = bool,
QueryKind = ValueQuery,
@@ -1403,18 +1403,18 @@
pub fn set_allowance_for_all(
collection: &RefungibleHandle<T>,
owner: &T::CrossAccountId,
- operator: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
approve: bool,
) -> DispatchResult {
<PalletCommon<T>>::set_allowance_for_all(
collection,
owner,
- operator,
+ spender,
approve,
- || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),
+ || <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),
ERC721Events::ApprovalForAll {
owner: *owner.as_eth(),
- operator: *operator.as_eth(),
+ operator: *spender.as_eth(),
approved: approve,
}
.to_log(collection_id_to_address(collection.id)),
@@ -1425,9 +1425,9 @@
pub fn allowance_for_all(
collection: &RefungibleHandle<T>,
owner: &T::CrossAccountId,
- operator: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
) -> bool {
- <CollectionAllowance<T>>::get((collection.id, owner, operator))
+ <CollectionAllowance<T>>::get((collection.id, owner, spender))
}
pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {