difftreelog
Merge pull request #907 from UniqueNetwork/feature/nft-transfer-correct-weight
in: master
feat(weight): added benchs for decompose weight
23 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6262,7 +6262,7 @@
[[package]]
name = "pallet-common"
-version = "0.1.13"
+version = "0.1.14"
dependencies = [
"ethereum",
"evm-coder",
@@ -6558,7 +6558,7 @@
[[package]]
name = "pallet-fungible"
-version = "0.1.10"
+version = "0.1.11"
dependencies = [
"evm-coder",
"frame-benchmarking",
@@ -6814,7 +6814,7 @@
[[package]]
name = "pallet-nonfungible"
-version = "0.1.13"
+version = "0.1.14"
dependencies = [
"evm-coder",
"frame-benchmarking",
pallets/app-promotion/src/lib.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -845,7 +845,6 @@
/// - `staker`: staker account.
pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {
let staked = Staked::<T>::iter_prefix((staker,))
- .into_iter()
.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {
acc + amount
});
@@ -864,7 +863,6 @@
staker: impl EncodeLike<T::AccountId>,
) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {
let mut staked = Staked::<T>::iter_prefix((staker,))
- .into_iter()
.map(|(block, (amount, _))| (block, amount))
.collect::<Vec<_>>();
staked.sort_by_key(|(block, _)| *block);
@@ -883,12 +881,6 @@
Self::total_staked_by_id(s.as_sub())
})
}
-
- // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {
- // Self::get_locked_balance(staker.as_sub())
- // .map(|l| l.amount)
- // .unwrap_or_default()
- // }
/// Returns all relay block numbers when stake was made,
/// the amount of the stake.
pallets/common/CHANGELOG.mddiffbeforeafterboth--- a/pallets/common/CHANGELOG.md
+++ b/pallets/common/CHANGELOG.md
@@ -4,6 +4,12 @@
<!-- bureaucrate goes here -->
+## [0.1.14] - 2023-03-28
+
+### Added
+
+- Added benchmark to check if user is contained in AllowList (`check_accesslist()`).
+
## [0.1.13] - 2023-01-20
### Changed
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2021"
license = "GPLv3"
name = "pallet-common"
-version = "0.1.13"
+version = "0.1.14"
[dependencies]
# Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -22,8 +22,9 @@
use frame_benchmarking::{benchmarks, account};
use up_data_structs::{
CollectionMode, CollectionFlags, CreateCollectionData, CollectionId, Property, PropertyKey,
- PropertyValue, CollectionPermissions, NestingPermissions, MAX_COLLECTION_NAME_LENGTH,
- MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, MAX_PROPERTIES_PER_ITEM,
+ PropertyValue, CollectionPermissions, NestingPermissions, AccessMode,
+ MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+ MAX_PROPERTIES_PER_ITEM,
};
use frame_support::{
traits::{Currency, Get},
@@ -193,4 +194,28 @@
<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;
let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();
}: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?}
+
+ check_accesslist{
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner);
+ };
+
+ let mut collection_handle = <CollectionHandle<T>>::try_get(collection.id)?;
+ <Pallet<T>>::update_permissions(
+ &sender,
+ &mut collection_handle,
+ CollectionPermissions { access: Some(AccessMode::AllowList), ..Default::default() }
+ )?;
+
+ <Pallet<T>>::toggle_allowlist(
+ &collection,
+ &sender,
+ &sender,
+ true,
+ )?;
+
+ assert_eq!(collection_handle.permissions.access(), AccessMode::AllowList);
+
+ }: {collection_handle.check_allowlist(&sender)?;}
}
pallets/common/src/helpers.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/common/src/helpers.rs
@@ -0,0 +1,30 @@
+//! # Helpers module
+//!
+//! The module contains helpers.
+//!
+use frame_support::{
+ pallet_prelude::DispatchResultWithPostInfo,
+ weights::Weight,
+ dispatch::{DispatchErrorWithPostInfo, PostDispatchInfo},
+};
+
+/// Add weight for a `DispatchResultWithPostInfo`
+///
+/// - `target`: DispatchResultWithPostInfo to which weight will be added
+/// - `additional_weight`: Weight to be added
+pub fn add_weight_to_post_info(target: &mut DispatchResultWithPostInfo, additional_weight: Weight) {
+ match target {
+ Ok(PostDispatchInfo {
+ actual_weight: Some(weight),
+ ..
+ })
+ | Err(DispatchErrorWithPostInfo {
+ post_info: PostDispatchInfo {
+ actual_weight: Some(weight),
+ ..
+ },
+ ..
+ }) => *weight += additional_weight,
+ _ => {}
+ }
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -92,9 +92,9 @@
pub mod dispatch;
pub mod erc;
pub mod eth;
+pub mod helpers;
#[allow(missing_docs)]
pub mod weights;
-
/// Weight info.
pub type SelfWeightOf<T> = <T as Config>::WeightInfo;
pallets/common/src/weights.rsdiffbeforeafterboth--- a/pallets/common/src/weights.rs
+++ b/pallets/common/src/weights.rs
@@ -36,6 +36,7 @@
pub trait WeightInfo {
fn set_collection_properties(b: u32, ) -> Weight;
fn delete_collection_properties(b: u32, ) -> Weight;
+ fn check_accesslist() -> Weight;
}
/// Weights for pallet_common using the Substrate node and recommended hardware.
@@ -69,6 +70,16 @@
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
+ /// Storage: Common Allowlist (r:1 w:0)
+ /// Proof: Common Allowlist (max_values: None, max_size: Some(70), added: 2545, mode: MaxEncodedLen)
+ fn check_accesslist() -> Weight {
+ // Proof Size summary in bytes:
+ // Measured: `340`
+ // Estimated: `2545`
+ // Minimum execution time: 2_887_000 picoseconds.
+ Weight::from_parts(3_072_000, 2545)
+ .saturating_add(T::DbWeight::get().reads(1_u64))
+ }
}
// For backwards compatibility and tests
@@ -101,5 +112,15 @@
.saturating_add(RocksDbWeight::get().reads(1_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
+ /// Storage: Common Allowlist (r:1 w:0)
+ /// Proof: Common Allowlist (max_values: None, max_size: Some(70), added: 2545, mode: MaxEncodedLen)
+ fn check_accesslist() -> Weight {
+ // Proof Size summary in bytes:
+ // Measured: `340`
+ // Estimated: `2545`
+ // Minimum execution time: 2_887_000 picoseconds.
+ Weight::from_parts(3_072_000, 2545)
+ .saturating_add(RocksDbWeight::get().reads(1_u64))
+ }
}
pallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -452,7 +452,8 @@
&T::CrossAccountId::from_sub(dest.clone()),
amount.into(),
&Value::new(0),
- )?;
+ )
+ .map_err(|e| e.error)?;
Ok(amount)
}
pallets/fungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/fungible/CHANGELOG.md
+++ b/pallets/fungible/CHANGELOG.md
@@ -4,6 +4,12 @@
<!-- bureaucrate goes here -->
+## [0.1.11] - 2023-03-28
+
+### Fixed
+
+- The weight of `transfer` and `transfer_from`.
+
## [0.1.10] - 2023-02-01
### Added
pallets/fungible/Cargo.tomldiffbeforeafterboth--- a/pallets/fungible/Cargo.toml
+++ b/pallets/fungible/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2021"
license = "GPLv3"
name = "pallet-fungible"
-version = "0.1.10"
+version = "0.1.11"
[dependencies]
# Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -66,7 +66,7 @@
<Pallet<T>>::create_item(&collection, &owner, (burner.clone(), 200), &Unlimited)?;
}: {<Pallet<T>>::burn(&collection, &burner, 100)?}
- transfer {
+ transfer_raw {
bench_init!{
owner: sub; collection: collection(owner);
owner: cross_from_sub; sender: cross_sub; to: cross_sub;
@@ -92,14 +92,22 @@
<Pallet<T>>::create_item(&collection, &owner, (owner_eth.clone(), 200), &Unlimited)?;
}: {<Pallet<T>>::set_allowance_from(&collection, &sender, &owner_eth, &spender, 100)?}
- transfer_from {
+ check_allowed_raw {
bench_init!{
owner: sub; collection: collection(owner);
- owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
};
<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
<Pallet<T>>::set_allowance(&collection, &sender, &spender, 200)?;
- }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, 100, &Unlimited)?}
+ }: {<Pallet<T>>::check_allowed(&collection, &spender, &sender, 200, &Unlimited)?;}
+
+ set_allowance_unchecked_raw {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
+ }: {<Pallet<T>>::set_allowance_unchecked(&collection, &sender, &spender, 200);}
burn_from {
bench_init!{
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -22,7 +22,7 @@
};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
- weights::WeightInfo as _,
+ weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
};
use pallet_structure::Error as StructureError;
use sp_runtime::ArithmeticError;
@@ -78,7 +78,7 @@
}
fn transfer() -> Weight {
- <SelfWeightOf<T>>::transfer()
+ <SelfWeightOf<T>>::transfer_raw() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
}
fn approve() -> Weight {
@@ -90,7 +90,9 @@
}
fn transfer_from() -> Weight {
- <SelfWeightOf<T>>::transfer_from()
+ Self::transfer()
+ + <SelfWeightOf<T>>::check_allowed_raw()
+ + <SelfWeightOf<T>>::set_allowance_unchecked_raw()
}
fn burn_from() -> Weight {
@@ -232,10 +234,7 @@
<Error<T>>::FungibleItemsHaveNoId
);
- with_weight(
- <Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),
- <CommonWeights<T>>::transfer(),
- )
+ <Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget)
}
fn approve(
@@ -289,10 +288,7 @@
<Error<T>>::FungibleItemsHaveNoId
);
- with_weight(
- <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),
- <CommonWeights<T>>::transfer_from(),
- )
+ <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget)
}
fn burn_from(
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -26,6 +26,7 @@
CollectionHandle,
erc::{CommonEvmHandler, PrecompileResult, CollectionCall},
eth::CrossAddress,
+ CommonWeightInfo as _,
};
use sp_std::vec::Vec;
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
@@ -39,7 +40,7 @@
use crate::{
Allowance, Balance, Config, FungibleHandle, Pallet, TotalSupply, SelfWeightOf,
- weights::WeightInfo,
+ weights::WeightInfo, common::CommonWeights,
};
frontier_contract! {
@@ -99,7 +100,7 @@
let balance = <Balance<T>>::get((self.id, owner));
Ok(balance.into())
}
- #[weight(<SelfWeightOf<T>>::transfer())]
+ #[weight(<CommonWeights<T>>::transfer())]
fn transfer(&mut self, caller: Caller, to: Address, amount: U256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
@@ -112,7 +113,7 @@
Ok(true)
}
- #[weight(<SelfWeightOf<T>>::transfer_from())]
+ #[weight(<CommonWeights<T>>::transfer_from())]
fn transfer_from(
&mut self,
caller: Caller,
@@ -129,7 +130,7 @@
.weight_calls_budget(<StructureWeight<T>>::find_parent());
<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
- .map_err(dispatch_to_evm::<T>)?;
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(true)
}
#[weight(<SelfWeightOf<T>>::approve())]
@@ -201,7 +202,7 @@
let budget = self
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::create_item(&self, &caller, (to, amount), &budget)
+ <Pallet<T>>::create_item(self, &caller, (to, amount), &budget)
.map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
@@ -289,7 +290,7 @@
Ok(true)
}
- #[weight(<SelfWeightOf<T>>::transfer())]
+ #[weight(<CommonWeights<T>>::transfer())]
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>()?;
@@ -302,7 +303,7 @@
Ok(true)
}
- #[weight(<SelfWeightOf<T>>::transfer_from())]
+ #[weight(<CommonWeights<T>>::transfer_from())]
fn transfer_from_cross(
&mut self,
caller: Caller,
@@ -319,7 +320,7 @@
.weight_calls_budget(<StructureWeight<T>>::find_parent());
<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
- .map_err(dispatch_to_evm::<T>)?;
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(true)
}
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 pub struct Pallet<T>(_);145146 /// Total amount of fungible tokens inside a collection.147 #[pallet::storage]148 pub type TotalSupply<T: Config> =149 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;150151 /// Amount of tokens owned by an account inside a collection.152 #[pallet::storage]153 pub type Balance<T: Config> = StorageNMap<154 Key = (155 Key<Twox64Concat, CollectionId>,156 Key<Blake2_128Concat, T::CrossAccountId>,157 ),158 Value = u128,159 QueryKind = ValueQuery,160 >;161162 /// Storage for assets delegated to a limited extent to other users.163 #[pallet::storage]164 pub type Allowance<T: Config> = StorageNMap<165 Key = (166 Key<Twox64Concat, CollectionId>,167 Key<Blake2_128, T::CrossAccountId>, // Owner168 Key<Blake2_128Concat, T::CrossAccountId>, // Spender169 ),170 Value = u128,171 QueryKind = ValueQuery,172 >;173}174175/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.176/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].177pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);178179/// Implementation of methods required for dispatching during runtime.180impl<T: Config> FungibleHandle<T> {181 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].182 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {183 Self(inner)184 }185186 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].187 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {188 self.0189 }190 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].191 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {192 &mut self.0193 }194}195impl<T: Config> WithRecorder<T> for FungibleHandle<T> {196 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {197 self.0.recorder()198 }199 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {200 self.0.into_recorder()201 }202}203impl<T: Config> Deref for FungibleHandle<T> {204 type Target = pallet_common::CollectionHandle<T>;205206 fn deref(&self) -> &Self::Target {207 &self.0208 }209}210211/// Pallet implementation for fungible assets212impl<T: Config> Pallet<T> {213 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.214 pub fn init_collection(215 owner: T::CrossAccountId,216 payer: T::CrossAccountId,217 data: CreateCollectionData<T::AccountId>,218 flags: CollectionFlags,219 ) -> Result<CollectionId, DispatchError> {220 <PalletCommon<T>>::init_collection(owner, payer, data, flags)221 }222223 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.224 pub fn init_foreign_collection(225 owner: T::CrossAccountId,226 payer: T::CrossAccountId,227 data: CreateCollectionData<T::AccountId>,228 ) -> Result<CollectionId, DispatchError> {229 let id = <PalletCommon<T>>::init_collection(230 owner,231 payer,232 data,233 CollectionFlags {234 foreign: true,235 ..Default::default()236 },237 )?;238 Ok(id)239 }240241 /// Destroys a collection.242 pub fn destroy_collection(243 collection: FungibleHandle<T>,244 sender: &T::CrossAccountId,245 ) -> DispatchResult {246 let id = collection.id;247248 if Self::collection_has_tokens(id) {249 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());250 }251252 // =========253254 PalletCommon::destroy_collection(collection.0, sender)?;255256 <TotalSupply<T>>::remove(id);257 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);258 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);259 Ok(())260 }261262 /// Add properties to the collection.263 pub fn set_collection_properties(264 collection: &FungibleHandle<T>,265 sender: &T::CrossAccountId,266 properties: Vec<Property>,267 ) -> DispatchResult {268 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())269 }270271 /// Delete properties of the collection, associated with the provided keys.272 pub fn delete_collection_properties(273 collection: &FungibleHandle<T>,274 sender: &T::CrossAccountId,275 property_keys: Vec<PropertyKey>,276 ) -> DispatchResult {277 <PalletCommon<T>>::delete_collection_properties(278 collection,279 sender,280 property_keys.into_iter(),281 )282 }283284 /// Checks if collection has tokens. Return `true` if it has.285 fn collection_has_tokens(collection_id: CollectionId) -> bool {286 <TotalSupply<T>>::get(collection_id) != 0287 }288289 /// Burns the specified amount of the token. If the token balance290 /// or total supply is less than the given value,291 /// it will return [DispatchError].292 pub fn burn(293 collection: &FungibleHandle<T>,294 owner: &T::CrossAccountId,295 amount: u128,296 ) -> DispatchResult {297 let total_supply = <TotalSupply<T>>::get(collection.id)298 .checked_sub(amount)299 .ok_or(<CommonError<T>>::TokenValueTooLow)?;300301 let balance = <Balance<T>>::get((collection.id, owner))302 .checked_sub(amount)303 .ok_or(<CommonError<T>>::TokenValueTooLow)?;304305 // Foreign collection check306 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);307308 if collection.permissions.access() == AccessMode::AllowList {309 collection.check_allowlist(owner)?;310 }311312 // =========313314 if balance == 0 {315 <Balance<T>>::remove((collection.id, owner));316 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());317 } else {318 <Balance<T>>::insert((collection.id, owner), balance);319 }320 <TotalSupply<T>>::insert(collection.id, total_supply);321322 <PalletEvm<T>>::deposit_log(323 ERC20Events::Transfer {324 from: *owner.as_eth(),325 to: H160::default(),326 value: amount.into(),327 }328 .to_log(collection_id_to_address(collection.id)),329 );330 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(331 collection.id,332 TokenId::default(),333 owner.clone(),334 amount,335 ));336 Ok(())337 }338339 /// Burns the specified amount of the token.340 pub fn burn_foreign(341 collection: &FungibleHandle<T>,342 owner: &T::CrossAccountId,343 amount: u128,344 ) -> DispatchResult {345 let total_supply = <TotalSupply<T>>::get(collection.id)346 .checked_sub(amount)347 .ok_or(<CommonError<T>>::TokenValueTooLow)?;348349 let balance = <Balance<T>>::get((collection.id, owner))350 .checked_sub(amount)351 .ok_or(<CommonError<T>>::TokenValueTooLow)?;352 // =========353354 if balance == 0 {355 <Balance<T>>::remove((collection.id, owner));356 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());357 } else {358 <Balance<T>>::insert((collection.id, owner), balance);359 }360 <TotalSupply<T>>::insert(collection.id, total_supply);361362 <PalletEvm<T>>::deposit_log(363 ERC20Events::Transfer {364 from: *owner.as_eth(),365 to: H160::default(),366 value: amount.into(),367 }368 .to_log(collection_id_to_address(collection.id)),369 );370 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(371 collection.id,372 TokenId::default(),373 owner.clone(),374 amount,375 ));376 Ok(())377 }378379 /// Transfers the specified amount of tokens. Will check that380 /// the transfer is allowed for the token.381 ///382 /// - `from`: Owner of tokens to transfer.383 /// - `to`: Recepient of transfered tokens.384 /// - `amount`: Amount of tokens to transfer.385 /// - `collection`: Collection that contains the token386 pub fn transfer(387 collection: &FungibleHandle<T>,388 from: &T::CrossAccountId,389 to: &T::CrossAccountId,390 amount: u128,391 nesting_budget: &dyn Budget,392 ) -> DispatchResult {393 ensure!(394 collection.limits.transfers_enabled(),395 <CommonError<T>>::TransferNotAllowed,396 );397398 if collection.permissions.access() == AccessMode::AllowList {399 collection.check_allowlist(from)?;400 collection.check_allowlist(to)?;401 }402 <PalletCommon<T>>::ensure_correct_receiver(to)?;403404 let balance_from = <Balance<T>>::get((collection.id, from))405 .checked_sub(amount)406 .ok_or(<CommonError<T>>::TokenValueTooLow)?;407 let balance_to = if from != to && amount != 0 {408 Some(409 <Balance<T>>::get((collection.id, to))410 .checked_add(amount)411 .ok_or(ArithmeticError::Overflow)?,412 )413 } else {414 None415 };416417 // =========418419 if let Some(balance_to) = balance_to {420 // from != to && amount != 0421422 <PalletStructure<T>>::nest_if_sent_to_token(423 from.clone(),424 to,425 collection.id,426 TokenId::default(),427 nesting_budget,428 )?;429430 if balance_from == 0 {431 <Balance<T>>::remove((collection.id, from));432 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());433 } else {434 <Balance<T>>::insert((collection.id, from), balance_from);435 }436 <Balance<T>>::insert((collection.id, to), balance_to);437 }438439 <PalletEvm<T>>::deposit_log(440 ERC20Events::Transfer {441 from: *from.as_eth(),442 to: *to.as_eth(),443 value: amount.into(),444 }445 .to_log(collection_id_to_address(collection.id)),446 );447 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(448 collection.id,449 TokenId::default(),450 from.clone(),451 to.clone(),452 amount,453 ));454 Ok(())455 }456457 /// Minting tokens for multiple IDs.458 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]459 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]460 pub fn create_multiple_items_common(461 collection: &FungibleHandle<T>,462 sender: &T::CrossAccountId,463 data: BTreeMap<T::CrossAccountId, u128>,464 nesting_budget: &dyn Budget,465 ) -> DispatchResult {466 let total_supply = data467 .iter()468 .map(|(_, v)| *v)469 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {470 acc.checked_add(v)471 })472 .ok_or(ArithmeticError::Overflow)?;473474 for (to, _) in data.iter() {475 <PalletStructure<T>>::check_nesting(476 sender.clone(),477 to,478 collection.id,479 TokenId::default(),480 nesting_budget,481 )?;482 }483484 let updated_balances = data485 .into_iter()486 .map(|(user, amount)| {487 let updated_balance = <Balance<T>>::get((collection.id, &user))488 .checked_add(amount)489 .ok_or(ArithmeticError::Overflow)?;490 Ok((user, amount, updated_balance))491 })492 .collect::<Result<Vec<_>, DispatchError>>()?;493494 // =========495496 <TotalSupply<T>>::insert(collection.id, total_supply);497 for (user, amount, updated_balance) in updated_balances {498 <Balance<T>>::insert((collection.id, &user), updated_balance);499 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(500 &user,501 collection.id,502 TokenId::default(),503 );504 <PalletEvm<T>>::deposit_log(505 ERC20Events::Transfer {506 from: H160::default(),507 to: *user.as_eth(),508 value: amount.into(),509 }510 .to_log(collection_id_to_address(collection.id)),511 );512 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(513 collection.id,514 TokenId::default(),515 user.clone(),516 amount,517 ));518 }519520 Ok(())521 }522523 /// Minting tokens for multiple IDs.524 /// See [`create_item`][`Pallet::create_item`] for more details.525 pub fn create_multiple_items(526 collection: &FungibleHandle<T>,527 sender: &T::CrossAccountId,528 data: BTreeMap<T::CrossAccountId, u128>,529 nesting_budget: &dyn Budget,530 ) -> DispatchResult {531 // Foreign collection check532 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);533534 if !collection.is_owner_or_admin(sender) {535 ensure!(536 collection.permissions.mint_mode(),537 <CommonError<T>>::PublicMintingNotAllowed538 );539 collection.check_allowlist(sender)?;540541 for (owner, _) in data.iter() {542 collection.check_allowlist(owner)?;543 }544 }545546 Self::create_multiple_items_common(collection, sender, data, nesting_budget)547 }548549 /// Minting tokens for multiple IDs.550 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.551 pub fn create_multiple_items_foreign(552 collection: &FungibleHandle<T>,553 sender: &T::CrossAccountId,554 data: BTreeMap<T::CrossAccountId, u128>,555 nesting_budget: &dyn Budget,556 ) -> DispatchResult {557 Self::create_multiple_items_common(collection, sender, data, nesting_budget)558 }559560 fn set_allowance_unchecked(561 collection: &FungibleHandle<T>,562 owner: &T::CrossAccountId,563 spender: &T::CrossAccountId,564 amount: u128,565 ) {566 if amount == 0 {567 <Allowance<T>>::remove((collection.id, owner, spender));568 } else {569 <Allowance<T>>::insert((collection.id, owner, spender), amount);570 }571572 <PalletEvm<T>>::deposit_log(573 ERC20Events::Approval {574 owner: *owner.as_eth(),575 spender: *spender.as_eth(),576 value: amount.into(),577 }578 .to_log(collection_id_to_address(collection.id)),579 );580 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(581 collection.id,582 TokenId(0),583 owner.clone(),584 spender.clone(),585 amount,586 ));587 }588589 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.590 ///591 /// - `collection`: Collection that contains the token592 /// - `owner`: Owner of tokens that sets the allowance.593 /// - `spender`: Recipient of the allowance rights.594 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.595 pub fn set_allowance(596 collection: &FungibleHandle<T>,597 owner: &T::CrossAccountId,598 spender: &T::CrossAccountId,599 amount: u128,600 ) -> DispatchResult {601 if collection.permissions.access() == AccessMode::AllowList {602 collection.check_allowlist(owner)?;603 collection.check_allowlist(spender)?;604 }605606 if <Balance<T>>::get((collection.id, owner)) < amount {607 ensure!(608 collection.ignores_owned_amount(owner),609 <CommonError<T>>::CantApproveMoreThanOwned610 );611 }612613 // =========614615 Self::set_allowance_unchecked(collection, owner, spender, amount);616 Ok(())617 }618619 /// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.620 ///621 /// - `collection`: Collection that contains the token622 /// - `sender`: Owner of tokens that sets the allowance.623 /// - `from`: Owner's eth mirror.624 /// - `to`: Recipient of the allowance rights.625 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.626 pub fn set_allowance_from(627 collection: &FungibleHandle<T>,628 sender: &T::CrossAccountId,629 from: &T::CrossAccountId,630 to: &T::CrossAccountId,631 amount: u128,632 ) -> DispatchResult {633 if collection.permissions.access() == AccessMode::AllowList {634 collection.check_allowlist(sender)?;635 collection.check_allowlist(from)?;636 collection.check_allowlist(to)?;637 }638639 ensure!(640 sender.conv_eq(from),641 <CommonError<T>>::AddressIsNotEthMirror642 );643644 if <Balance<T>>::get((collection.id, from)) < amount {645 ensure!(646 collection.limits.owner_can_transfer()647 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),648 <CommonError<T>>::CantApproveMoreThanOwned649 );650 }651652 // =========653654 Self::set_allowance_unchecked(collection, from, to, amount);655 Ok(())656 }657658 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.659 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.660 ///661 /// - `collection`: Collection that contains the token.662 /// - `spender`: CrossAccountId who has the allowance rights.663 /// - `from`: The owner of the tokens who sets the allowance.664 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.665 fn check_allowed(666 collection: &FungibleHandle<T>,667 spender: &T::CrossAccountId,668 from: &T::CrossAccountId,669 amount: u128,670 nesting_budget: &dyn Budget,671 ) -> Result<Option<u128>, DispatchError> {672 if spender.conv_eq(from) {673 return Ok(None);674 }675 if collection.permissions.access() == AccessMode::AllowList {676 // `from`, `to` checked in [`transfer`]677 collection.check_allowlist(spender)?;678 }679680 if collection.ignores_token_restrictions(spender) {681 return Ok(Self::compute_allowance_decrease(682 collection, from, spender, amount,683 ));684 }685686 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {687 ensure!(688 <PalletStructure<T>>::check_indirectly_owned(689 spender.clone(),690 source.0,691 source.1,692 None,693 nesting_budget694 )?,695 <CommonError<T>>::ApprovedValueTooLow,696 );697 return Ok(None);698 }699700 let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);701 ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);702703 Ok(allowance)704 }705706 /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.707 /// Otherwise, it returns `None`.708 fn compute_allowance_decrease(709 collection: &FungibleHandle<T>,710 from: &T::CrossAccountId,711 spender: &T::CrossAccountId,712 amount: u128,713 ) -> Option<u128> {714 <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)715 }716717 /// Transfer fungible tokens from one account to another.718 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.719 /// The owner should set allowance for the spender to transfer pieces.720 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.721722 pub fn transfer_from(723 collection: &FungibleHandle<T>,724 spender: &T::CrossAccountId,725 from: &T::CrossAccountId,726 to: &T::CrossAccountId,727 amount: u128,728 nesting_budget: &dyn Budget,729 ) -> DispatchResult {730 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;731732 // =========733734 Self::transfer(collection, from, to, amount, nesting_budget)?;735 if let Some(allowance) = allowance {736 Self::set_allowance_unchecked(collection, from, spender, allowance);737 }738 Ok(())739 }740741 /// Burn fungible tokens from the account.742 ///743 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should744 /// set allowance for the spender to burn tokens.745 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.746 pub fn burn_from(747 collection: &FungibleHandle<T>,748 spender: &T::CrossAccountId,749 from: &T::CrossAccountId,750 amount: u128,751 nesting_budget: &dyn Budget,752 ) -> DispatchResult {753 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;754755 // =========756757 Self::burn(collection, from, amount)?;758 if let Some(allowance) = allowance {759 Self::set_allowance_unchecked(collection, from, spender, allowance);760 }761 Ok(())762 }763764 /// Creates fungible token.765 ///766 /// The sender should be the owner/admin of the collection or collection should be configured767 /// to allow public minting.768 ///769 /// - `data`: Contains user who will become the owners of the tokens and amount770 /// of tokens he will receive.771 pub fn create_item(772 collection: &FungibleHandle<T>,773 sender: &T::CrossAccountId,774 data: CreateItemData<T>,775 nesting_budget: &dyn Budget,776 ) -> DispatchResult {777 Self::create_multiple_items(778 collection,779 sender,780 [(data.0, data.1)].into_iter().collect(),781 nesting_budget,782 )783 }784785 /// Creates fungible token.786 ///787 /// - `data`: Contains user who will become the owners of the tokens and amount788 /// of tokens he will receive.789 pub fn create_item_foreign(790 collection: &FungibleHandle<T>,791 sender: &T::CrossAccountId,792 data: CreateItemData<T>,793 nesting_budget: &dyn Budget,794 ) -> DispatchResult {795 Self::create_multiple_items_foreign(796 collection,797 sender,798 [(data.0, data.1)].into_iter().collect(),799 nesting_budget,800 )801 }802803 /// Returns 10 tokens owners in no particular order804 ///805 /// There is no direct way to get token holders in ascending order,806 /// since `iter_prefix` returns values in no particular order.807 /// Therefore, getting the 10 largest holders with a large value of holders808 /// can lead to impact memory allocation + sorting with `n * log (n)`.809 pub fn token_owners(810 collection: CollectionId,811 _token: TokenId,812 ) -> Option<Vec<T::CrossAccountId>> {813 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))814 .map(|(owner, _amount)| owner)815 .take(10)816 .collect();817818 if res.is_empty() {819 None820 } else {821 Some(res)822 }823 }824}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::{84 ensure,85 pallet_prelude::{DispatchResultWithPostInfo, Pays},86 dispatch::PostDispatchInfo,87};88use pallet_evm::account::CrossAccountId;89use up_data_structs::{90 AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,91 mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,92};93use pallet_common::{94 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,95 eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,96 weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,97};98use pallet_evm::Pallet as PalletEvm;99use pallet_structure::Pallet as PalletStructure;100use pallet_evm_coder_substrate::WithRecorder;101use sp_core::H160;102use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};103use sp_std::{collections::btree_map::BTreeMap, vec::Vec};104use weights::WeightInfo;105pub use pallet::*;106107use crate::erc::ERC20Events;108#[cfg(feature = "runtime-benchmarks")]109pub mod benchmarking;110pub mod common;111pub mod erc;112pub mod weights;113114pub type CreateItemData<T> = (<T as pallet_evm::Config>::CrossAccountId, u128);115pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;116117#[frame_support::pallet]118pub mod pallet {119 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};120 use up_data_structs::CollectionId;121 use super::weights::WeightInfo;122123 #[pallet::error]124 pub enum Error<T> {125 /// Not Fungible item data used to mint in Fungible collection.126 NotFungibleDataUsedToMintFungibleCollectionToken,127 /// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.128 FungibleItemsHaveNoId,129 /// Tried to set data for fungible item.130 FungibleItemsDontHaveData,131 /// Fungible token does not support nesting.132 FungibleDisallowsNesting,133 /// Setting item properties is not allowed.134 SettingPropertiesNotAllowed,135 /// Setting allowance for all is not allowed.136 SettingAllowanceForAllNotAllowed,137 /// Only a fungible collection could be possibly broken; any fungible token is valid.138 FungibleTokensAreAlwaysValid,139 }140141 #[pallet::config]142 pub trait Config:143 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config144 {145 type WeightInfo: WeightInfo;146 }147148 #[pallet::pallet]149 pub struct Pallet<T>(_);150151 /// Total amount of fungible tokens inside a collection.152 #[pallet::storage]153 pub type TotalSupply<T: Config> =154 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;155156 /// Amount of tokens owned by an account inside a collection.157 #[pallet::storage]158 pub type Balance<T: Config> = StorageNMap<159 Key = (160 Key<Twox64Concat, CollectionId>,161 Key<Blake2_128Concat, T::CrossAccountId>,162 ),163 Value = u128,164 QueryKind = ValueQuery,165 >;166167 /// Storage for assets delegated to a limited extent to other users.168 #[pallet::storage]169 pub type Allowance<T: Config> = StorageNMap<170 Key = (171 Key<Twox64Concat, CollectionId>,172 Key<Blake2_128, T::CrossAccountId>, // Owner173 Key<Blake2_128Concat, T::CrossAccountId>, // Spender174 ),175 Value = u128,176 QueryKind = ValueQuery,177 >;178}179180/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.181/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].182pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);183184/// Implementation of methods required for dispatching during runtime.185impl<T: Config> FungibleHandle<T> {186 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].187 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {188 Self(inner)189 }190191 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].192 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {193 self.0194 }195 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].196 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {197 &mut self.0198 }199}200impl<T: Config> WithRecorder<T> for FungibleHandle<T> {201 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {202 self.0.recorder()203 }204 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {205 self.0.into_recorder()206 }207}208impl<T: Config> Deref for FungibleHandle<T> {209 type Target = pallet_common::CollectionHandle<T>;210211 fn deref(&self) -> &Self::Target {212 &self.0213 }214}215216/// Pallet implementation for fungible assets217impl<T: Config> Pallet<T> {218 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.219 pub fn init_collection(220 owner: T::CrossAccountId,221 payer: T::CrossAccountId,222 data: CreateCollectionData<T::AccountId>,223 flags: CollectionFlags,224 ) -> Result<CollectionId, DispatchError> {225 <PalletCommon<T>>::init_collection(owner, payer, data, flags)226 }227228 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.229 pub fn init_foreign_collection(230 owner: T::CrossAccountId,231 payer: T::CrossAccountId,232 data: CreateCollectionData<T::AccountId>,233 ) -> Result<CollectionId, DispatchError> {234 let id = <PalletCommon<T>>::init_collection(235 owner,236 payer,237 data,238 CollectionFlags {239 foreign: true,240 ..Default::default()241 },242 )?;243 Ok(id)244 }245246 /// Destroys a collection.247 pub fn destroy_collection(248 collection: FungibleHandle<T>,249 sender: &T::CrossAccountId,250 ) -> DispatchResult {251 let id = collection.id;252253 if Self::collection_has_tokens(id) {254 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());255 }256257 // =========258259 PalletCommon::destroy_collection(collection.0, sender)?;260261 <TotalSupply<T>>::remove(id);262 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);263 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);264 Ok(())265 }266267 /// Add properties to the collection.268 pub fn set_collection_properties(269 collection: &FungibleHandle<T>,270 sender: &T::CrossAccountId,271 properties: Vec<Property>,272 ) -> DispatchResult {273 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())274 }275276 /// Delete properties of the collection, associated with the provided keys.277 pub fn delete_collection_properties(278 collection: &FungibleHandle<T>,279 sender: &T::CrossAccountId,280 property_keys: Vec<PropertyKey>,281 ) -> DispatchResult {282 <PalletCommon<T>>::delete_collection_properties(283 collection,284 sender,285 property_keys.into_iter(),286 )287 }288289 /// Checks if collection has tokens. Return `true` if it has.290 fn collection_has_tokens(collection_id: CollectionId) -> bool {291 <TotalSupply<T>>::get(collection_id) != 0292 }293294 /// Burns the specified amount of the token. If the token balance295 /// or total supply is less than the given value,296 /// it will return [DispatchError].297 pub fn burn(298 collection: &FungibleHandle<T>,299 owner: &T::CrossAccountId,300 amount: u128,301 ) -> DispatchResult {302 let total_supply = <TotalSupply<T>>::get(collection.id)303 .checked_sub(amount)304 .ok_or(<CommonError<T>>::TokenValueTooLow)?;305306 let balance = <Balance<T>>::get((collection.id, owner))307 .checked_sub(amount)308 .ok_or(<CommonError<T>>::TokenValueTooLow)?;309310 // Foreign collection check311 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);312313 if collection.permissions.access() == AccessMode::AllowList {314 collection.check_allowlist(owner)?;315 }316317 // =========318319 if balance == 0 {320 <Balance<T>>::remove((collection.id, owner));321 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());322 } else {323 <Balance<T>>::insert((collection.id, owner), balance);324 }325 <TotalSupply<T>>::insert(collection.id, total_supply);326327 <PalletEvm<T>>::deposit_log(328 ERC20Events::Transfer {329 from: *owner.as_eth(),330 to: H160::default(),331 value: amount.into(),332 }333 .to_log(collection_id_to_address(collection.id)),334 );335 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(336 collection.id,337 TokenId::default(),338 owner.clone(),339 amount,340 ));341 Ok(())342 }343344 /// Burns the specified amount of the token.345 pub fn burn_foreign(346 collection: &FungibleHandle<T>,347 owner: &T::CrossAccountId,348 amount: u128,349 ) -> DispatchResult {350 let total_supply = <TotalSupply<T>>::get(collection.id)351 .checked_sub(amount)352 .ok_or(<CommonError<T>>::TokenValueTooLow)?;353354 let balance = <Balance<T>>::get((collection.id, owner))355 .checked_sub(amount)356 .ok_or(<CommonError<T>>::TokenValueTooLow)?;357 // =========358359 if balance == 0 {360 <Balance<T>>::remove((collection.id, owner));361 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());362 } else {363 <Balance<T>>::insert((collection.id, owner), balance);364 }365 <TotalSupply<T>>::insert(collection.id, total_supply);366367 <PalletEvm<T>>::deposit_log(368 ERC20Events::Transfer {369 from: *owner.as_eth(),370 to: H160::default(),371 value: amount.into(),372 }373 .to_log(collection_id_to_address(collection.id)),374 );375 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(376 collection.id,377 TokenId::default(),378 owner.clone(),379 amount,380 ));381 Ok(())382 }383384 /// Transfers the specified amount of tokens. Will check that385 /// the transfer is allowed for the token.386 ///387 /// - `from`: Owner of tokens to transfer.388 /// - `to`: Recepient of transfered tokens.389 /// - `amount`: Amount of tokens to transfer.390 /// - `collection`: Collection that contains the token391 pub fn transfer(392 collection: &FungibleHandle<T>,393 from: &T::CrossAccountId,394 to: &T::CrossAccountId,395 amount: u128,396 nesting_budget: &dyn Budget,397 ) -> DispatchResultWithPostInfo {398 ensure!(399 collection.limits.transfers_enabled(),400 <CommonError<T>>::TransferNotAllowed,401 );402403 let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();404405 if collection.permissions.access() == AccessMode::AllowList {406 collection.check_allowlist(from)?;407 collection.check_allowlist(to)?;408 actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;409 }410 <PalletCommon<T>>::ensure_correct_receiver(to)?;411 let balance_from = <Balance<T>>::get((collection.id, from))412 .checked_sub(amount)413 .ok_or(<CommonError<T>>::TokenValueTooLow)?;414 let balance_to = if from != to && amount != 0 {415 Some(416 <Balance<T>>::get((collection.id, to))417 .checked_add(amount)418 .ok_or(ArithmeticError::Overflow)?,419 )420 } else {421 None422 };423424 // =========425426 if let Some(balance_to) = balance_to {427 // from != to && amount != 0428429 <PalletStructure<T>>::nest_if_sent_to_token(430 from.clone(),431 to,432 collection.id,433 TokenId::default(),434 nesting_budget,435 )?;436437 if balance_from == 0 {438 <Balance<T>>::remove((collection.id, from));439 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());440 } else {441 <Balance<T>>::insert((collection.id, from), balance_from);442 }443 <Balance<T>>::insert((collection.id, to), balance_to);444 }445446 <PalletEvm<T>>::deposit_log(447 ERC20Events::Transfer {448 from: *from.as_eth(),449 to: *to.as_eth(),450 value: amount.into(),451 }452 .to_log(collection_id_to_address(collection.id)),453 );454 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(455 collection.id,456 TokenId::default(),457 from.clone(),458 to.clone(),459 amount,460 ));461462 Ok(PostDispatchInfo {463 actual_weight: Some(actual_weight),464 pays_fee: Pays::Yes,465 })466 }467468 /// Minting tokens for multiple IDs.469 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]470 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]471 pub fn create_multiple_items_common(472 collection: &FungibleHandle<T>,473 sender: &T::CrossAccountId,474 data: BTreeMap<T::CrossAccountId, u128>,475 nesting_budget: &dyn Budget,476 ) -> DispatchResult {477 let total_supply = data478 .values()479 .copied()480 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {481 acc.checked_add(v)482 })483 .ok_or(ArithmeticError::Overflow)?;484485 for (to, _) in data.iter() {486 <PalletStructure<T>>::check_nesting(487 sender.clone(),488 to,489 collection.id,490 TokenId::default(),491 nesting_budget,492 )?;493 }494495 let updated_balances = data496 .into_iter()497 .map(|(user, amount)| {498 let updated_balance = <Balance<T>>::get((collection.id, &user))499 .checked_add(amount)500 .ok_or(ArithmeticError::Overflow)?;501 Ok((user, amount, updated_balance))502 })503 .collect::<Result<Vec<_>, DispatchError>>()?;504505 // =========506507 <TotalSupply<T>>::insert(collection.id, total_supply);508 for (user, amount, updated_balance) in updated_balances {509 <Balance<T>>::insert((collection.id, &user), updated_balance);510 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(511 &user,512 collection.id,513 TokenId::default(),514 );515 <PalletEvm<T>>::deposit_log(516 ERC20Events::Transfer {517 from: H160::default(),518 to: *user.as_eth(),519 value: amount.into(),520 }521 .to_log(collection_id_to_address(collection.id)),522 );523 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(524 collection.id,525 TokenId::default(),526 user.clone(),527 amount,528 ));529 }530531 Ok(())532 }533534 /// Minting tokens for multiple IDs.535 /// See [`create_item`][`Pallet::create_item`] for more details.536 pub fn create_multiple_items(537 collection: &FungibleHandle<T>,538 sender: &T::CrossAccountId,539 data: BTreeMap<T::CrossAccountId, u128>,540 nesting_budget: &dyn Budget,541 ) -> DispatchResult {542 // Foreign collection check543 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);544545 if !collection.is_owner_or_admin(sender) {546 ensure!(547 collection.permissions.mint_mode(),548 <CommonError<T>>::PublicMintingNotAllowed549 );550 collection.check_allowlist(sender)?;551552 for (owner, _) in data.iter() {553 collection.check_allowlist(owner)?;554 }555 }556557 Self::create_multiple_items_common(collection, sender, data, nesting_budget)558 }559560 /// Minting tokens for multiple IDs.561 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.562 pub fn create_multiple_items_foreign(563 collection: &FungibleHandle<T>,564 sender: &T::CrossAccountId,565 data: BTreeMap<T::CrossAccountId, u128>,566 nesting_budget: &dyn Budget,567 ) -> DispatchResult {568 Self::create_multiple_items_common(collection, sender, data, nesting_budget)569 }570571 fn set_allowance_unchecked(572 collection: &FungibleHandle<T>,573 owner: &T::CrossAccountId,574 spender: &T::CrossAccountId,575 amount: u128,576 ) {577 if amount == 0 {578 <Allowance<T>>::remove((collection.id, owner, spender));579 } else {580 <Allowance<T>>::insert((collection.id, owner, spender), amount);581 }582583 <PalletEvm<T>>::deposit_log(584 ERC20Events::Approval {585 owner: *owner.as_eth(),586 spender: *spender.as_eth(),587 value: amount.into(),588 }589 .to_log(collection_id_to_address(collection.id)),590 );591 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(592 collection.id,593 TokenId(0),594 owner.clone(),595 spender.clone(),596 amount,597 ));598 }599600 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.601 ///602 /// - `collection`: Collection that contains the token603 /// - `owner`: Owner of tokens that sets the allowance.604 /// - `spender`: Recipient of the allowance rights.605 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.606 pub fn set_allowance(607 collection: &FungibleHandle<T>,608 owner: &T::CrossAccountId,609 spender: &T::CrossAccountId,610 amount: u128,611 ) -> DispatchResult {612 if collection.permissions.access() == AccessMode::AllowList {613 collection.check_allowlist(owner)?;614 collection.check_allowlist(spender)?;615 }616617 if <Balance<T>>::get((collection.id, owner)) < amount {618 ensure!(619 collection.ignores_owned_amount(owner),620 <CommonError<T>>::CantApproveMoreThanOwned621 );622 }623624 // =========625626 Self::set_allowance_unchecked(collection, owner, spender, amount);627 Ok(())628 }629630 /// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.631 ///632 /// - `collection`: Collection that contains the token633 /// - `sender`: Owner of tokens that sets the allowance.634 /// - `from`: Owner's eth mirror.635 /// - `to`: Recipient of the allowance rights.636 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.637 pub fn set_allowance_from(638 collection: &FungibleHandle<T>,639 sender: &T::CrossAccountId,640 from: &T::CrossAccountId,641 to: &T::CrossAccountId,642 amount: u128,643 ) -> DispatchResult {644 if collection.permissions.access() == AccessMode::AllowList {645 collection.check_allowlist(sender)?;646 collection.check_allowlist(from)?;647 collection.check_allowlist(to)?;648 }649650 ensure!(651 sender.conv_eq(from),652 <CommonError<T>>::AddressIsNotEthMirror653 );654655 if <Balance<T>>::get((collection.id, from)) < amount {656 ensure!(657 collection.limits.owner_can_transfer()658 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),659 <CommonError<T>>::CantApproveMoreThanOwned660 );661 }662663 // =========664665 Self::set_allowance_unchecked(collection, from, to, amount);666 Ok(())667 }668669 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.670 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.671 ///672 /// - `collection`: Collection that contains the token.673 /// - `spender`: CrossAccountId who has the allowance rights.674 /// - `from`: The owner of the tokens who sets the allowance.675 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.676 fn check_allowed(677 collection: &FungibleHandle<T>,678 spender: &T::CrossAccountId,679 from: &T::CrossAccountId,680 amount: u128,681 nesting_budget: &dyn Budget,682 ) -> Result<Option<u128>, DispatchError> {683 if spender.conv_eq(from) {684 return Ok(None);685 }686 if collection.permissions.access() == AccessMode::AllowList {687 // `from`, `to` checked in [`transfer`]688 collection.check_allowlist(spender)?;689 }690691 if collection.ignores_token_restrictions(spender) {692 return Ok(Self::compute_allowance_decrease(693 collection, from, spender, amount,694 ));695 }696697 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {698 ensure!(699 <PalletStructure<T>>::check_indirectly_owned(700 spender.clone(),701 source.0,702 source.1,703 None,704 nesting_budget705 )?,706 <CommonError<T>>::ApprovedValueTooLow,707 );708 return Ok(None);709 }710711 let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);712 ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);713714 Ok(allowance)715 }716717 /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.718 /// Otherwise, it returns `None`.719 fn compute_allowance_decrease(720 collection: &FungibleHandle<T>,721 from: &T::CrossAccountId,722 spender: &T::CrossAccountId,723 amount: u128,724 ) -> Option<u128> {725 <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)726 }727728 /// Transfer fungible tokens from one account to another.729 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.730 /// The owner should set allowance for the spender to transfer pieces.731 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.732 pub fn transfer_from(733 collection: &FungibleHandle<T>,734 spender: &T::CrossAccountId,735 from: &T::CrossAccountId,736 to: &T::CrossAccountId,737 amount: u128,738 nesting_budget: &dyn Budget,739 ) -> DispatchResultWithPostInfo {740 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;741742 // =========743744 let mut result = Self::transfer(collection, from, to, amount, nesting_budget);745 add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());746 result?;747748 if let Some(allowance) = allowance {749 Self::set_allowance_unchecked(collection, from, spender, allowance);750 add_weight_to_post_info(751 &mut result,752 <SelfWeightOf<T>>::set_allowance_unchecked_raw(),753 )754 }755 result756 }757758 /// Burn fungible tokens from the account.759 ///760 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should761 /// set allowance for the spender to burn tokens.762 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.763 pub fn burn_from(764 collection: &FungibleHandle<T>,765 spender: &T::CrossAccountId,766 from: &T::CrossAccountId,767 amount: u128,768 nesting_budget: &dyn Budget,769 ) -> DispatchResult {770 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;771772 // =========773774 Self::burn(collection, from, amount)?;775 if let Some(allowance) = allowance {776 Self::set_allowance_unchecked(collection, from, spender, allowance);777 }778 Ok(())779 }780781 /// Creates fungible token.782 ///783 /// The sender should be the owner/admin of the collection or collection should be configured784 /// to allow public minting.785 ///786 /// - `data`: Contains user who will become the owners of the tokens and amount787 /// of tokens he will receive.788 pub fn create_item(789 collection: &FungibleHandle<T>,790 sender: &T::CrossAccountId,791 data: CreateItemData<T>,792 nesting_budget: &dyn Budget,793 ) -> DispatchResult {794 Self::create_multiple_items(795 collection,796 sender,797 [(data.0, data.1)].into_iter().collect(),798 nesting_budget,799 )800 }801802 /// Creates fungible token.803 ///804 /// - `data`: Contains user who will become the owners of the tokens and amount805 /// of tokens he will receive.806 pub fn create_item_foreign(807 collection: &FungibleHandle<T>,808 sender: &T::CrossAccountId,809 data: CreateItemData<T>,810 nesting_budget: &dyn Budget,811 ) -> DispatchResult {812 Self::create_multiple_items_foreign(813 collection,814 sender,815 [(data.0, data.1)].into_iter().collect(),816 nesting_budget,817 )818 }819820 /// Returns 10 tokens owners in no particular order821 ///822 /// There is no direct way to get token holders in ascending order,823 /// since `iter_prefix` returns values in no particular order.824 /// Therefore, getting the 10 largest holders with a large value of holders825 /// can lead to impact memory allocation + sorting with `n * log (n)`.826 pub fn token_owners(827 collection: CollectionId,828 _token: TokenId,829 ) -> Option<Vec<T::CrossAccountId>> {830 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))831 .map(|(owner, _amount)| owner)832 .take(10)833 .collect();834835 if res.is_empty() {836 None837 } else {838 Some(res)839 }840 }841}pallets/fungible/src/weights.rsdiffbeforeafterboth--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -37,10 +37,11 @@
fn create_item() -> Weight;
fn create_multiple_items_ex(b: u32, ) -> Weight;
fn burn_item() -> Weight;
- fn transfer() -> Weight;
+ fn transfer_raw() -> Weight;
fn approve() -> Weight;
fn approve_from() -> Weight;
- fn transfer_from() -> Weight;
+ fn check_allowed_raw() -> Weight;
+ fn set_allowance_unchecked_raw() -> Weight;
fn burn_from() -> Weight;
}
@@ -94,12 +95,12 @@
}
/// Storage: Fungible Balance (r:2 w:2)
/// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
- fn transfer() -> Weight {
+ fn transfer_raw() -> Weight {
// Proof Size summary in bytes:
// Measured: `182`
// Estimated: `5104`
- // Minimum execution time: 13_832_000 picoseconds.
- Weight::from_parts(14_064_000, 5104)
+ // Minimum execution time: 6_678_000 picoseconds.
+ Weight::from_parts(7_151_000, 5104)
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(2_u64))
}
@@ -129,19 +130,26 @@
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
- /// Storage: Fungible Allowance (r:1 w:1)
+ /// Storage: Fungible Allowance (r:1 w:0)
/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
- /// Storage: Fungible Balance (r:2 w:2)
- /// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
- fn transfer_from() -> Weight {
+ fn check_allowed_raw() -> Weight {
// Proof Size summary in bytes:
- // Measured: `300`
- // Estimated: `7672`
- // Minimum execution time: 21_667_000 picoseconds.
- Weight::from_parts(22_166_000, 7672)
- .saturating_add(T::DbWeight::get().reads(3_u64))
- .saturating_add(T::DbWeight::get().writes(3_u64))
+ // Measured: `210`
+ // Estimated: `2568`
+ // Minimum execution time: 2_842_000 picoseconds.
+ Weight::from_parts(3_077_000, 2568)
+ .saturating_add(T::DbWeight::get().reads(1_u64))
}
+ /// Storage: Fungible Allowance (r:0 w:1)
+ /// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
+ fn set_allowance_unchecked_raw() -> Weight {
+ // Proof Size summary in bytes:
+ // Measured: `0`
+ // Estimated: `0`
+ // Minimum execution time: 2_532_000 picoseconds.
+ Weight::from_parts(2_680_000, 0)
+ .saturating_add(T::DbWeight::get().writes(1_u64))
+ }
/// Storage: Fungible Allowance (r:1 w:1)
/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
/// Storage: Fungible TotalSupply (r:1 w:1)
@@ -208,12 +216,12 @@
}
/// Storage: Fungible Balance (r:2 w:2)
/// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
- fn transfer() -> Weight {
+ fn transfer_raw() -> Weight {
// Proof Size summary in bytes:
// Measured: `182`
// Estimated: `5104`
- // Minimum execution time: 13_832_000 picoseconds.
- Weight::from_parts(14_064_000, 5104)
+ // Minimum execution time: 6_678_000 picoseconds.
+ Weight::from_parts(7_151_000, 5104)
.saturating_add(RocksDbWeight::get().reads(2_u64))
.saturating_add(RocksDbWeight::get().writes(2_u64))
}
@@ -243,18 +251,25 @@
.saturating_add(RocksDbWeight::get().reads(1_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
- /// Storage: Fungible Allowance (r:1 w:1)
+ /// Storage: Fungible Allowance (r:1 w:0)
/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
- /// Storage: Fungible Balance (r:2 w:2)
- /// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
- fn transfer_from() -> Weight {
+ fn check_allowed_raw() -> Weight {
// Proof Size summary in bytes:
- // Measured: `300`
- // Estimated: `7672`
- // Minimum execution time: 21_667_000 picoseconds.
- Weight::from_parts(22_166_000, 7672)
- .saturating_add(RocksDbWeight::get().reads(3_u64))
- .saturating_add(RocksDbWeight::get().writes(3_u64))
+ // Measured: `210`
+ // Estimated: `2568`
+ // Minimum execution time: 2_842_000 picoseconds.
+ Weight::from_parts(3_077_000, 2568)
+ .saturating_add(RocksDbWeight::get().reads(1_u64))
+ }
+ /// Storage: Fungible Allowance (r:0 w:1)
+ /// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
+ fn set_allowance_unchecked_raw() -> Weight {
+ // Proof Size summary in bytes:
+ // Measured: `0`
+ // Estimated: `0`
+ // Minimum execution time: 2_532_000 picoseconds.
+ Weight::from_parts(2_680_000, 0)
+ .saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: Fungible Allowance (r:1 w:1)
/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
pallets/nonfungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -4,6 +4,12 @@
<!-- bureaucrate goes here -->
+## [0.1.14] - 2023-03-28
+
+### Fixed
+
+- The weight of `transfer` and `transfer_from`.
+
## [0.1.13] - 2023-01-20
### Fixed
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2021"
license = "GPLv3"
name = "pallet-nonfungible"
-version = "0.1.13"
+version = "0.1.14"
[dependencies]
# Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -121,7 +121,7 @@
}
}: {<Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)?}
- transfer {
+ transfer_raw {
bench_init!{
owner: sub; collection: collection(owner);
owner: cross_from_sub; sender: cross_sub; receiver: cross_sub;
@@ -146,14 +146,14 @@
let item = create_max_item(&collection, &owner, owner_eth.clone())?;
}: {<Pallet<T>>::set_allowance_from(&collection, &sender, &owner_eth, item, Some(&spender))?}
- transfer_from {
+ check_allowed_raw {
bench_init!{
owner: sub; collection: collection(owner);
owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
};
let item = create_max_item(&collection, &owner, sender.clone())?;
<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?;
- }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, &Unlimited)?}
+ }: {<Pallet<T>>::check_allowed(&collection, &spender, &sender, item, &Unlimited)?}
burn_from {
bench_init!{
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -23,7 +23,7 @@
};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
- weights::WeightInfo as _,
+ weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
};
use sp_runtime::DispatchError;
use sp_std::{vec::Vec, vec};
@@ -91,7 +91,7 @@
}
fn transfer() -> Weight {
- <SelfWeightOf<T>>::transfer()
+ <SelfWeightOf<T>>::transfer_raw() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
}
fn approve() -> Weight {
@@ -103,7 +103,7 @@
}
fn transfer_from() -> Weight {
- <SelfWeightOf<T>>::transfer_from()
+ Self::transfer() + <SelfWeightOf<T>>::check_allowed_raw()
}
fn burn_from() -> Weight {
@@ -325,10 +325,7 @@
) -> DispatchResultWithPostInfo {
ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
if amount == 1 {
- with_weight(
- <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),
- <CommonWeights<T>>::transfer(),
- )
+ <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget)
} else {
<Pallet<T>>::check_token_immediate_ownership(self, token, &from)?;
Ok(().into())
@@ -386,10 +383,7 @@
ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
if amount == 1 {
- with_weight(
- <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),
- <CommonWeights<T>>::transfer_from(),
- )
+ <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget)
} else {
<Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -39,6 +39,7 @@
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
eth::{self, TokenUri},
+ CommonWeightInfo,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::call;
@@ -47,7 +48,7 @@
use crate::{
AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
- TokenProperties, SelfWeightOf, weights::WeightInfo,
+ TokenProperties, SelfWeightOf, weights::WeightInfo, common::CommonWeights,
};
/// Nft events.
@@ -458,7 +459,7 @@
/// @param from The current owner of the NFT
/// @param to The new owner
/// @param tokenId The NFT to transfer
- #[weight(<SelfWeightOf<T>>::transfer_from())]
+ #[weight(<CommonWeights<T>>::transfer_from())]
fn transfer_from(
&mut self,
caller: Caller,
@@ -475,7 +476,7 @@
.weight_calls_budget(<StructureWeight<T>>::find_parent());
<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)
- .map_err(dispatch_to_evm::<T>)?;
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(())
}
@@ -824,7 +825,7 @@
/// is the zero address. Throws if `tokenId` is not a valid NFT.
/// @param to The new owner
/// @param tokenId The NFT to transfer
- #[weight(<SelfWeightOf<T>>::transfer())]
+ #[weight(<CommonWeights<T>>::transfer())]
fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
@@ -833,7 +834,8 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::transfer(self, &caller, &to, token, &budget)
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(())
}
@@ -842,7 +844,7 @@
/// is the zero address. Throws if `tokenId` is not a valid NFT.
/// @param to The new owner
/// @param tokenId The NFT to transfer
- #[weight(<SelfWeightOf<T>>::transfer())]
+ #[weight(<CommonWeights<T>>::transfer())]
fn transfer_cross(
&mut self,
caller: Caller,
@@ -856,7 +858,8 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::transfer(self, &caller, &to, token, &budget)
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(())
}
@@ -866,7 +869,7 @@
/// @param from Cross acccount address of current owner
/// @param to Cross acccount address of new owner
/// @param tokenId The NFT to transfer
- #[weight(<SelfWeightOf<T>>::transfer())]
+ #[weight(<CommonWeights<T>>::transfer_from())]
fn transfer_from_cross(
&mut self,
caller: Caller,
@@ -882,7 +885,7 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)
- .map_err(dispatch_to_evm::<T>)?;
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(())
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -108,7 +108,8 @@
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
- eth::collection_id_to_address,
+ eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
+ weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
};
use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
@@ -802,12 +803,13 @@
to: &T::CrossAccountId,
token: TokenId,
nesting_budget: &dyn Budget,
- ) -> DispatchResult {
+ ) -> DispatchResultWithPostInfo {
ensure!(
collection.limits.transfers_enabled(),
<CommonError<T>>::TransferNotAllowed
);
+ let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();
let token_data =
<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);
@@ -815,6 +817,7 @@
if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(from)?;
collection.check_allowlist(to)?;
+ actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;
}
<PalletCommon<T>>::ensure_correct_receiver(to)?;
@@ -884,7 +887,11 @@
to.clone(),
1,
));
- Ok(())
+
+ Ok(PostDispatchInfo {
+ actual_weight: Some(actual_weight),
+ pays_fee: Pays::Yes,
+ })
}
/// Batch operation to mint multiple NFT tokens.
@@ -1228,13 +1235,15 @@
to: &T::CrossAccountId,
token: TokenId,
nesting_budget: &dyn Budget,
- ) -> DispatchResult {
+ ) -> DispatchResultWithPostInfo {
Self::check_allowed(collection, spender, from, token, nesting_budget)?;
// =========
// Allowance is reset in [`transfer`]
- Self::transfer(collection, from, to, token, nesting_budget)
+ let mut result = Self::transfer(collection, from, to, token, nesting_budget);
+ add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());
+ result
}
/// Burn NFT token for `from` account.
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -40,10 +40,10 @@
fn burn_item() -> Weight;
fn burn_recursively_self_raw() -> Weight;
fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight;
- fn transfer() -> Weight;
+ fn transfer_raw() -> Weight;
fn approve() -> Weight;
fn approve_from() -> Weight;
- fn transfer_from() -> Weight;
+ fn check_allowed_raw() -> Weight;
fn burn_from() -> Weight;
fn set_token_property_permissions(b: u32, ) -> Weight;
fn set_token_properties(b: u32, ) -> Weight;
@@ -217,12 +217,12 @@
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
/// Storage: Nonfungible Owned (r:0 w:2)
/// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
- fn transfer() -> Weight {
+ fn transfer_raw() -> Weight {
// Proof Size summary in bytes:
// Measured: `412`
// Estimated: `10144`
- // Minimum execution time: 18_629_000 picoseconds.
- Weight::from_parts(18_997_000, 10144)
+ // Minimum execution time: 9_307_000 picoseconds.
+ Weight::from_parts(10_108_000, 10144)
.saturating_add(T::DbWeight::get().reads(4_u64))
.saturating_add(T::DbWeight::get().writes(5_u64))
}
@@ -252,22 +252,15 @@
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
- /// Storage: Nonfungible Allowance (r:1 w:1)
+ /// Storage: Nonfungible Allowance (r:1 w:0)
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
- /// Storage: Nonfungible TokenData (r:1 w:1)
- /// Proof: Nonfungible TokenData (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
- /// Storage: Nonfungible AccountBalance (r:2 w:2)
- /// Proof: Nonfungible AccountBalance (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
- /// Storage: Nonfungible Owned (r:0 w:2)
- /// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
- fn transfer_from() -> Weight {
+ fn check_allowed_raw() -> Weight {
// Proof Size summary in bytes:
- // Measured: `527`
- // Estimated: `10144`
- // Minimum execution time: 24_919_000 picoseconds.
- Weight::from_parts(25_333_000, 10144)
- .saturating_add(T::DbWeight::get().reads(4_u64))
- .saturating_add(T::DbWeight::get().writes(6_u64))
+ // Measured: `394`
+ // Estimated: `2532`
+ // Minimum execution time: 2_668_000 picoseconds.
+ Weight::from_parts(2_877_000, 2532)
+ .saturating_add(T::DbWeight::get().reads(1_u64))
}
/// Storage: Nonfungible Allowance (r:1 w:1)
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
@@ -543,12 +536,12 @@
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
/// Storage: Nonfungible Owned (r:0 w:2)
/// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
- fn transfer() -> Weight {
+ fn transfer_raw() -> Weight {
// Proof Size summary in bytes:
// Measured: `412`
// Estimated: `10144`
- // Minimum execution time: 18_629_000 picoseconds.
- Weight::from_parts(18_997_000, 10144)
+ // Minimum execution time: 9_307_000 picoseconds.
+ Weight::from_parts(10_108_000, 10144)
.saturating_add(RocksDbWeight::get().reads(4_u64))
.saturating_add(RocksDbWeight::get().writes(5_u64))
}
@@ -578,22 +571,15 @@
.saturating_add(RocksDbWeight::get().reads(2_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
- /// Storage: Nonfungible Allowance (r:1 w:1)
+ /// Storage: Nonfungible Allowance (r:1 w:0)
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
- /// Storage: Nonfungible TokenData (r:1 w:1)
- /// Proof: Nonfungible TokenData (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
- /// Storage: Nonfungible AccountBalance (r:2 w:2)
- /// Proof: Nonfungible AccountBalance (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
- /// Storage: Nonfungible Owned (r:0 w:2)
- /// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
- fn transfer_from() -> Weight {
+ fn check_allowed_raw() -> Weight {
// Proof Size summary in bytes:
- // Measured: `527`
- // Estimated: `10144`
- // Minimum execution time: 24_919_000 picoseconds.
- Weight::from_parts(25_333_000, 10144)
- .saturating_add(RocksDbWeight::get().reads(4_u64))
- .saturating_add(RocksDbWeight::get().writes(6_u64))
+ // Measured: `394`
+ // Estimated: `2532`
+ // Minimum execution time: 2_668_000 picoseconds.
+ Weight::from_parts(2_877_000, 2532)
+ .saturating_add(RocksDbWeight::get().reads(1_u64))
}
/// Storage: Nonfungible Allowance (r:1 w:1)
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)