difftreelog
misk: generalize 2 methods
in: master
3 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -66,10 +66,11 @@
ensure,
traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},
dispatch::Pays,
- transactional,
+ transactional, fail,
};
use pallet_evm::GasWeightMapping;
use up_data_structs::{
+ AccessMode,
COLLECTION_NUMBER_LIMIT,
Collection,
RpcCollection,
@@ -124,6 +125,8 @@
pub use pallet::*;
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
+
+use crate::erc::CollectionHelpersEvents;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
pub mod dispatch;
@@ -1264,6 +1267,128 @@
Ok(())
}
+ /// A batch operation to add, edit or remove properties for a token.
+ /// It sets or removes a token's properties according to
+ /// `properties_updates` contents:
+ /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
+ /// * removes a property under the <key> if the value is `None` `(<key>, None)`.
+ ///
+ /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
+ /// - `is_token_create`: Indicates that method is called during token initialization.
+ /// Allows to bypass ownership check.
+ ///
+ /// All affected properties should have `mutable` permission
+ /// to be **deleted** or to be **set more than once**,
+ /// and the sender should have permission to edit those properties.
+ ///
+ /// This function fires an event for each property change.
+ /// In case of an error, all the changes (including the events) will be reverted
+ /// since the function is transactional.
+ pub fn modify_token_properties(
+ collection: &CollectionHandle<T>,
+ sender: &T::CrossAccountId,
+ token_id: TokenId,
+ properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+ is_token_create: bool,
+ mut stored_properties: Properties,
+ is_token_owner: impl Fn() -> Result<bool, DispatchError>,
+ set_token_properties: impl FnOnce(Properties),
+ ) -> DispatchResult {
+ let is_collection_admin = collection.is_owner_or_admin(sender);
+ let permissions = Self::property_permissions(collection.id);
+
+ for (key, value) in properties_updates {
+ let permission = permissions
+ .get(&key)
+ .cloned()
+ .unwrap_or_else(PropertyPermission::none);
+
+ let is_property_exists = stored_properties.get(&key).is_some();
+
+ match permission {
+ PropertyPermission { mutable: false, .. } if is_property_exists => {
+ return Err(<Error<T>>::NoPermission.into());
+ }
+
+ PropertyPermission {
+ collection_admin,
+ token_owner,
+ ..
+ } => {
+ //TODO: investigate threats during public minting.
+ let is_token_create =
+ is_token_create && (collection_admin || token_owner) && value.is_some();
+ if !(is_token_create
+ || (collection_admin && is_collection_admin)
+ || (token_owner && is_token_owner()?))
+ {
+ fail!(<Error<T>>::NoPermission);
+ }
+ }
+ }
+
+ match value {
+ Some(value) => {
+ stored_properties
+ .try_set(key.clone(), value)
+ .map_err(<Error<T>>::from)?;
+
+ Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));
+ }
+ None => {
+ stored_properties.remove(&key).map_err(<Error<T>>::from)?;
+
+ Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));
+ }
+ }
+
+ <PalletEvm<T>>::deposit_log(
+ CollectionHelpersEvents::TokenChanged {
+ collection_id: eth::collection_id_to_address(collection.id),
+ token_id: token_id.into(),
+ }
+ .to_log(T::ContractAddress::get()),
+ );
+ }
+
+ set_token_properties(stored_properties);
+
+ Ok(())
+ }
+
+ /// Sets or unsets the approval of a given operator.
+ ///
+ /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.
+ /// - `owner`: Token owner
+ /// - `operator`: Operator
+ /// - `approve`: Should operator status be granted or revoked?
+ pub fn set_allowance_for_all(
+ collection: &CollectionHandle<T>,
+ owner: &T::CrossAccountId,
+ operator: &T::CrossAccountId,
+ approve: bool,
+ set_allowance: impl FnOnce(),
+ log: evm_coder::ethereum::Log,
+ ) -> DispatchResult {
+ if collection.permissions.access() == AccessMode::AllowList {
+ collection.check_allowlist(owner)?;
+ collection.check_allowlist(operator)?;
+ }
+
+ Self::ensure_correct_receiver(operator)?;
+
+ set_allowance();
+
+ <PalletEvm<T>>::deposit_log(log);
+ Self::deposit_event(Event::ApprovedForAll(
+ collection.id,
+ owner.clone(),
+ operator.clone(),
+ approve,
+ ));
+ Ok(())
+ }
+
/// Set collection property.
///
/// * `collection` - Collection handler.
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -101,18 +101,18 @@
};
use up_data_structs::{
AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,
- CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission,
- PropertyKey, PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,
- TokenChild, AuxPropertyValue, PropertiesPermissionMap,
+ CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey,
+ PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty, TokenChild,
+ AuxPropertyValue, PropertiesPermissionMap,
};
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, erc::CollectionHelpersEvents,
+ eth::collection_id_to_address,
};
use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use sp_core::{H160, Get};
+use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use core::ops::Deref;
@@ -578,10 +578,6 @@
}
/// A batch operation to add, edit or remove properties for a token.
- /// It sets or removes a token's properties according to
- /// `properties_updates` contents:
- /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
- /// * removes a property under the <key> if the value is `None` `(<key>, None)`.
///
/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
/// - `is_token_create`: Indicates that method is called during token initialization.
@@ -603,97 +599,30 @@
is_token_create: bool,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let mut collection_admin_status = None;
- let mut token_owner_result = None;
-
- let mut is_collection_admin =
- || *collection_admin_status.get_or_insert_with(|| collection.is_owner_or_admin(sender));
+ let is_token_owner = || {
+ let is_owned = <PalletStructure<T>>::check_indirectly_owned(
+ sender.clone(),
+ collection.id,
+ token_id,
+ None,
+ nesting_budget,
+ )?;
- let mut is_token_owner = || {
- *token_owner_result.get_or_insert_with(|| -> Result<bool, DispatchError> {
- let is_owned = <PalletStructure<T>>::check_indirectly_owned(
- sender.clone(),
- collection.id,
- token_id,
- None,
- nesting_budget,
- )?;
-
- Ok(is_owned)
- })
+ Ok(is_owned)
};
-
- let mut stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
- let permissions = <PalletCommon<T>>::property_permissions(collection.id);
-
- for (key, value) in properties_updates {
- let permission = permissions
- .get(&key)
- .cloned()
- .unwrap_or_else(PropertyPermission::none);
-
- let is_property_exists = stored_properties.get(&key).is_some();
-
- match permission {
- PropertyPermission { mutable: false, .. } if is_property_exists => {
- return Err(<CommonError<T>>::NoPermission.into());
- }
-
- PropertyPermission {
- collection_admin,
- token_owner,
- ..
- } => {
- //TODO: investigate threats during public minting.
- if is_token_create && (collection_admin || token_owner) && value.is_some() {
- // Pass
- } else if collection_admin && is_collection_admin() {
- // Pass
- } else if token_owner && is_token_owner()? {
- // Pass
- } else {
- fail!(<CommonError<T>>::NoPermission);
- }
- }
- }
- match value {
- Some(value) => {
- stored_properties
- .try_set(key.clone(), value)
- .map_err(<CommonError<T>>::from)?;
-
- <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(
- collection.id,
- token_id,
- key,
- ));
- }
- None => {
- stored_properties
- .remove(&key)
- .map_err(<CommonError<T>>::from)?;
-
- <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
- collection.id,
- token_id,
- key,
- ));
- }
- }
-
- <PalletEvm<T>>::deposit_log(
- CollectionHelpersEvents::TokenChanged {
- collection_id: collection_id_to_address(collection.id),
- token_id: token_id.into(),
- }
- .to_log(T::ContractAddress::get()),
- );
- }
-
- <TokenProperties<T>>::set((collection.id, token_id), stored_properties);
+ let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
- Ok(())
+ <PalletCommon<T>>::modify_token_properties(
+ collection,
+ sender,
+ token_id,
+ properties_updates,
+ is_token_create,
+ stored_properties,
+ is_token_owner,
+ |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
+ )
}
/// Batch operation to add or edit properties for the token
@@ -1418,31 +1347,19 @@
operator: &T::CrossAccountId,
approve: bool,
) -> DispatchResult {
- if collection.permissions.access() == AccessMode::AllowList {
- collection.check_allowlist(owner)?;
- collection.check_allowlist(operator)?;
- }
-
- <PalletCommon<T>>::ensure_correct_receiver(operator)?;
-
- // =========
-
- <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);
- <PalletEvm<T>>::deposit_log(
+ <PalletCommon<T>>::set_allowance_for_all(
+ collection,
+ owner,
+ operator,
+ approve,
+ || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),
ERC721Events::ApprovalForAll {
owner: *owner.as_eth(),
operator: *operator.as_eth(),
approved: approve,
}
.to_log(collection_id_to_address(collection.id)),
- );
- <PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(
- collection.id,
- owner.clone(),
- operator.clone(),
- approve,
- ));
- Ok(())
+ )
}
/// Tells whether the given `owner` approves the `operator`.
pallets/refungible/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//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//! of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//! Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//! transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//! an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//! with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//! collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//! Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{ensure, fail, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99 CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,100 Event as CommonEvent, Pallet as PalletCommon, erc::CollectionHelpersEvents,101};102use pallet_structure::Pallet as PalletStructure;103use sp_core::{Get, H160};104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107 AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,108 mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,109 PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue, TokenId,110 TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120121pub type CreateItemData<T> =122 CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;123pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;124125#[frame_support::pallet]126pub mod pallet {127 use super::*;128 use frame_support::{129 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,130 traits::StorageVersion,131 };132 use up_data_structs::{CollectionId, TokenId};133 use super::weights::WeightInfo;134135 #[pallet::error]136 pub enum Error<T> {137 /// Not Refungible item data used to mint in Refungible collection.138 NotRefungibleDataUsedToMintFungibleCollectionToken,139 /// Maximum refungibility exceeded.140 WrongRefungiblePieces,141 /// Refungible token can't be repartitioned by user who isn't owns all pieces.142 RepartitionWhileNotOwningAllPieces,143 /// Refungible token can't nest other tokens.144 RefungibleDisallowsNesting,145 /// Setting item properties is not allowed.146 SettingPropertiesNotAllowed,147 }148149 #[pallet::config]150 pub trait Config:151 frame_system::Config + pallet_common::Config + pallet_structure::Config152 {153 type WeightInfo: WeightInfo;154 }155156 const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);157158 #[pallet::pallet]159 #[pallet::storage_version(STORAGE_VERSION)]160 #[pallet::generate_store(pub(super) trait Store)]161 pub struct Pallet<T>(_);162163 /// Total amount of minted tokens in a collection.164 #[pallet::storage]165 pub type TokensMinted<T: Config> =166 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;167168 /// Amount of tokens burnt in a collection.169 #[pallet::storage]170 pub type TokensBurnt<T: Config> =171 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;172173 /// Amount of pieces a refungible token is split into.174 #[pallet::storage]175 #[pallet::getter(fn token_properties)]176 pub type TokenProperties<T: Config> = StorageNMap<177 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),178 Value = up_data_structs::Properties,179 QueryKind = ValueQuery,180 OnEmpty = up_data_structs::TokenProperties,181 >;182183 /// Total amount of pieces for token184 #[pallet::storage]185 pub type TotalSupply<T: Config> = StorageNMap<186 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),187 Value = u128,188 QueryKind = ValueQuery,189 >;190191 /// Used to enumerate tokens owned by account.192 #[pallet::storage]193 pub type Owned<T: Config> = StorageNMap<194 Key = (195 Key<Twox64Concat, CollectionId>,196 Key<Blake2_128Concat, T::CrossAccountId>,197 Key<Twox64Concat, TokenId>,198 ),199 Value = bool,200 QueryKind = ValueQuery,201 >;202203 /// Amount of tokens (not pieces) partially owned by an account within a collection.204 #[pallet::storage]205 pub type AccountBalance<T: Config> = StorageNMap<206 Key = (207 Key<Twox64Concat, CollectionId>,208 // Owner209 Key<Blake2_128Concat, T::CrossAccountId>,210 ),211 Value = u32,212 QueryKind = ValueQuery,213 >;214215 /// Amount of token pieces owned by account.216 #[pallet::storage]217 pub type Balance<T: Config> = StorageNMap<218 Key = (219 Key<Twox64Concat, CollectionId>,220 Key<Twox64Concat, TokenId>,221 // Owner222 Key<Blake2_128Concat, T::CrossAccountId>,223 ),224 Value = u128,225 QueryKind = ValueQuery,226 >;227228 /// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.229 #[pallet::storage]230 pub type Allowance<T: Config> = StorageNMap<231 Key = (232 Key<Twox64Concat, CollectionId>,233 Key<Twox64Concat, TokenId>,234 // Owner235 Key<Blake2_128, T::CrossAccountId>,236 // Spender237 Key<Blake2_128Concat, T::CrossAccountId>,238 ),239 Value = u128,240 QueryKind = ValueQuery,241 >;242243 /// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.244 #[pallet::storage]245 pub type CollectionAllowance<T: Config> = StorageNMap<246 Key = (247 Key<Twox64Concat, CollectionId>,248 Key<Blake2_128Concat, T::CrossAccountId>,249 Key<Blake2_128Concat, T::CrossAccountId>,250 ),251 Value = bool,252 QueryKind = ValueQuery,253 >;254}255256pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);257impl<T: Config> RefungibleHandle<T> {258 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {259 Self(inner)260 }261 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {262 self.0263 }264 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {265 &mut self.0266 }267}268269impl<T: Config> Deref for RefungibleHandle<T> {270 type Target = pallet_common::CollectionHandle<T>;271272 fn deref(&self) -> &Self::Target {273 &self.0274 }275}276277impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {278 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {279 self.0.recorder()280 }281 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {282 self.0.into_recorder()283 }284}285286impl<T: Config> Pallet<T> {287 /// Get number of RFT tokens in collection288 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {289 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)290 }291292 /// Check that RFT token exists293 ///294 /// - `token`: Token ID.295 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {296 <TotalSupply<T>>::contains_key((collection.id, token))297 }298299 pub fn set_scoped_token_property(300 collection_id: CollectionId,301 token_id: TokenId,302 scope: PropertyScope,303 property: Property,304 ) -> DispatchResult {305 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {306 properties.try_scoped_set(scope, property.key, property.value)307 })308 .map_err(<CommonError<T>>::from)?;309310 Ok(())311 }312313 pub fn set_scoped_token_properties(314 collection_id: CollectionId,315 token_id: TokenId,316 scope: PropertyScope,317 properties: impl Iterator<Item = Property>,318 ) -> DispatchResult {319 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {320 stored_properties.try_scoped_set_from_iter(scope, properties)321 })322 .map_err(<CommonError<T>>::from)?;323324 Ok(())325 }326}327328// unchecked calls skips any permission checks329impl<T: Config> Pallet<T> {330 /// Create RFT collection331 ///332 /// `init_collection` will take non-refundable deposit for collection creation.333 ///334 /// - `data`: Contains settings for collection limits and permissions.335 pub fn init_collection(336 owner: T::CrossAccountId,337 payer: T::CrossAccountId,338 data: CreateCollectionData<T::AccountId>,339 flags: CollectionFlags,340 ) -> Result<CollectionId, DispatchError> {341 <PalletCommon<T>>::init_collection(owner, payer, data, flags)342 }343344 /// Destroy RFT collection345 ///346 /// `destroy_collection` will throw error if collection contains any tokens.347 /// Only owner can destroy collection.348 pub fn destroy_collection(349 collection: RefungibleHandle<T>,350 sender: &T::CrossAccountId,351 ) -> DispatchResult {352 let id = collection.id;353354 if Self::collection_has_tokens(id) {355 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());356 }357358 // =========359360 PalletCommon::destroy_collection(collection.0, sender)?;361362 <TokensMinted<T>>::remove(id);363 <TokensBurnt<T>>::remove(id);364 let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);365 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);366 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);367 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);368 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);369 Ok(())370 }371372 fn collection_has_tokens(collection_id: CollectionId) -> bool {373 <TotalSupply<T>>::iter_prefix((collection_id,))374 .next()375 .is_some()376 }377378 pub fn burn_token_unchecked(379 collection: &RefungibleHandle<T>,380 owner: &T::CrossAccountId,381 token_id: TokenId,382 ) -> DispatchResult {383 let burnt = <TokensBurnt<T>>::get(collection.id)384 .checked_add(1)385 .ok_or(ArithmeticError::Overflow)?;386387 <TokensBurnt<T>>::insert(collection.id, burnt);388 <TokenProperties<T>>::remove((collection.id, token_id));389 <TotalSupply<T>>::remove((collection.id, token_id));390 let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);391 let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);392 <PalletEvm<T>>::deposit_log(393 ERC721Events::Transfer {394 from: *owner.as_eth(),395 to: H160::default(),396 token_id: token_id.into(),397 }398 .to_log(collection_id_to_address(collection.id)),399 );400 Ok(())401 }402403 /// Burn RFT token pieces404 ///405 /// `burn` will decrease total amount of token pieces and amount owned by sender.406 /// `burn` can be called even if there are multiple owners of the RFT token.407 /// If sender wouldn't have any pieces left after `burn` than she will stop being408 /// one of the owners of the token. If there is no account that owns any pieces of409 /// the token than token will be burned too.410 ///411 /// - `amount`: Amount of token pieces to burn.412 /// - `token`: Token who's pieces should be burned413 /// - `collection`: Collection that contains the token414 pub fn burn(415 collection: &RefungibleHandle<T>,416 owner: &T::CrossAccountId,417 token: TokenId,418 amount: u128,419 ) -> DispatchResult {420 if <Balance<T>>::get((collection.id, token, owner)) == 0 {421 return Err(<CommonError<T>>::TokenValueTooLow.into());422 }423424 let total_supply = <TotalSupply<T>>::get((collection.id, token))425 .checked_sub(amount)426 .ok_or(<CommonError<T>>::TokenValueTooLow)?;427428 // This was probally last owner of this token?429 if total_supply == 0 {430 // Ensure user actually owns this amount431 ensure!(432 <Balance<T>>::get((collection.id, token, owner)) == amount,433 <CommonError<T>>::TokenValueTooLow434 );435 let account_balance = <AccountBalance<T>>::get((collection.id, owner))436 .checked_sub(1)437 // Should not occur438 .ok_or(ArithmeticError::Underflow)?;439440 // =========441442 <Owned<T>>::remove((collection.id, owner, token));443 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);444 <AccountBalance<T>>::insert((collection.id, owner), account_balance);445 Self::burn_token_unchecked(collection, owner, token)?;446 <PalletEvm<T>>::deposit_log(447 ERC20Events::Transfer {448 from: *owner.as_eth(),449 to: H160::default(),450 value: amount.into(),451 }452 .to_log(collection_id_to_address(collection.id)),453 );454 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(455 collection.id,456 token,457 owner.clone(),458 amount,459 ));460 return Ok(());461 }462463 let balance = <Balance<T>>::get((collection.id, token, owner))464 .checked_sub(amount)465 .ok_or(<CommonError<T>>::TokenValueTooLow)?;466 let account_balance = if balance == 0 {467 <AccountBalance<T>>::get((collection.id, owner))468 .checked_sub(1)469 // Should not occur470 .ok_or(ArithmeticError::Underflow)?471 } else {472 0473 };474475 // =========476477 if balance == 0 {478 <Owned<T>>::remove((collection.id, owner, token));479 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);480 <Balance<T>>::remove((collection.id, token, owner));481 <AccountBalance<T>>::insert((collection.id, owner), account_balance);482483 if let Ok(user) = Self::token_owner(collection.id, token) {484 <PalletEvm<T>>::deposit_log(485 ERC721Events::Transfer {486 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,487 to: *user.as_eth(),488 token_id: token.into(),489 }490 .to_log(collection_id_to_address(collection.id)),491 );492 }493 } else {494 <Balance<T>>::insert((collection.id, token, owner), balance);495 }496 <TotalSupply<T>>::insert((collection.id, token), total_supply);497498 <PalletEvm<T>>::deposit_log(499 ERC20Events::Transfer {500 from: *owner.as_eth(),501 to: H160::default(),502 value: amount.into(),503 }504 .to_log(T::EvmTokenAddressMapping::token_to_address(505 collection.id,506 token,507 )),508 );509 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(510 collection.id,511 token,512 owner.clone(),513 amount,514 ));515 Ok(())516 }517518 /// A batch operation to add, edit or remove properties for a token.519 /// It sets or removes a token's properties according to520 /// `properties_updates` contents:521 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`522 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.523 ///524 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.525 /// - `is_token_create`: Indicates that method is called during token initialization.526 /// Allows to bypass ownership check.527 ///528 /// All affected properties should have `mutable` permission529 /// to be **deleted** or to be **set more than once**,530 /// and the sender should have permission to edit those properties.531 ///532 /// This function fires an event for each property change.533 /// In case of an error, all the changes (including the events) will be reverted534 /// since the function is transactional.535 #[transactional]536 fn modify_token_properties(537 collection: &RefungibleHandle<T>,538 sender: &T::CrossAccountId,539 token_id: TokenId,540 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,541 is_token_create: bool,542 nesting_budget: &dyn Budget,543 ) -> DispatchResult {544 let is_collection_admin = || collection.is_owner_or_admin(sender);545 let is_token_owner = || -> Result<bool, DispatchError> {546 let balance = collection.balance(sender.clone(), token_id);547 let total_pieces: u128 =548 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);549 if balance != total_pieces {550 return Ok(false);551 }552553 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(554 sender.clone(),555 collection.id,556 token_id,557 None,558 nesting_budget,559 )?;560561 Ok(is_bundle_owner)562 };563564 let mut stored_properties = <TokenProperties<T>>::get((collection.id, token_id));565 let permissions = <PalletCommon<T>>::property_permissions(collection.id);566567 for (key, value) in properties_updates {568 let permission = permissions569 .get(&key)570 .cloned()571 .unwrap_or_else(PropertyPermission::none);572573 let is_property_exists = stored_properties.get(&key).is_some();574575 match permission {576 PropertyPermission { mutable: false, .. } if is_property_exists => {577 return Err(<CommonError<T>>::NoPermission.into());578 }579580 PropertyPermission {581 collection_admin,582 token_owner,583 ..584 } => {585 //TODO: investigate threats during public minting.586 let is_token_create =587 is_token_create && (collection_admin || token_owner) && value.is_some();588 if !(is_token_create589 || (collection_admin && is_collection_admin())590 || (token_owner && is_token_owner()?))591 {592 fail!(<CommonError<T>>::NoPermission);593 }594 }595 }596597 match value {598 Some(value) => {599 stored_properties600 .try_set(key.clone(), value)601 .map_err(<CommonError<T>>::from)?;602603 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(604 collection.id,605 token_id,606 key,607 ));608 }609 None => {610 stored_properties611 .remove(&key)612 .map_err(<CommonError<T>>::from)?;613614 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(615 collection.id,616 token_id,617 key,618 ));619 }620 }621622 <PalletEvm<T>>::deposit_log(623 CollectionHelpersEvents::TokenChanged {624 collection_id: collection_id_to_address(collection.id),625 token_id: token_id.into(),626 }627 .to_log(T::ContractAddress::get()),628 );629 }630631 <TokenProperties<T>>::set((collection.id, token_id), stored_properties);632633 Ok(())634 }635636 pub fn set_token_properties(637 collection: &RefungibleHandle<T>,638 sender: &T::CrossAccountId,639 token_id: TokenId,640 properties: impl Iterator<Item = Property>,641 is_token_create: bool,642 nesting_budget: &dyn Budget,643 ) -> DispatchResult {644 Self::modify_token_properties(645 collection,646 sender,647 token_id,648 properties.map(|p| (p.key, Some(p.value))),649 is_token_create,650 nesting_budget,651 )652 }653654 pub fn set_token_property(655 collection: &RefungibleHandle<T>,656 sender: &T::CrossAccountId,657 token_id: TokenId,658 property: Property,659 nesting_budget: &dyn Budget,660 ) -> DispatchResult {661 let is_token_create = false;662663 Self::set_token_properties(664 collection,665 sender,666 token_id,667 [property].into_iter(),668 is_token_create,669 nesting_budget,670 )671 }672673 pub fn delete_token_properties(674 collection: &RefungibleHandle<T>,675 sender: &T::CrossAccountId,676 token_id: TokenId,677 property_keys: impl Iterator<Item = PropertyKey>,678 nesting_budget: &dyn Budget,679 ) -> DispatchResult {680 let is_token_create = false;681682 Self::modify_token_properties(683 collection,684 sender,685 token_id,686 property_keys.into_iter().map(|key| (key, None)),687 is_token_create,688 nesting_budget,689 )690 }691692 pub fn delete_token_property(693 collection: &RefungibleHandle<T>,694 sender: &T::CrossAccountId,695 token_id: TokenId,696 property_key: PropertyKey,697 nesting_budget: &dyn Budget,698 ) -> DispatchResult {699 Self::delete_token_properties(700 collection,701 sender,702 token_id,703 [property_key].into_iter(),704 nesting_budget,705 )706 }707708 /// Transfer RFT token pieces from one account to another.709 ///710 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.711 ///712 /// - `from`: Owner of token pieces to transfer.713 /// - `to`: Recepient of transfered token pieces.714 /// - `amount`: Amount of token pieces to transfer.715 /// - `token`: Token whos pieces should be transfered716 /// - `collection`: Collection that contains the token717 pub fn transfer(718 collection: &RefungibleHandle<T>,719 from: &T::CrossAccountId,720 to: &T::CrossAccountId,721 token: TokenId,722 amount: u128,723 nesting_budget: &dyn Budget,724 ) -> DispatchResult {725 ensure!(726 collection.limits.transfers_enabled(),727 <CommonError<T>>::TransferNotAllowed728 );729730 if collection.permissions.access() == AccessMode::AllowList {731 collection.check_allowlist(from)?;732 collection.check_allowlist(to)?;733 }734 <PalletCommon<T>>::ensure_correct_receiver(to)?;735736 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));737738 if initial_balance_from == 0 {739 return Err(<CommonError<T>>::TokenValueTooLow.into());740 }741742 let updated_balance_from = initial_balance_from743 .checked_sub(amount)744 .ok_or(<CommonError<T>>::TokenValueTooLow)?;745 let mut create_target = false;746 let from_to_differ = from != to;747 let updated_balance_to = if from != to && amount != 0 {748 let old_balance = <Balance<T>>::get((collection.id, token, to));749 if old_balance == 0 {750 create_target = true;751 }752 Some(753 old_balance754 .checked_add(amount)755 .ok_or(ArithmeticError::Overflow)?,756 )757 } else {758 None759 };760761 let account_balance_from = if updated_balance_from == 0 {762 Some(763 <AccountBalance<T>>::get((collection.id, from))764 .checked_sub(1)765 // Should not occur766 .ok_or(ArithmeticError::Underflow)?,767 )768 } else {769 None770 };771 // Account data is created in token, AccountBalance should be increased772 // But only if from != to as we shouldn't check overflow in this case773 let account_balance_to = if create_target && from_to_differ {774 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))775 .checked_add(1)776 .ok_or(ArithmeticError::Overflow)?;777 ensure!(778 account_balance_to < collection.limits.account_token_ownership_limit(),779 <CommonError<T>>::AccountTokenLimitExceeded,780 );781782 Some(account_balance_to)783 } else {784 None785 };786787 // =========788789 if let Some(updated_balance_to) = updated_balance_to {790 // from != to && amount != 0791792 <PalletStructure<T>>::nest_if_sent_to_token(793 from.clone(),794 to,795 collection.id,796 token,797 nesting_budget,798 )?;799800 if updated_balance_from == 0 {801 <Balance<T>>::remove((collection.id, token, from));802 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);803 } else {804 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);805 }806 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);807 if let Some(account_balance_from) = account_balance_from {808 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);809 <Owned<T>>::remove((collection.id, from, token));810 }811 if let Some(account_balance_to) = account_balance_to {812 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);813 <Owned<T>>::insert((collection.id, to, token), true);814 }815 }816817 <PalletEvm<T>>::deposit_log(818 ERC20Events::Transfer {819 from: *from.as_eth(),820 to: *to.as_eth(),821 value: amount.into(),822 }823 .to_log(T::EvmTokenAddressMapping::token_to_address(824 collection.id,825 token,826 )),827 );828829 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(830 collection.id,831 token,832 from.clone(),833 to.clone(),834 amount,835 ));836837 let total_supply = <TotalSupply<T>>::get((collection.id, token));838839 if amount == total_supply {840 // if token was fully owned by `from` and will be fully owned by `to` after transfer841 <PalletEvm<T>>::deposit_log(842 ERC721Events::Transfer {843 from: *from.as_eth(),844 to: *to.as_eth(),845 token_id: token.into(),846 }847 .to_log(collection_id_to_address(collection.id)),848 );849 } else if let Some(updated_balance_to) = updated_balance_to {850 // if `from` not equals `to`. This condition is needed to avoid sending event851 // when `from` fully owns token and sends part of token pieces to itself.852 if initial_balance_from == total_supply {853 // if token was fully owned by `from` and will be only partially owned by `to`854 // and `from` after transfer855 <PalletEvm<T>>::deposit_log(856 ERC721Events::Transfer {857 from: *from.as_eth(),858 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,859 token_id: token.into(),860 }861 .to_log(collection_id_to_address(collection.id)),862 );863 } else if updated_balance_to == total_supply {864 // if token was partially owned by `from` and will be fully owned by `to` after transfer865 <PalletEvm<T>>::deposit_log(866 ERC721Events::Transfer {867 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,868 to: *to.as_eth(),869 token_id: token.into(),870 }871 .to_log(collection_id_to_address(collection.id)),872 );873 }874 }875876 Ok(())877 }878879 /// Batched operation to create multiple RFT tokens.880 ///881 /// Same as `create_item` but creates multiple tokens.882 ///883 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.884 pub fn create_multiple_items(885 collection: &RefungibleHandle<T>,886 sender: &T::CrossAccountId,887 data: Vec<CreateItemData<T>>,888 nesting_budget: &dyn Budget,889 ) -> DispatchResult {890 if !collection.is_owner_or_admin(sender) {891 ensure!(892 collection.permissions.mint_mode(),893 <CommonError<T>>::PublicMintingNotAllowed894 );895 collection.check_allowlist(sender)?;896897 for item in data.iter() {898 for user in item.users.keys() {899 collection.check_allowlist(user)?;900 }901 }902 }903904 for item in data.iter() {905 for (owner, _) in item.users.iter() {906 <PalletCommon<T>>::ensure_correct_receiver(owner)?;907 }908 }909910 // Total pieces per tokens911 let totals = data912 .iter()913 .map(|data| {914 Ok(data915 .users916 .iter()917 .map(|u| u.1)918 .try_fold(0u128, |acc, v| acc.checked_add(*v))919 .ok_or(ArithmeticError::Overflow)?)920 })921 .collect::<Result<Vec<_>, DispatchError>>()?;922 for total in &totals {923 ensure!(924 *total <= MAX_REFUNGIBLE_PIECES,925 <Error<T>>::WrongRefungiblePieces926 );927 }928929 let first_token_id = <TokensMinted<T>>::get(collection.id);930 let tokens_minted = first_token_id931 .checked_add(data.len() as u32)932 .ok_or(ArithmeticError::Overflow)?;933 ensure!(934 tokens_minted < collection.limits.token_limit(),935 <CommonError<T>>::CollectionTokenLimitExceeded936 );937938 let mut balances = BTreeMap::new();939 for data in &data {940 for owner in data.users.keys() {941 let balance = balances942 .entry(owner)943 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));944 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;945946 ensure!(947 *balance <= collection.limits.account_token_ownership_limit(),948 <CommonError<T>>::AccountTokenLimitExceeded,949 );950 }951 }952953 for (i, token) in data.iter().enumerate() {954 let token_id = TokenId(first_token_id + i as u32 + 1);955 for (to, _) in token.users.iter() {956 <PalletStructure<T>>::check_nesting(957 sender.clone(),958 to,959 collection.id,960 token_id,961 nesting_budget,962 )?;963 }964 }965966 // =========967968 with_transaction(|| {969 for (i, data) in data.iter().enumerate() {970 let token_id = first_token_id + i as u32 + 1;971 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);972973 for (user, amount) in data.users.iter() {974 if *amount == 0 {975 continue;976 }977 <Balance<T>>::insert((collection.id, token_id, &user), amount);978 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);979 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(980 user,981 collection.id,982 TokenId(token_id),983 );984 }985986 if let Err(e) = Self::set_token_properties(987 collection,988 sender,989 TokenId(token_id),990 data.properties.clone().into_iter(),991 true,992 nesting_budget,993 ) {994 return TransactionOutcome::Rollback(Err(e));995 }996 }997 TransactionOutcome::Commit(Ok(()))998 })?;9991000 <TokensMinted<T>>::insert(collection.id, tokens_minted);10011002 for (account, balance) in balances {1003 <AccountBalance<T>>::insert((collection.id, account), balance);1004 }10051006 for (i, token) in data.into_iter().enumerate() {1007 let token_id = first_token_id + i as u32 + 1;10081009 let receivers = token1010 .users1011 .into_iter()1012 .filter(|(_, amount)| *amount > 0)1013 .collect::<Vec<_>>();10141015 if let [(user, _)] = receivers.as_slice() {1016 // if there is exactly one receiver1017 <PalletEvm<T>>::deposit_log(1018 ERC721Events::Transfer {1019 from: H160::default(),1020 to: *user.as_eth(),1021 token_id: token_id.into(),1022 }1023 .to_log(collection_id_to_address(collection.id)),1024 );1025 } else if let [_, ..] = receivers.as_slice() {1026 // if there is more than one receiver1027 <PalletEvm<T>>::deposit_log(1028 ERC721Events::Transfer {1029 from: H160::default(),1030 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1031 token_id: token_id.into(),1032 }1033 .to_log(collection_id_to_address(collection.id)),1034 );1035 }10361037 for (user, amount) in receivers.into_iter() {1038 <PalletEvm<T>>::deposit_log(1039 ERC20Events::Transfer {1040 from: H160::default(),1041 to: *user.as_eth(),1042 value: amount.into(),1043 }1044 .to_log(T::EvmTokenAddressMapping::token_to_address(1045 collection.id,1046 TokenId(token_id),1047 )),1048 );1049 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1050 collection.id,1051 TokenId(token_id),1052 user,1053 amount,1054 ));1055 }1056 }1057 Ok(())1058 }10591060 pub fn set_allowance_unchecked(1061 collection: &RefungibleHandle<T>,1062 sender: &T::CrossAccountId,1063 spender: &T::CrossAccountId,1064 token: TokenId,1065 amount: u128,1066 ) {1067 if amount == 0 {1068 <Allowance<T>>::remove((collection.id, token, sender, spender));1069 } else {1070 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);1071 }10721073 <PalletEvm<T>>::deposit_log(1074 ERC20Events::Approval {1075 owner: *sender.as_eth(),1076 spender: *spender.as_eth(),1077 value: amount.into(),1078 }1079 .to_log(T::EvmTokenAddressMapping::token_to_address(1080 collection.id,1081 token,1082 )),1083 );1084 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1085 collection.id,1086 token,1087 sender.clone(),1088 spender.clone(),1089 amount,1090 ))1091 }10921093 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1094 ///1095 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1096 pub fn set_allowance(1097 collection: &RefungibleHandle<T>,1098 sender: &T::CrossAccountId,1099 spender: &T::CrossAccountId,1100 token: TokenId,1101 amount: u128,1102 ) -> DispatchResult {1103 if collection.permissions.access() == AccessMode::AllowList {1104 collection.check_allowlist(sender)?;1105 collection.check_allowlist(spender)?;1106 }11071108 <PalletCommon<T>>::ensure_correct_receiver(spender)?;11091110 if <Balance<T>>::get((collection.id, token, sender)) < amount {1111 ensure!(1112 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1113 <CommonError<T>>::CantApproveMoreThanOwned1114 );1115 }11161117 // =========11181119 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1120 Ok(())1121 }11221123 /// Set allowance to spend from sender's eth mirror1124 ///1125 /// - `from`: Address of sender's eth mirror.1126 /// - `to`: Adress of spender.1127 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1128 pub fn set_allowance_from(1129 collection: &RefungibleHandle<T>,1130 sender: &T::CrossAccountId,1131 from: &T::CrossAccountId,1132 to: &T::CrossAccountId,1133 token_id: TokenId,1134 amount: u128,1135 ) -> DispatchResult {1136 if collection.permissions.access() == AccessMode::AllowList {1137 collection.check_allowlist(sender)?;1138 collection.check_allowlist(from)?;1139 collection.check_allowlist(to)?;1140 }11411142 <PalletCommon<T>>::ensure_correct_receiver(to)?;11431144 ensure!(1145 sender.conv_eq(from),1146 <CommonError<T>>::AddressIsNotEthMirror1147 );11481149 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1150 ensure!(1151 collection.limits.owner_can_transfer()1152 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1153 && Self::token_exists(collection, token_id),1154 <CommonError<T>>::CantApproveMoreThanOwned1155 );1156 }11571158 // =========11591160 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1161 Ok(())1162 }11631164 /// Returns allowance, which should be set after transaction1165 fn check_allowed(1166 collection: &RefungibleHandle<T>,1167 spender: &T::CrossAccountId,1168 from: &T::CrossAccountId,1169 token: TokenId,1170 amount: u128,1171 nesting_budget: &dyn Budget,1172 ) -> Result<Option<u128>, DispatchError> {1173 if spender.conv_eq(from) {1174 return Ok(None);1175 }1176 if collection.permissions.access() == AccessMode::AllowList {1177 // `from`, `to` checked in [`transfer`]1178 collection.check_allowlist(spender)?;1179 }11801181 if collection.ignores_token_restrictions(spender) {1182 return Ok(Self::compute_allowance_decrease(1183 collection, token, from, &spender, amount,1184 ));1185 }11861187 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1188 // TODO: should collection owner be allowed to perform this transfer?1189 ensure!(1190 <PalletStructure<T>>::check_indirectly_owned(1191 spender.clone(),1192 source.0,1193 source.1,1194 None,1195 nesting_budget1196 )?,1197 <CommonError<T>>::ApprovedValueTooLow,1198 );1199 return Ok(None);1200 }12011202 let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);1203 if allowance.is_some() {1204 return Ok(allowance);1205 }12061207 // Allowance (if any) would be reduced if spender is also wallet operator1208 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1209 return Ok(allowance);1210 }12111212 Err(<CommonError<T>>::ApprovedValueTooLow.into())1213 }12141215 /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1216 /// Otherwise, it returns `None`.1217 fn compute_allowance_decrease(1218 collection: &RefungibleHandle<T>,1219 token: TokenId,1220 from: &T::CrossAccountId,1221 spender: &T::CrossAccountId,1222 amount: u128,1223 ) -> Option<u128> {1224 <Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1225 }12261227 /// Transfer RFT token pieces from one account to another.1228 ///1229 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1230 /// The owner should set allowance for the spender to transfer pieces.1231 ///1232 /// [`transfer`]: struct.Pallet.html#method.transfer1233 pub fn transfer_from(1234 collection: &RefungibleHandle<T>,1235 spender: &T::CrossAccountId,1236 from: &T::CrossAccountId,1237 to: &T::CrossAccountId,1238 token: TokenId,1239 amount: u128,1240 nesting_budget: &dyn Budget,1241 ) -> DispatchResult {1242 let allowance =1243 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12441245 // =========12461247 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1248 if let Some(allowance) = allowance {1249 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1250 }1251 Ok(())1252 }12531254 /// Burn RFT token pieces from the account.1255 ///1256 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1257 /// set allowance for the spender to burn pieces1258 ///1259 /// [`burn`]: struct.Pallet.html#method.burn1260 pub fn burn_from(1261 collection: &RefungibleHandle<T>,1262 spender: &T::CrossAccountId,1263 from: &T::CrossAccountId,1264 token: TokenId,1265 amount: u128,1266 nesting_budget: &dyn Budget,1267 ) -> DispatchResult {1268 let allowance =1269 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12701271 // =========12721273 Self::burn(collection, from, token, amount)?;1274 if let Some(allowance) = allowance {1275 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1276 }1277 Ok(())1278 }12791280 /// Create RFT token.1281 ///1282 /// The sender should be the owner/admin of the collection or collection should be configured1283 /// to allow public minting.1284 ///1285 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1286 /// of token pieces they will receive.1287 pub fn create_item(1288 collection: &RefungibleHandle<T>,1289 sender: &T::CrossAccountId,1290 data: CreateItemData<T>,1291 nesting_budget: &dyn Budget,1292 ) -> DispatchResult {1293 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1294 }12951296 /// Repartition RFT token.1297 ///1298 /// `repartition` will set token balance of the sender and total amount of token pieces.1299 /// Sender should own all of the token pieces. `repartition' could be done even if some1300 /// token pieces were burned before.1301 ///1302 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1303 pub fn repartition(1304 collection: &RefungibleHandle<T>,1305 owner: &T::CrossAccountId,1306 token: TokenId,1307 amount: u128,1308 ) -> DispatchResult {1309 ensure!(1310 amount <= MAX_REFUNGIBLE_PIECES,1311 <Error<T>>::WrongRefungiblePieces1312 );1313 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1314 // Ensure user owns all pieces1315 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1316 let balance = <Balance<T>>::get((collection.id, token, owner));1317 ensure!(1318 total_pieces == balance,1319 <Error<T>>::RepartitionWhileNotOwningAllPieces1320 );13211322 <Balance<T>>::insert((collection.id, token, owner), amount);1323 <TotalSupply<T>>::insert((collection.id, token), amount);13241325 if amount > total_pieces {1326 let mint_amount = amount - total_pieces;1327 <PalletEvm<T>>::deposit_log(1328 ERC20Events::Transfer {1329 from: H160::default(),1330 to: *owner.as_eth(),1331 value: mint_amount.into(),1332 }1333 .to_log(T::EvmTokenAddressMapping::token_to_address(1334 collection.id,1335 token,1336 )),1337 );1338 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1339 collection.id,1340 token,1341 owner.clone(),1342 mint_amount,1343 ));1344 } else if total_pieces > amount {1345 let burn_amount = total_pieces - amount;1346 <PalletEvm<T>>::deposit_log(1347 ERC20Events::Transfer {1348 from: *owner.as_eth(),1349 to: H160::default(),1350 value: burn_amount.into(),1351 }1352 .to_log(T::EvmTokenAddressMapping::token_to_address(1353 collection.id,1354 token,1355 )),1356 );1357 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1358 collection.id,1359 token,1360 owner.clone(),1361 burn_amount,1362 ));1363 }13641365 Ok(())1366 }13671368 fn token_owner(1369 collection_id: CollectionId,1370 token_id: TokenId,1371 ) -> Result<T::CrossAccountId, TokenOwnerError> {1372 let mut owner = None;1373 let mut count = 0;1374 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1375 count += 1;1376 if count > 1 {1377 return Err(TokenOwnerError::MultipleOwners);1378 }1379 owner = Some(key);1380 }1381 owner.ok_or(TokenOwnerError::NotFound)1382 }13831384 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1385 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1386 }13871388 pub fn set_collection_properties(1389 collection: &RefungibleHandle<T>,1390 sender: &T::CrossAccountId,1391 properties: Vec<Property>,1392 ) -> DispatchResult {1393 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1394 }13951396 pub fn delete_collection_properties(1397 collection: &RefungibleHandle<T>,1398 sender: &T::CrossAccountId,1399 property_keys: Vec<PropertyKey>,1400 ) -> DispatchResult {1401 <PalletCommon<T>>::delete_collection_properties(1402 collection,1403 sender,1404 property_keys.into_iter(),1405 )1406 }14071408 pub fn set_token_property_permissions(1409 collection: &RefungibleHandle<T>,1410 sender: &T::CrossAccountId,1411 property_permissions: Vec<PropertyKeyPermission>,1412 ) -> DispatchResult {1413 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1414 }14151416 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1417 <PalletCommon<T>>::property_permissions(collection_id)1418 }14191420 pub fn set_scoped_token_property_permissions(1421 collection: &RefungibleHandle<T>,1422 sender: &T::CrossAccountId,1423 scope: PropertyScope,1424 property_permissions: Vec<PropertyKeyPermission>,1425 ) -> DispatchResult {1426 <PalletCommon<T>>::set_scoped_token_property_permissions(1427 collection,1428 sender,1429 scope,1430 property_permissions,1431 )1432 }14331434 /// Returns 10 token in no particular order.1435 ///1436 /// There is no direct way to get token holders in ascending order,1437 /// since `iter_prefix` returns values in no particular order.1438 /// Therefore, getting the 10 largest holders with a large value of holders1439 /// can lead to impact memory allocation + sorting with `n * log (n)`.1440 pub fn token_owners(1441 collection_id: CollectionId,1442 token: TokenId,1443 ) -> Option<Vec<T::CrossAccountId>> {1444 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1445 .map(|(owner, _amount)| owner)1446 .take(10)1447 .collect();14481449 if res.is_empty() {1450 None1451 } else {1452 Some(res)1453 }1454 }14551456 /// Sets or unsets the approval of a given operator.1457 ///1458 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1459 /// - `owner`: Token owner1460 /// - `operator`: Operator1461 /// - `approve`: Should operator status be granted or revoked?1462 pub fn set_allowance_for_all(1463 collection: &RefungibleHandle<T>,1464 owner: &T::CrossAccountId,1465 operator: &T::CrossAccountId,1466 approve: bool,1467 ) -> DispatchResult {1468 if collection.permissions.access() == AccessMode::AllowList {1469 collection.check_allowlist(owner)?;1470 collection.check_allowlist(operator)?;1471 }14721473 <PalletCommon<T>>::ensure_correct_receiver(operator)?;14741475 // =========14761477 <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);1478 <PalletEvm<T>>::deposit_log(1479 ERC721Events::ApprovalForAll {1480 owner: *owner.as_eth(),1481 operator: *operator.as_eth(),1482 approved: approve,1483 }1484 .to_log(collection_id_to_address(collection.id)),1485 );1486 <PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1487 collection.id,1488 owner.clone(),1489 operator.clone(),1490 approve,1491 ));1492 Ok(())1493 }14941495 /// Tells whether the given `owner` approves the `operator`.1496 pub fn allowance_for_all(1497 collection: &RefungibleHandle<T>,1498 owner: &T::CrossAccountId,1499 operator: &T::CrossAccountId,1500 ) -> bool {1501 <CollectionAllowance<T>>::get((collection.id, owner, operator))1502 }15031504 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1505 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1506 properties.recompute_consumed_space();1507 });15081509 Ok(())1510 }1511}