difftreelog
fix use set instead of mutate
in: master
3 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1236,9 +1236,7 @@
}
}
- <CollectionProperties<T>>::mutate(collection.id, |properties| {
- *properties = stored_properties;
- });
+ <CollectionProperties<T>>::set(collection.id, stored_properties);
Ok(())
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -682,9 +682,7 @@
);
}
- <TokenProperties<T>>::mutate((collection.id, token_id), |properties| {
- *properties = stored_properties;
- });
+ <TokenProperties<T>>::set((collection.id, token_id), stored_properties);
Ok(())
}
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,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 Some(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 #[transactional]519 fn modify_token_properties(520 collection: &RefungibleHandle<T>,521 sender: &T::CrossAccountId,522 token_id: TokenId,523 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,524 is_token_create: bool,525 nesting_budget: &dyn Budget,526 ) -> DispatchResult {527 let is_collection_admin = || collection.is_owner_or_admin(sender);528 let is_token_owner = || -> Result<bool, DispatchError> {529 let balance = collection.balance(sender.clone(), token_id);530 let total_pieces: u128 =531 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);532 if balance != total_pieces {533 return Ok(false);534 }535536 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(537 sender.clone(),538 collection.id,539 token_id,540 None,541 nesting_budget,542 )?;543544 Ok(is_bundle_owner)545 };546547 let mut stored_properties = <TokenProperties<T>>::get((collection.id, token_id));548 let permissions = <PalletCommon<T>>::property_permissions(collection.id);549550 for (key, value) in properties_updates {551 let permission = permissions552 .get(&key)553 .cloned()554 .unwrap_or_else(PropertyPermission::none);555556 let is_property_exists = stored_properties.get(&key).is_some();557558 match permission {559 PropertyPermission { mutable: false, .. } if is_property_exists => {560 return Err(<CommonError<T>>::NoPermission.into());561 }562563 PropertyPermission {564 collection_admin,565 token_owner,566 ..567 } => {568 //TODO: investigate threats during public minting.569 let is_token_create =570 is_token_create && (collection_admin || token_owner) && value.is_some();571 if !(is_token_create572 || (collection_admin && is_collection_admin())573 || (token_owner && is_token_owner()?))574 {575 fail!(<CommonError<T>>::NoPermission);576 }577 }578 }579580 match value {581 Some(value) => {582 stored_properties583 .try_set(key.clone(), value)584 .map_err(<CommonError<T>>::from)?;585586 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(587 collection.id,588 token_id,589 key,590 ));591 }592 None => {593 stored_properties594 .remove(&key)595 .map_err(<CommonError<T>>::from)?;596597 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(598 collection.id,599 token_id,600 key,601 ));602 }603 }604605 <PalletEvm<T>>::deposit_log(606 CollectionHelpersEvents::TokenChanged {607 collection_id: collection_id_to_address(collection.id),608 token_id: token_id.into(),609 }610 .to_log(T::ContractAddress::get()),611 );612 }613614 <TokenProperties<T>>::mutate((collection.id, token_id), |properties| {615 *properties = stored_properties;616 });617618 Ok(())619 }620621 pub fn set_token_properties(622 collection: &RefungibleHandle<T>,623 sender: &T::CrossAccountId,624 token_id: TokenId,625 properties: impl Iterator<Item = Property>,626 is_token_create: bool,627 nesting_budget: &dyn Budget,628 ) -> DispatchResult {629 Self::modify_token_properties(630 collection,631 sender,632 token_id,633 properties.map(|p| (p.key, Some(p.value))),634 is_token_create,635 nesting_budget,636 )637 }638639 pub fn set_token_property(640 collection: &RefungibleHandle<T>,641 sender: &T::CrossAccountId,642 token_id: TokenId,643 property: Property,644 nesting_budget: &dyn Budget,645 ) -> DispatchResult {646 let is_token_create = false;647648 Self::set_token_properties(649 collection,650 sender,651 token_id,652 [property].into_iter(),653 is_token_create,654 nesting_budget,655 )656 }657658 pub fn delete_token_properties(659 collection: &RefungibleHandle<T>,660 sender: &T::CrossAccountId,661 token_id: TokenId,662 property_keys: impl Iterator<Item = PropertyKey>,663 nesting_budget: &dyn Budget,664 ) -> DispatchResult {665 let is_token_create = false;666667 Self::modify_token_properties(668 collection,669 sender,670 token_id,671 property_keys.into_iter().map(|key| (key, None)),672 is_token_create,673 nesting_budget,674 )675 }676677 pub fn delete_token_property(678 collection: &RefungibleHandle<T>,679 sender: &T::CrossAccountId,680 token_id: TokenId,681 property_key: PropertyKey,682 nesting_budget: &dyn Budget,683 ) -> DispatchResult {684 Self::delete_token_properties(685 collection,686 sender,687 token_id,688 [property_key].into_iter(),689 nesting_budget,690 )691 }692693 /// Transfer RFT token pieces from one account to another.694 ///695 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.696 ///697 /// - `from`: Owner of token pieces to transfer.698 /// - `to`: Recepient of transfered token pieces.699 /// - `amount`: Amount of token pieces to transfer.700 /// - `token`: Token whos pieces should be transfered701 /// - `collection`: Collection that contains the token702 pub fn transfer(703 collection: &RefungibleHandle<T>,704 from: &T::CrossAccountId,705 to: &T::CrossAccountId,706 token: TokenId,707 amount: u128,708 nesting_budget: &dyn Budget,709 ) -> DispatchResult {710 ensure!(711 collection.limits.transfers_enabled(),712 <CommonError<T>>::TransferNotAllowed713 );714715 if collection.permissions.access() == AccessMode::AllowList {716 collection.check_allowlist(from)?;717 collection.check_allowlist(to)?;718 }719 <PalletCommon<T>>::ensure_correct_receiver(to)?;720721 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));722723 if initial_balance_from == 0 {724 return Err(<CommonError<T>>::TokenValueTooLow.into());725 }726727 let updated_balance_from = initial_balance_from728 .checked_sub(amount)729 .ok_or(<CommonError<T>>::TokenValueTooLow)?;730 let mut create_target = false;731 let from_to_differ = from != to;732 let updated_balance_to = if from != to && amount != 0 {733 let old_balance = <Balance<T>>::get((collection.id, token, to));734 if old_balance == 0 {735 create_target = true;736 }737 Some(738 old_balance739 .checked_add(amount)740 .ok_or(ArithmeticError::Overflow)?,741 )742 } else {743 None744 };745746 let account_balance_from = if updated_balance_from == 0 {747 Some(748 <AccountBalance<T>>::get((collection.id, from))749 .checked_sub(1)750 // Should not occur751 .ok_or(ArithmeticError::Underflow)?,752 )753 } else {754 None755 };756 // Account data is created in token, AccountBalance should be increased757 // But only if from != to as we shouldn't check overflow in this case758 let account_balance_to = if create_target && from_to_differ {759 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))760 .checked_add(1)761 .ok_or(ArithmeticError::Overflow)?;762 ensure!(763 account_balance_to < collection.limits.account_token_ownership_limit(),764 <CommonError<T>>::AccountTokenLimitExceeded,765 );766767 Some(account_balance_to)768 } else {769 None770 };771772 // =========773774 if let Some(updated_balance_to) = updated_balance_to {775 // from != to && amount != 0776777 <PalletStructure<T>>::nest_if_sent_to_token(778 from.clone(),779 to,780 collection.id,781 token,782 nesting_budget,783 )?;784785 if updated_balance_from == 0 {786 <Balance<T>>::remove((collection.id, token, from));787 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);788 } else {789 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);790 }791 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);792 if let Some(account_balance_from) = account_balance_from {793 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);794 <Owned<T>>::remove((collection.id, from, token));795 }796 if let Some(account_balance_to) = account_balance_to {797 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);798 <Owned<T>>::insert((collection.id, to, token), true);799 }800 }801802 <PalletEvm<T>>::deposit_log(803 ERC20Events::Transfer {804 from: *from.as_eth(),805 to: *to.as_eth(),806 value: amount.into(),807 }808 .to_log(T::EvmTokenAddressMapping::token_to_address(809 collection.id,810 token,811 )),812 );813814 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(815 collection.id,816 token,817 from.clone(),818 to.clone(),819 amount,820 ));821822 let total_supply = <TotalSupply<T>>::get((collection.id, token));823824 if amount == total_supply {825 // if token was fully owned by `from` and will be fully owned by `to` after transfer826 <PalletEvm<T>>::deposit_log(827 ERC721Events::Transfer {828 from: *from.as_eth(),829 to: *to.as_eth(),830 token_id: token.into(),831 }832 .to_log(collection_id_to_address(collection.id)),833 );834 } else if let Some(updated_balance_to) = updated_balance_to {835 // if `from` not equals `to`. This condition is needed to avoid sending event836 // when `from` fully owns token and sends part of token pieces to itself.837 if initial_balance_from == total_supply {838 // if token was fully owned by `from` and will be only partially owned by `to`839 // and `from` after transfer840 <PalletEvm<T>>::deposit_log(841 ERC721Events::Transfer {842 from: *from.as_eth(),843 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,844 token_id: token.into(),845 }846 .to_log(collection_id_to_address(collection.id)),847 );848 } else if updated_balance_to == total_supply {849 // if token was partially owned by `from` and will be fully owned by `to` after transfer850 <PalletEvm<T>>::deposit_log(851 ERC721Events::Transfer {852 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,853 to: *to.as_eth(),854 token_id: token.into(),855 }856 .to_log(collection_id_to_address(collection.id)),857 );858 }859 }860861 Ok(())862 }863864 /// Batched operation to create multiple RFT tokens.865 ///866 /// Same as `create_item` but creates multiple tokens.867 ///868 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.869 pub fn create_multiple_items(870 collection: &RefungibleHandle<T>,871 sender: &T::CrossAccountId,872 data: Vec<CreateItemData<T>>,873 nesting_budget: &dyn Budget,874 ) -> DispatchResult {875 if !collection.is_owner_or_admin(sender) {876 ensure!(877 collection.permissions.mint_mode(),878 <CommonError<T>>::PublicMintingNotAllowed879 );880 collection.check_allowlist(sender)?;881882 for item in data.iter() {883 for user in item.users.keys() {884 collection.check_allowlist(user)?;885 }886 }887 }888889 for item in data.iter() {890 for (owner, _) in item.users.iter() {891 <PalletCommon<T>>::ensure_correct_receiver(owner)?;892 }893 }894895 // Total pieces per tokens896 let totals = data897 .iter()898 .map(|data| {899 Ok(data900 .users901 .iter()902 .map(|u| u.1)903 .try_fold(0u128, |acc, v| acc.checked_add(*v))904 .ok_or(ArithmeticError::Overflow)?)905 })906 .collect::<Result<Vec<_>, DispatchError>>()?;907 for total in &totals {908 ensure!(909 *total <= MAX_REFUNGIBLE_PIECES,910 <Error<T>>::WrongRefungiblePieces911 );912 }913914 let first_token_id = <TokensMinted<T>>::get(collection.id);915 let tokens_minted = first_token_id916 .checked_add(data.len() as u32)917 .ok_or(ArithmeticError::Overflow)?;918 ensure!(919 tokens_minted < collection.limits.token_limit(),920 <CommonError<T>>::CollectionTokenLimitExceeded921 );922923 let mut balances = BTreeMap::new();924 for data in &data {925 for owner in data.users.keys() {926 let balance = balances927 .entry(owner)928 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));929 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;930931 ensure!(932 *balance <= collection.limits.account_token_ownership_limit(),933 <CommonError<T>>::AccountTokenLimitExceeded,934 );935 }936 }937938 for (i, token) in data.iter().enumerate() {939 let token_id = TokenId(first_token_id + i as u32 + 1);940 for (to, _) in token.users.iter() {941 <PalletStructure<T>>::check_nesting(942 sender.clone(),943 to,944 collection.id,945 token_id,946 nesting_budget,947 )?;948 }949 }950951 // =========952953 with_transaction(|| {954 for (i, data) in data.iter().enumerate() {955 let token_id = first_token_id + i as u32 + 1;956 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);957958 for (user, amount) in data.users.iter() {959 if *amount == 0 {960 continue;961 }962 <Balance<T>>::insert((collection.id, token_id, &user), amount);963 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);964 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(965 user,966 collection.id,967 TokenId(token_id),968 );969 }970971 if let Err(e) = Self::set_token_properties(972 collection,973 sender,974 TokenId(token_id),975 data.properties.clone().into_iter(),976 true,977 nesting_budget,978 ) {979 return TransactionOutcome::Rollback(Err(e));980 }981 }982 TransactionOutcome::Commit(Ok(()))983 })?;984985 <TokensMinted<T>>::insert(collection.id, tokens_minted);986987 for (account, balance) in balances {988 <AccountBalance<T>>::insert((collection.id, account), balance);989 }990991 for (i, token) in data.into_iter().enumerate() {992 let token_id = first_token_id + i as u32 + 1;993994 let receivers = token995 .users996 .into_iter()997 .filter(|(_, amount)| *amount > 0)998 .collect::<Vec<_>>();9991000 if let [(user, _)] = receivers.as_slice() {1001 // if there is exactly one receiver1002 <PalletEvm<T>>::deposit_log(1003 ERC721Events::Transfer {1004 from: H160::default(),1005 to: *user.as_eth(),1006 token_id: token_id.into(),1007 }1008 .to_log(collection_id_to_address(collection.id)),1009 );1010 } else if let [_, ..] = receivers.as_slice() {1011 // if there is more than one receiver1012 <PalletEvm<T>>::deposit_log(1013 ERC721Events::Transfer {1014 from: H160::default(),1015 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1016 token_id: token_id.into(),1017 }1018 .to_log(collection_id_to_address(collection.id)),1019 );1020 }10211022 for (user, amount) in receivers.into_iter() {1023 <PalletEvm<T>>::deposit_log(1024 ERC20Events::Transfer {1025 from: H160::default(),1026 to: *user.as_eth(),1027 value: amount.into(),1028 }1029 .to_log(T::EvmTokenAddressMapping::token_to_address(1030 collection.id,1031 TokenId(token_id),1032 )),1033 );1034 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1035 collection.id,1036 TokenId(token_id),1037 user,1038 amount,1039 ));1040 }1041 }1042 Ok(())1043 }10441045 pub fn set_allowance_unchecked(1046 collection: &RefungibleHandle<T>,1047 sender: &T::CrossAccountId,1048 spender: &T::CrossAccountId,1049 token: TokenId,1050 amount: u128,1051 ) {1052 if amount == 0 {1053 <Allowance<T>>::remove((collection.id, token, sender, spender));1054 } else {1055 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);1056 }10571058 <PalletEvm<T>>::deposit_log(1059 ERC20Events::Approval {1060 owner: *sender.as_eth(),1061 spender: *spender.as_eth(),1062 value: amount.into(),1063 }1064 .to_log(T::EvmTokenAddressMapping::token_to_address(1065 collection.id,1066 token,1067 )),1068 );1069 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1070 collection.id,1071 token,1072 sender.clone(),1073 spender.clone(),1074 amount,1075 ))1076 }10771078 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1079 ///1080 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1081 pub fn set_allowance(1082 collection: &RefungibleHandle<T>,1083 sender: &T::CrossAccountId,1084 spender: &T::CrossAccountId,1085 token: TokenId,1086 amount: u128,1087 ) -> DispatchResult {1088 if collection.permissions.access() == AccessMode::AllowList {1089 collection.check_allowlist(sender)?;1090 collection.check_allowlist(spender)?;1091 }10921093 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10941095 if <Balance<T>>::get((collection.id, token, sender)) < amount {1096 ensure!(1097 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1098 <CommonError<T>>::CantApproveMoreThanOwned1099 );1100 }11011102 // =========11031104 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1105 Ok(())1106 }11071108 /// Set allowance to spend from sender's eth mirror1109 ///1110 /// - `from`: Address of sender's eth mirror.1111 /// - `to`: Adress of spender.1112 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1113 pub fn set_allowance_from(1114 collection: &RefungibleHandle<T>,1115 sender: &T::CrossAccountId,1116 from: &T::CrossAccountId,1117 to: &T::CrossAccountId,1118 token_id: TokenId,1119 amount: u128,1120 ) -> DispatchResult {1121 if collection.permissions.access() == AccessMode::AllowList {1122 collection.check_allowlist(sender)?;1123 collection.check_allowlist(from)?;1124 collection.check_allowlist(to)?;1125 }11261127 <PalletCommon<T>>::ensure_correct_receiver(to)?;11281129 ensure!(1130 sender.conv_eq(from),1131 <CommonError<T>>::AddressIsNotEthMirror1132 );11331134 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1135 ensure!(1136 collection.limits.owner_can_transfer()1137 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1138 && Self::token_exists(collection, token_id),1139 <CommonError<T>>::CantApproveMoreThanOwned1140 );1141 }11421143 // =========11441145 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1146 Ok(())1147 }11481149 /// Returns allowance, which should be set after transaction1150 fn check_allowed(1151 collection: &RefungibleHandle<T>,1152 spender: &T::CrossAccountId,1153 from: &T::CrossAccountId,1154 token: TokenId,1155 amount: u128,1156 nesting_budget: &dyn Budget,1157 ) -> Result<Option<u128>, DispatchError> {1158 if spender.conv_eq(from) {1159 return Ok(None);1160 }1161 if collection.permissions.access() == AccessMode::AllowList {1162 // `from`, `to` checked in [`transfer`]1163 collection.check_allowlist(spender)?;1164 }1165 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1166 // TODO: should collection owner be allowed to perform this transfer?1167 ensure!(1168 <PalletStructure<T>>::check_indirectly_owned(1169 spender.clone(),1170 source.0,1171 source.1,1172 None,1173 nesting_budget1174 )?,1175 <CommonError<T>>::ApprovedValueTooLow,1176 );1177 return Ok(None);1178 }1179 let allowance =1180 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);11811182 // Allowance (if any) would be reduced if spender is also wallet operator1183 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1184 return Ok(allowance);1185 }11861187 if allowance.is_none() {1188 ensure!(1189 collection.ignores_allowance(spender),1190 <CommonError<T>>::ApprovedValueTooLow1191 );1192 }1193 Ok(allowance)1194 }11951196 /// Transfer RFT token pieces from one account to another.1197 ///1198 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1199 /// The owner should set allowance for the spender to transfer pieces.1200 ///1201 /// [`transfer`]: struct.Pallet.html#method.transfer1202 pub fn transfer_from(1203 collection: &RefungibleHandle<T>,1204 spender: &T::CrossAccountId,1205 from: &T::CrossAccountId,1206 to: &T::CrossAccountId,1207 token: TokenId,1208 amount: u128,1209 nesting_budget: &dyn Budget,1210 ) -> DispatchResult {1211 let allowance =1212 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12131214 // =========12151216 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1217 if let Some(allowance) = allowance {1218 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1219 }1220 Ok(())1221 }12221223 /// Burn RFT token pieces from the account.1224 ///1225 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1226 /// set allowance for the spender to burn pieces1227 ///1228 /// [`burn`]: struct.Pallet.html#method.burn1229 pub fn burn_from(1230 collection: &RefungibleHandle<T>,1231 spender: &T::CrossAccountId,1232 from: &T::CrossAccountId,1233 token: TokenId,1234 amount: u128,1235 nesting_budget: &dyn Budget,1236 ) -> DispatchResult {1237 let allowance =1238 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12391240 // =========12411242 Self::burn(collection, from, token, amount)?;1243 if let Some(allowance) = allowance {1244 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1245 }1246 Ok(())1247 }12481249 /// Create RFT token.1250 ///1251 /// The sender should be the owner/admin of the collection or collection should be configured1252 /// to allow public minting.1253 ///1254 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1255 /// of token pieces they will receive.1256 pub fn create_item(1257 collection: &RefungibleHandle<T>,1258 sender: &T::CrossAccountId,1259 data: CreateItemData<T>,1260 nesting_budget: &dyn Budget,1261 ) -> DispatchResult {1262 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1263 }12641265 /// Repartition RFT token.1266 ///1267 /// `repartition` will set token balance of the sender and total amount of token pieces.1268 /// Sender should own all of the token pieces. `repartition' could be done even if some1269 /// token pieces were burned before.1270 ///1271 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1272 pub fn repartition(1273 collection: &RefungibleHandle<T>,1274 owner: &T::CrossAccountId,1275 token: TokenId,1276 amount: u128,1277 ) -> DispatchResult {1278 ensure!(1279 amount <= MAX_REFUNGIBLE_PIECES,1280 <Error<T>>::WrongRefungiblePieces1281 );1282 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1283 // Ensure user owns all pieces1284 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1285 let balance = <Balance<T>>::get((collection.id, token, owner));1286 ensure!(1287 total_pieces == balance,1288 <Error<T>>::RepartitionWhileNotOwningAllPieces1289 );12901291 <Balance<T>>::insert((collection.id, token, owner), amount);1292 <TotalSupply<T>>::insert((collection.id, token), amount);12931294 if amount > total_pieces {1295 let mint_amount = amount - total_pieces;1296 <PalletEvm<T>>::deposit_log(1297 ERC20Events::Transfer {1298 from: H160::default(),1299 to: *owner.as_eth(),1300 value: mint_amount.into(),1301 }1302 .to_log(T::EvmTokenAddressMapping::token_to_address(1303 collection.id,1304 token,1305 )),1306 );1307 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1308 collection.id,1309 token,1310 owner.clone(),1311 mint_amount,1312 ));1313 } else if total_pieces > amount {1314 let burn_amount = total_pieces - amount;1315 <PalletEvm<T>>::deposit_log(1316 ERC20Events::Transfer {1317 from: *owner.as_eth(),1318 to: H160::default(),1319 value: burn_amount.into(),1320 }1321 .to_log(T::EvmTokenAddressMapping::token_to_address(1322 collection.id,1323 token,1324 )),1325 );1326 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1327 collection.id,1328 token,1329 owner.clone(),1330 burn_amount,1331 ));1332 }13331334 Ok(())1335 }13361337 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1338 let mut owner = None;1339 let mut count = 0;1340 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1341 count += 1;1342 if count > 1 {1343 return None;1344 }1345 owner = Some(key);1346 }1347 owner1348 }13491350 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1351 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1352 }13531354 pub fn set_collection_properties(1355 collection: &RefungibleHandle<T>,1356 sender: &T::CrossAccountId,1357 properties: Vec<Property>,1358 ) -> DispatchResult {1359 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1360 }13611362 pub fn delete_collection_properties(1363 collection: &RefungibleHandle<T>,1364 sender: &T::CrossAccountId,1365 property_keys: Vec<PropertyKey>,1366 ) -> DispatchResult {1367 <PalletCommon<T>>::delete_collection_properties(1368 collection,1369 sender,1370 property_keys.into_iter(),1371 )1372 }13731374 pub fn set_token_property_permissions(1375 collection: &RefungibleHandle<T>,1376 sender: &T::CrossAccountId,1377 property_permissions: Vec<PropertyKeyPermission>,1378 ) -> DispatchResult {1379 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1380 }13811382 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1383 <PalletCommon<T>>::property_permissions(collection_id)1384 }13851386 pub fn set_scoped_token_property_permissions(1387 collection: &RefungibleHandle<T>,1388 sender: &T::CrossAccountId,1389 scope: PropertyScope,1390 property_permissions: Vec<PropertyKeyPermission>,1391 ) -> DispatchResult {1392 <PalletCommon<T>>::set_scoped_token_property_permissions(1393 collection,1394 sender,1395 scope,1396 property_permissions,1397 )1398 }13991400 /// Returns 10 token in no particular order.1401 ///1402 /// There is no direct way to get token holders in ascending order,1403 /// since `iter_prefix` returns values in no particular order.1404 /// Therefore, getting the 10 largest holders with a large value of holders1405 /// can lead to impact memory allocation + sorting with `n * log (n)`.1406 pub fn token_owners(1407 collection_id: CollectionId,1408 token: TokenId,1409 ) -> Option<Vec<T::CrossAccountId>> {1410 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1411 .map(|(owner, _amount)| owner)1412 .take(10)1413 .collect();14141415 if res.is_empty() {1416 None1417 } else {1418 Some(res)1419 }1420 }14211422 /// Sets or unsets the approval of a given operator.1423 ///1424 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1425 /// - `owner`: Token owner1426 /// - `operator`: Operator1427 /// - `approve`: Should operator status be granted or revoked?1428 pub fn set_allowance_for_all(1429 collection: &RefungibleHandle<T>,1430 owner: &T::CrossAccountId,1431 operator: &T::CrossAccountId,1432 approve: bool,1433 ) -> DispatchResult {1434 if collection.permissions.access() == AccessMode::AllowList {1435 collection.check_allowlist(owner)?;1436 collection.check_allowlist(operator)?;1437 }14381439 <PalletCommon<T>>::ensure_correct_receiver(operator)?;14401441 // =========14421443 <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);1444 <PalletEvm<T>>::deposit_log(1445 ERC721Events::ApprovalForAll {1446 owner: *owner.as_eth(),1447 operator: *operator.as_eth(),1448 approved: approve,1449 }1450 .to_log(collection_id_to_address(collection.id)),1451 );1452 <PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1453 collection.id,1454 owner.clone(),1455 operator.clone(),1456 approve,1457 ));1458 Ok(())1459 }14601461 /// Tells whether the given `owner` approves the `operator`.1462 pub fn allowance_for_all(1463 collection: &RefungibleHandle<T>,1464 owner: &T::CrossAccountId,1465 operator: &T::CrossAccountId,1466 ) -> bool {1467 <CollectionAllowance<T>>::get((collection.id, owner, operator))1468 }14691470 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1471 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1472 properties.recompute_consumed_space();1473 });14741475 Ok(())1476 }1477}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//! # 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,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 Some(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 #[transactional]519 fn modify_token_properties(520 collection: &RefungibleHandle<T>,521 sender: &T::CrossAccountId,522 token_id: TokenId,523 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,524 is_token_create: bool,525 nesting_budget: &dyn Budget,526 ) -> DispatchResult {527 let is_collection_admin = || collection.is_owner_or_admin(sender);528 let is_token_owner = || -> Result<bool, DispatchError> {529 let balance = collection.balance(sender.clone(), token_id);530 let total_pieces: u128 =531 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);532 if balance != total_pieces {533 return Ok(false);534 }535536 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(537 sender.clone(),538 collection.id,539 token_id,540 None,541 nesting_budget,542 )?;543544 Ok(is_bundle_owner)545 };546547 let mut stored_properties = <TokenProperties<T>>::get((collection.id, token_id));548 let permissions = <PalletCommon<T>>::property_permissions(collection.id);549550 for (key, value) in properties_updates {551 let permission = permissions552 .get(&key)553 .cloned()554 .unwrap_or_else(PropertyPermission::none);555556 let is_property_exists = stored_properties.get(&key).is_some();557558 match permission {559 PropertyPermission { mutable: false, .. } if is_property_exists => {560 return Err(<CommonError<T>>::NoPermission.into());561 }562563 PropertyPermission {564 collection_admin,565 token_owner,566 ..567 } => {568 //TODO: investigate threats during public minting.569 let is_token_create =570 is_token_create && (collection_admin || token_owner) && value.is_some();571 if !(is_token_create572 || (collection_admin && is_collection_admin())573 || (token_owner && is_token_owner()?))574 {575 fail!(<CommonError<T>>::NoPermission);576 }577 }578 }579580 match value {581 Some(value) => {582 stored_properties583 .try_set(key.clone(), value)584 .map_err(<CommonError<T>>::from)?;585586 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(587 collection.id,588 token_id,589 key,590 ));591 }592 None => {593 stored_properties594 .remove(&key)595 .map_err(<CommonError<T>>::from)?;596597 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(598 collection.id,599 token_id,600 key,601 ));602 }603 }604605 <PalletEvm<T>>::deposit_log(606 CollectionHelpersEvents::TokenChanged {607 collection_id: collection_id_to_address(collection.id),608 token_id: token_id.into(),609 }610 .to_log(T::ContractAddress::get()),611 );612 }613614 <TokenProperties<T>>::set((collection.id, token_id), stored_properties);615616 Ok(())617 }618619 pub fn set_token_properties(620 collection: &RefungibleHandle<T>,621 sender: &T::CrossAccountId,622 token_id: TokenId,623 properties: impl Iterator<Item = Property>,624 is_token_create: bool,625 nesting_budget: &dyn Budget,626 ) -> DispatchResult {627 Self::modify_token_properties(628 collection,629 sender,630 token_id,631 properties.map(|p| (p.key, Some(p.value))),632 is_token_create,633 nesting_budget,634 )635 }636637 pub fn set_token_property(638 collection: &RefungibleHandle<T>,639 sender: &T::CrossAccountId,640 token_id: TokenId,641 property: Property,642 nesting_budget: &dyn Budget,643 ) -> DispatchResult {644 let is_token_create = false;645646 Self::set_token_properties(647 collection,648 sender,649 token_id,650 [property].into_iter(),651 is_token_create,652 nesting_budget,653 )654 }655656 pub fn delete_token_properties(657 collection: &RefungibleHandle<T>,658 sender: &T::CrossAccountId,659 token_id: TokenId,660 property_keys: impl Iterator<Item = PropertyKey>,661 nesting_budget: &dyn Budget,662 ) -> DispatchResult {663 let is_token_create = false;664665 Self::modify_token_properties(666 collection,667 sender,668 token_id,669 property_keys.into_iter().map(|key| (key, None)),670 is_token_create,671 nesting_budget,672 )673 }674675 pub fn delete_token_property(676 collection: &RefungibleHandle<T>,677 sender: &T::CrossAccountId,678 token_id: TokenId,679 property_key: PropertyKey,680 nesting_budget: &dyn Budget,681 ) -> DispatchResult {682 Self::delete_token_properties(683 collection,684 sender,685 token_id,686 [property_key].into_iter(),687 nesting_budget,688 )689 }690691 /// Transfer RFT token pieces from one account to another.692 ///693 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.694 ///695 /// - `from`: Owner of token pieces to transfer.696 /// - `to`: Recepient of transfered token pieces.697 /// - `amount`: Amount of token pieces to transfer.698 /// - `token`: Token whos pieces should be transfered699 /// - `collection`: Collection that contains the token700 pub fn transfer(701 collection: &RefungibleHandle<T>,702 from: &T::CrossAccountId,703 to: &T::CrossAccountId,704 token: TokenId,705 amount: u128,706 nesting_budget: &dyn Budget,707 ) -> DispatchResult {708 ensure!(709 collection.limits.transfers_enabled(),710 <CommonError<T>>::TransferNotAllowed711 );712713 if collection.permissions.access() == AccessMode::AllowList {714 collection.check_allowlist(from)?;715 collection.check_allowlist(to)?;716 }717 <PalletCommon<T>>::ensure_correct_receiver(to)?;718719 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));720721 if initial_balance_from == 0 {722 return Err(<CommonError<T>>::TokenValueTooLow.into());723 }724725 let updated_balance_from = initial_balance_from726 .checked_sub(amount)727 .ok_or(<CommonError<T>>::TokenValueTooLow)?;728 let mut create_target = false;729 let from_to_differ = from != to;730 let updated_balance_to = if from != to && amount != 0 {731 let old_balance = <Balance<T>>::get((collection.id, token, to));732 if old_balance == 0 {733 create_target = true;734 }735 Some(736 old_balance737 .checked_add(amount)738 .ok_or(ArithmeticError::Overflow)?,739 )740 } else {741 None742 };743744 let account_balance_from = if updated_balance_from == 0 {745 Some(746 <AccountBalance<T>>::get((collection.id, from))747 .checked_sub(1)748 // Should not occur749 .ok_or(ArithmeticError::Underflow)?,750 )751 } else {752 None753 };754 // Account data is created in token, AccountBalance should be increased755 // But only if from != to as we shouldn't check overflow in this case756 let account_balance_to = if create_target && from_to_differ {757 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))758 .checked_add(1)759 .ok_or(ArithmeticError::Overflow)?;760 ensure!(761 account_balance_to < collection.limits.account_token_ownership_limit(),762 <CommonError<T>>::AccountTokenLimitExceeded,763 );764765 Some(account_balance_to)766 } else {767 None768 };769770 // =========771772 if let Some(updated_balance_to) = updated_balance_to {773 // from != to && amount != 0774775 <PalletStructure<T>>::nest_if_sent_to_token(776 from.clone(),777 to,778 collection.id,779 token,780 nesting_budget,781 )?;782783 if updated_balance_from == 0 {784 <Balance<T>>::remove((collection.id, token, from));785 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);786 } else {787 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);788 }789 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);790 if let Some(account_balance_from) = account_balance_from {791 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);792 <Owned<T>>::remove((collection.id, from, token));793 }794 if let Some(account_balance_to) = account_balance_to {795 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);796 <Owned<T>>::insert((collection.id, to, token), true);797 }798 }799800 <PalletEvm<T>>::deposit_log(801 ERC20Events::Transfer {802 from: *from.as_eth(),803 to: *to.as_eth(),804 value: amount.into(),805 }806 .to_log(T::EvmTokenAddressMapping::token_to_address(807 collection.id,808 token,809 )),810 );811812 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(813 collection.id,814 token,815 from.clone(),816 to.clone(),817 amount,818 ));819820 let total_supply = <TotalSupply<T>>::get((collection.id, token));821822 if amount == total_supply {823 // if token was fully owned by `from` and will be fully owned by `to` after transfer824 <PalletEvm<T>>::deposit_log(825 ERC721Events::Transfer {826 from: *from.as_eth(),827 to: *to.as_eth(),828 token_id: token.into(),829 }830 .to_log(collection_id_to_address(collection.id)),831 );832 } else if let Some(updated_balance_to) = updated_balance_to {833 // if `from` not equals `to`. This condition is needed to avoid sending event834 // when `from` fully owns token and sends part of token pieces to itself.835 if initial_balance_from == total_supply {836 // if token was fully owned by `from` and will be only partially owned by `to`837 // and `from` after transfer838 <PalletEvm<T>>::deposit_log(839 ERC721Events::Transfer {840 from: *from.as_eth(),841 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,842 token_id: token.into(),843 }844 .to_log(collection_id_to_address(collection.id)),845 );846 } else if updated_balance_to == total_supply {847 // if token was partially owned by `from` and will be fully owned by `to` after transfer848 <PalletEvm<T>>::deposit_log(849 ERC721Events::Transfer {850 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,851 to: *to.as_eth(),852 token_id: token.into(),853 }854 .to_log(collection_id_to_address(collection.id)),855 );856 }857 }858859 Ok(())860 }861862 /// Batched operation to create multiple RFT tokens.863 ///864 /// Same as `create_item` but creates multiple tokens.865 ///866 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.867 pub fn create_multiple_items(868 collection: &RefungibleHandle<T>,869 sender: &T::CrossAccountId,870 data: Vec<CreateItemData<T>>,871 nesting_budget: &dyn Budget,872 ) -> DispatchResult {873 if !collection.is_owner_or_admin(sender) {874 ensure!(875 collection.permissions.mint_mode(),876 <CommonError<T>>::PublicMintingNotAllowed877 );878 collection.check_allowlist(sender)?;879880 for item in data.iter() {881 for user in item.users.keys() {882 collection.check_allowlist(user)?;883 }884 }885 }886887 for item in data.iter() {888 for (owner, _) in item.users.iter() {889 <PalletCommon<T>>::ensure_correct_receiver(owner)?;890 }891 }892893 // Total pieces per tokens894 let totals = data895 .iter()896 .map(|data| {897 Ok(data898 .users899 .iter()900 .map(|u| u.1)901 .try_fold(0u128, |acc, v| acc.checked_add(*v))902 .ok_or(ArithmeticError::Overflow)?)903 })904 .collect::<Result<Vec<_>, DispatchError>>()?;905 for total in &totals {906 ensure!(907 *total <= MAX_REFUNGIBLE_PIECES,908 <Error<T>>::WrongRefungiblePieces909 );910 }911912 let first_token_id = <TokensMinted<T>>::get(collection.id);913 let tokens_minted = first_token_id914 .checked_add(data.len() as u32)915 .ok_or(ArithmeticError::Overflow)?;916 ensure!(917 tokens_minted < collection.limits.token_limit(),918 <CommonError<T>>::CollectionTokenLimitExceeded919 );920921 let mut balances = BTreeMap::new();922 for data in &data {923 for owner in data.users.keys() {924 let balance = balances925 .entry(owner)926 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));927 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;928929 ensure!(930 *balance <= collection.limits.account_token_ownership_limit(),931 <CommonError<T>>::AccountTokenLimitExceeded,932 );933 }934 }935936 for (i, token) in data.iter().enumerate() {937 let token_id = TokenId(first_token_id + i as u32 + 1);938 for (to, _) in token.users.iter() {939 <PalletStructure<T>>::check_nesting(940 sender.clone(),941 to,942 collection.id,943 token_id,944 nesting_budget,945 )?;946 }947 }948949 // =========950951 with_transaction(|| {952 for (i, data) in data.iter().enumerate() {953 let token_id = first_token_id + i as u32 + 1;954 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);955956 for (user, amount) in data.users.iter() {957 if *amount == 0 {958 continue;959 }960 <Balance<T>>::insert((collection.id, token_id, &user), amount);961 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);962 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(963 user,964 collection.id,965 TokenId(token_id),966 );967 }968969 if let Err(e) = Self::set_token_properties(970 collection,971 sender,972 TokenId(token_id),973 data.properties.clone().into_iter(),974 true,975 nesting_budget,976 ) {977 return TransactionOutcome::Rollback(Err(e));978 }979 }980 TransactionOutcome::Commit(Ok(()))981 })?;982983 <TokensMinted<T>>::insert(collection.id, tokens_minted);984985 for (account, balance) in balances {986 <AccountBalance<T>>::insert((collection.id, account), balance);987 }988989 for (i, token) in data.into_iter().enumerate() {990 let token_id = first_token_id + i as u32 + 1;991992 let receivers = token993 .users994 .into_iter()995 .filter(|(_, amount)| *amount > 0)996 .collect::<Vec<_>>();997998 if let [(user, _)] = receivers.as_slice() {999 // if there is exactly one receiver1000 <PalletEvm<T>>::deposit_log(1001 ERC721Events::Transfer {1002 from: H160::default(),1003 to: *user.as_eth(),1004 token_id: token_id.into(),1005 }1006 .to_log(collection_id_to_address(collection.id)),1007 );1008 } else if let [_, ..] = receivers.as_slice() {1009 // if there is more than one receiver1010 <PalletEvm<T>>::deposit_log(1011 ERC721Events::Transfer {1012 from: H160::default(),1013 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1014 token_id: token_id.into(),1015 }1016 .to_log(collection_id_to_address(collection.id)),1017 );1018 }10191020 for (user, amount) in receivers.into_iter() {1021 <PalletEvm<T>>::deposit_log(1022 ERC20Events::Transfer {1023 from: H160::default(),1024 to: *user.as_eth(),1025 value: amount.into(),1026 }1027 .to_log(T::EvmTokenAddressMapping::token_to_address(1028 collection.id,1029 TokenId(token_id),1030 )),1031 );1032 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1033 collection.id,1034 TokenId(token_id),1035 user,1036 amount,1037 ));1038 }1039 }1040 Ok(())1041 }10421043 pub fn set_allowance_unchecked(1044 collection: &RefungibleHandle<T>,1045 sender: &T::CrossAccountId,1046 spender: &T::CrossAccountId,1047 token: TokenId,1048 amount: u128,1049 ) {1050 if amount == 0 {1051 <Allowance<T>>::remove((collection.id, token, sender, spender));1052 } else {1053 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);1054 }10551056 <PalletEvm<T>>::deposit_log(1057 ERC20Events::Approval {1058 owner: *sender.as_eth(),1059 spender: *spender.as_eth(),1060 value: amount.into(),1061 }1062 .to_log(T::EvmTokenAddressMapping::token_to_address(1063 collection.id,1064 token,1065 )),1066 );1067 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1068 collection.id,1069 token,1070 sender.clone(),1071 spender.clone(),1072 amount,1073 ))1074 }10751076 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1077 ///1078 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1079 pub fn set_allowance(1080 collection: &RefungibleHandle<T>,1081 sender: &T::CrossAccountId,1082 spender: &T::CrossAccountId,1083 token: TokenId,1084 amount: u128,1085 ) -> DispatchResult {1086 if collection.permissions.access() == AccessMode::AllowList {1087 collection.check_allowlist(sender)?;1088 collection.check_allowlist(spender)?;1089 }10901091 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10921093 if <Balance<T>>::get((collection.id, token, sender)) < amount {1094 ensure!(1095 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1096 <CommonError<T>>::CantApproveMoreThanOwned1097 );1098 }10991100 // =========11011102 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1103 Ok(())1104 }11051106 /// Set allowance to spend from sender's eth mirror1107 ///1108 /// - `from`: Address of sender's eth mirror.1109 /// - `to`: Adress of spender.1110 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1111 pub fn set_allowance_from(1112 collection: &RefungibleHandle<T>,1113 sender: &T::CrossAccountId,1114 from: &T::CrossAccountId,1115 to: &T::CrossAccountId,1116 token_id: TokenId,1117 amount: u128,1118 ) -> DispatchResult {1119 if collection.permissions.access() == AccessMode::AllowList {1120 collection.check_allowlist(sender)?;1121 collection.check_allowlist(from)?;1122 collection.check_allowlist(to)?;1123 }11241125 <PalletCommon<T>>::ensure_correct_receiver(to)?;11261127 ensure!(1128 sender.conv_eq(from),1129 <CommonError<T>>::AddressIsNotEthMirror1130 );11311132 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1133 ensure!(1134 collection.limits.owner_can_transfer()1135 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1136 && Self::token_exists(collection, token_id),1137 <CommonError<T>>::CantApproveMoreThanOwned1138 );1139 }11401141 // =========11421143 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1144 Ok(())1145 }11461147 /// Returns allowance, which should be set after transaction1148 fn check_allowed(1149 collection: &RefungibleHandle<T>,1150 spender: &T::CrossAccountId,1151 from: &T::CrossAccountId,1152 token: TokenId,1153 amount: u128,1154 nesting_budget: &dyn Budget,1155 ) -> Result<Option<u128>, DispatchError> {1156 if spender.conv_eq(from) {1157 return Ok(None);1158 }1159 if collection.permissions.access() == AccessMode::AllowList {1160 // `from`, `to` checked in [`transfer`]1161 collection.check_allowlist(spender)?;1162 }1163 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1164 // TODO: should collection owner be allowed to perform this transfer?1165 ensure!(1166 <PalletStructure<T>>::check_indirectly_owned(1167 spender.clone(),1168 source.0,1169 source.1,1170 None,1171 nesting_budget1172 )?,1173 <CommonError<T>>::ApprovedValueTooLow,1174 );1175 return Ok(None);1176 }1177 let allowance =1178 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);11791180 // Allowance (if any) would be reduced if spender is also wallet operator1181 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1182 return Ok(allowance);1183 }11841185 if allowance.is_none() {1186 ensure!(1187 collection.ignores_allowance(spender),1188 <CommonError<T>>::ApprovedValueTooLow1189 );1190 }1191 Ok(allowance)1192 }11931194 /// Transfer RFT token pieces from one account to another.1195 ///1196 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1197 /// The owner should set allowance for the spender to transfer pieces.1198 ///1199 /// [`transfer`]: struct.Pallet.html#method.transfer1200 pub fn transfer_from(1201 collection: &RefungibleHandle<T>,1202 spender: &T::CrossAccountId,1203 from: &T::CrossAccountId,1204 to: &T::CrossAccountId,1205 token: TokenId,1206 amount: u128,1207 nesting_budget: &dyn Budget,1208 ) -> DispatchResult {1209 let allowance =1210 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12111212 // =========12131214 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1215 if let Some(allowance) = allowance {1216 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1217 }1218 Ok(())1219 }12201221 /// Burn RFT token pieces from the account.1222 ///1223 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1224 /// set allowance for the spender to burn pieces1225 ///1226 /// [`burn`]: struct.Pallet.html#method.burn1227 pub fn burn_from(1228 collection: &RefungibleHandle<T>,1229 spender: &T::CrossAccountId,1230 from: &T::CrossAccountId,1231 token: TokenId,1232 amount: u128,1233 nesting_budget: &dyn Budget,1234 ) -> DispatchResult {1235 let allowance =1236 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12371238 // =========12391240 Self::burn(collection, from, token, amount)?;1241 if let Some(allowance) = allowance {1242 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1243 }1244 Ok(())1245 }12461247 /// Create RFT token.1248 ///1249 /// The sender should be the owner/admin of the collection or collection should be configured1250 /// to allow public minting.1251 ///1252 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1253 /// of token pieces they will receive.1254 pub fn create_item(1255 collection: &RefungibleHandle<T>,1256 sender: &T::CrossAccountId,1257 data: CreateItemData<T>,1258 nesting_budget: &dyn Budget,1259 ) -> DispatchResult {1260 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1261 }12621263 /// Repartition RFT token.1264 ///1265 /// `repartition` will set token balance of the sender and total amount of token pieces.1266 /// Sender should own all of the token pieces. `repartition' could be done even if some1267 /// token pieces were burned before.1268 ///1269 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1270 pub fn repartition(1271 collection: &RefungibleHandle<T>,1272 owner: &T::CrossAccountId,1273 token: TokenId,1274 amount: u128,1275 ) -> DispatchResult {1276 ensure!(1277 amount <= MAX_REFUNGIBLE_PIECES,1278 <Error<T>>::WrongRefungiblePieces1279 );1280 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1281 // Ensure user owns all pieces1282 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1283 let balance = <Balance<T>>::get((collection.id, token, owner));1284 ensure!(1285 total_pieces == balance,1286 <Error<T>>::RepartitionWhileNotOwningAllPieces1287 );12881289 <Balance<T>>::insert((collection.id, token, owner), amount);1290 <TotalSupply<T>>::insert((collection.id, token), amount);12911292 if amount > total_pieces {1293 let mint_amount = amount - total_pieces;1294 <PalletEvm<T>>::deposit_log(1295 ERC20Events::Transfer {1296 from: H160::default(),1297 to: *owner.as_eth(),1298 value: mint_amount.into(),1299 }1300 .to_log(T::EvmTokenAddressMapping::token_to_address(1301 collection.id,1302 token,1303 )),1304 );1305 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1306 collection.id,1307 token,1308 owner.clone(),1309 mint_amount,1310 ));1311 } else if total_pieces > amount {1312 let burn_amount = total_pieces - amount;1313 <PalletEvm<T>>::deposit_log(1314 ERC20Events::Transfer {1315 from: *owner.as_eth(),1316 to: H160::default(),1317 value: burn_amount.into(),1318 }1319 .to_log(T::EvmTokenAddressMapping::token_to_address(1320 collection.id,1321 token,1322 )),1323 );1324 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1325 collection.id,1326 token,1327 owner.clone(),1328 burn_amount,1329 ));1330 }13311332 Ok(())1333 }13341335 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1336 let mut owner = None;1337 let mut count = 0;1338 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1339 count += 1;1340 if count > 1 {1341 return None;1342 }1343 owner = Some(key);1344 }1345 owner1346 }13471348 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1349 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1350 }13511352 pub fn set_collection_properties(1353 collection: &RefungibleHandle<T>,1354 sender: &T::CrossAccountId,1355 properties: Vec<Property>,1356 ) -> DispatchResult {1357 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1358 }13591360 pub fn delete_collection_properties(1361 collection: &RefungibleHandle<T>,1362 sender: &T::CrossAccountId,1363 property_keys: Vec<PropertyKey>,1364 ) -> DispatchResult {1365 <PalletCommon<T>>::delete_collection_properties(1366 collection,1367 sender,1368 property_keys.into_iter(),1369 )1370 }13711372 pub fn set_token_property_permissions(1373 collection: &RefungibleHandle<T>,1374 sender: &T::CrossAccountId,1375 property_permissions: Vec<PropertyKeyPermission>,1376 ) -> DispatchResult {1377 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1378 }13791380 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1381 <PalletCommon<T>>::property_permissions(collection_id)1382 }13831384 pub fn set_scoped_token_property_permissions(1385 collection: &RefungibleHandle<T>,1386 sender: &T::CrossAccountId,1387 scope: PropertyScope,1388 property_permissions: Vec<PropertyKeyPermission>,1389 ) -> DispatchResult {1390 <PalletCommon<T>>::set_scoped_token_property_permissions(1391 collection,1392 sender,1393 scope,1394 property_permissions,1395 )1396 }13971398 /// Returns 10 token in no particular order.1399 ///1400 /// There is no direct way to get token holders in ascending order,1401 /// since `iter_prefix` returns values in no particular order.1402 /// Therefore, getting the 10 largest holders with a large value of holders1403 /// can lead to impact memory allocation + sorting with `n * log (n)`.1404 pub fn token_owners(1405 collection_id: CollectionId,1406 token: TokenId,1407 ) -> Option<Vec<T::CrossAccountId>> {1408 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1409 .map(|(owner, _amount)| owner)1410 .take(10)1411 .collect();14121413 if res.is_empty() {1414 None1415 } else {1416 Some(res)1417 }1418 }14191420 /// Sets or unsets the approval of a given operator.1421 ///1422 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1423 /// - `owner`: Token owner1424 /// - `operator`: Operator1425 /// - `approve`: Should operator status be granted or revoked?1426 pub fn set_allowance_for_all(1427 collection: &RefungibleHandle<T>,1428 owner: &T::CrossAccountId,1429 operator: &T::CrossAccountId,1430 approve: bool,1431 ) -> DispatchResult {1432 if collection.permissions.access() == AccessMode::AllowList {1433 collection.check_allowlist(owner)?;1434 collection.check_allowlist(operator)?;1435 }14361437 <PalletCommon<T>>::ensure_correct_receiver(operator)?;14381439 // =========14401441 <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);1442 <PalletEvm<T>>::deposit_log(1443 ERC721Events::ApprovalForAll {1444 owner: *owner.as_eth(),1445 operator: *operator.as_eth(),1446 approved: approve,1447 }1448 .to_log(collection_id_to_address(collection.id)),1449 );1450 <PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1451 collection.id,1452 owner.clone(),1453 operator.clone(),1454 approve,1455 ));1456 Ok(())1457 }14581459 /// Tells whether the given `owner` approves the `operator`.1460 pub fn allowance_for_all(1461 collection: &RefungibleHandle<T>,1462 owner: &T::CrossAccountId,1463 operator: &T::CrossAccountId,1464 ) -> bool {1465 <CollectionAllowance<T>>::get((collection.id, owner, operator))1466 }14671468 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1469 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1470 properties.recompute_consumed_space();1471 });14721473 Ok(())1474 }1475}