difftreelog
refactor(weight) bench rename `transfer` to `transfer_raw`
in: master
8 files changed
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;
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -78,7 +78,7 @@
}
fn transfer() -> Weight {
- <SelfWeightOf<T>>::transfer() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
+ <SelfWeightOf<T>>::transfer_raw() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
}
fn approve() -> Weight {
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::{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();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,7 +37,7 @@
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 check_allowed_raw() -> Weight;
@@ -93,16 +93,11 @@
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(2_u64))
}
- /// Storage: Fungible Balance (r:2 w:2)
- /// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
- fn transfer() -> Weight {
- // Proof Size summary in bytes:
- // Measured: `182`
- // Estimated: `5104`
- // Minimum execution time: 13_832_000 picoseconds.
- Weight::from_parts(14_064_000, 5104)
- .saturating_add(T::DbWeight::get().reads(2_u64))
- .saturating_add(T::DbWeight::get().writes(2_u64))
+ // Storage: Fungible Balance (r:2 w:2)
+ fn transfer_raw() -> Weight {
+ Weight::from_ref_time(12_041_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(2 as u64))
+ .saturating_add(T::DbWeight::get().writes(2 as u64))
}
/// Storage: Fungible Balance (r:1 w:0)
/// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
@@ -205,16 +200,11 @@
.saturating_add(RocksDbWeight::get().reads(2_u64))
.saturating_add(RocksDbWeight::get().writes(2_u64))
}
- /// Storage: Fungible Balance (r:2 w:2)
- /// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
- fn transfer() -> Weight {
- // Proof Size summary in bytes:
- // Measured: `182`
- // Estimated: `5104`
- // Minimum execution time: 13_832_000 picoseconds.
- Weight::from_parts(14_064_000, 5104)
- .saturating_add(RocksDbWeight::get().reads(2_u64))
- .saturating_add(RocksDbWeight::get().writes(2_u64))
+ // Storage: Fungible Balance (r:2 w:2)
+ fn transfer_raw() -> Weight {
+ Weight::from_ref_time(12_041_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(2 as u64))
+ .saturating_add(RocksDbWeight::get().writes(2 as u64))
}
/// Storage: Fungible Balance (r:1 w:0)
/// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
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;
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -91,7 +91,7 @@
}
fn transfer() -> Weight {
- <SelfWeightOf<T>>::transfer() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
+ <SelfWeightOf<T>>::transfer_raw() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
}
fn approve() -> Weight {
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -809,7 +809,7 @@
<CommonError<T>>::TransferNotAllowed
);
- let mut actual_weight = <SelfWeightOf<T>>::transfer();
+ 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);
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -40,7 +40,7 @@
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 checks_allowed_raw() -> Weight;
@@ -209,22 +209,14 @@
.saturating_add(T::DbWeight::get().writes((4_u64).saturating_mul(b.into())))
.saturating_add(Weight::from_parts(0, 10097).saturating_mul(b.into()))
}
- /// 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 Allowance (r:1 w:0)
- /// 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 {
- // Proof Size summary in bytes:
- // Measured: `412`
- // Estimated: `10144`
- // Minimum execution time: 18_629_000 picoseconds.
- Weight::from_parts(18_997_000, 10144)
- .saturating_add(T::DbWeight::get().reads(4_u64))
- .saturating_add(T::DbWeight::get().writes(5_u64))
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:2 w:2)
+ // Storage: Nonfungible Allowance (r:1 w:0)
+ // Storage: Nonfungible Owned (r:0 w:2)
+ fn transfer_raw() -> Weight {
+ Weight::from_ref_time(14_909_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(4 as u64))
+ .saturating_add(T::DbWeight::get().writes(5 as u64))
}
/// Storage: Nonfungible TokenData (r:1 w:0)
/// Proof: Nonfungible TokenData (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
@@ -523,22 +515,14 @@
.saturating_add(RocksDbWeight::get().writes((4_u64).saturating_mul(b.into())))
.saturating_add(Weight::from_parts(0, 10097).saturating_mul(b.into()))
}
- /// 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 Allowance (r:1 w:0)
- /// 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 {
- // Proof Size summary in bytes:
- // Measured: `412`
- // Estimated: `10144`
- // Minimum execution time: 18_629_000 picoseconds.
- Weight::from_parts(18_997_000, 10144)
- .saturating_add(RocksDbWeight::get().reads(4_u64))
- .saturating_add(RocksDbWeight::get().writes(5_u64))
+ // Storage: Nonfungible TokenData (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:2 w:2)
+ // Storage: Nonfungible Allowance (r:1 w:0)
+ // Storage: Nonfungible Owned (r:0 w:2)
+ fn transfer_raw() -> Weight {
+ Weight::from_ref_time(14_909_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(4 as u64))
+ .saturating_add(RocksDbWeight::get().writes(5 as u64))
}
/// Storage: Nonfungible TokenData (r:1 w:0)
/// Proof: Nonfungible TokenData (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)