difftreelog
doc: added comments about burning
in: master
1 file changed
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`]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 frame_support::{ensure, BoundedVec};91use up_data_structs::{92 AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,93 CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,94};95use pallet_evm::account::CrossAccountId;96use pallet_common::{Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};97use pallet_structure::Pallet as PalletStructure;98use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};99use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};100use core::ops::Deref;101use codec::{Encode, Decode, MaxEncodedLen};102use scale_info::TypeInfo;103104pub use pallet::*;105#[cfg(feature = "runtime-benchmarks")]106pub mod benchmarking;107pub mod common;108pub mod erc;109pub mod weights;110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[struct_versioning::versioned(version = 2, upper)]113#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]114pub struct ItemData {115 pub const_data: BoundedVec<u8, CustomDataLimit>,116117 #[version(..2)]118 pub variable_data: BoundedVec<u8, CustomDataLimit>,119}120121#[frame_support::pallet]122pub mod pallet {123 use super::*;124 use frame_support::{125 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,126 traits::StorageVersion,127 };128 use frame_system::pallet_prelude::*;129 use up_data_structs::{CollectionId, TokenId};130 use super::weights::WeightInfo;131132 #[pallet::error]133 pub enum Error<T> {134 /// Not Refungible item data used to mint in Refungible collection.135 NotRefungibleDataUsedToMintFungibleCollectionToken,136 /// Maximum refungibility exceeded137 WrongRefungiblePieces,138 /// Refungible token can't be repartitioned by user who isn't owns all pieces139 RepartitionWhileNotOwningAllPieces,140 /// Refungible token can't nest other tokens141 RefungibleDisallowsNesting,142 /// Setting item properties is not allowed143 SettingPropertiesNotAllowed,144 }145146 #[pallet::config]147 pub trait Config:148 frame_system::Config + pallet_common::Config + pallet_structure::Config149 {150 type WeightInfo: WeightInfo;151 }152153 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);154155 #[pallet::pallet]156 #[pallet::storage_version(STORAGE_VERSION)]157 #[pallet::generate_store(pub(super) trait Store)]158 pub struct Pallet<T>(_);159160 /// Amount of tokens minted for collection161 #[pallet::storage]162 pub type TokensMinted<T: Config> =163 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;164165 /// Amount of burnt tokens for collection166 #[pallet::storage]167 pub type TokensBurnt<T: Config> =168 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;169170 /// Custom data serialized to bytes for token171 #[pallet::storage]172 pub type TokenData<T: Config> = StorageNMap<173 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),174 Value = ItemData,175 QueryKind = ValueQuery,176 >;177178 /// Total amount of pieces for token179 #[pallet::storage]180 pub type TotalSupply<T: Config> = StorageNMap<181 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),182 Value = u128,183 QueryKind = ValueQuery,184 >;185186 /// Used to enumerate tokens owned by account187 #[pallet::storage]188 pub type Owned<T: Config> = StorageNMap<189 Key = (190 Key<Twox64Concat, CollectionId>,191 Key<Blake2_128Concat, T::CrossAccountId>,192 Key<Twox64Concat, TokenId>,193 ),194 Value = bool,195 QueryKind = ValueQuery,196 >;197198 /// Amount of tokens owned by account199 #[pallet::storage]200 pub type AccountBalance<T: Config> = StorageNMap<201 Key = (202 Key<Twox64Concat, CollectionId>,203 // Owner204 Key<Blake2_128Concat, T::CrossAccountId>,205 ),206 Value = u32,207 QueryKind = ValueQuery,208 >;209210 /// Amount of token pieces owned by account211 #[pallet::storage]212 pub type Balance<T: Config> = StorageNMap<213 Key = (214 Key<Twox64Concat, CollectionId>,215 Key<Twox64Concat, TokenId>,216 // Owner217 Key<Blake2_128Concat, T::CrossAccountId>,218 ),219 Value = u128,220 QueryKind = ValueQuery,221 >;222223 /// Allowance set by an owner for a spender for a token224 #[pallet::storage]225 pub type Allowance<T: Config> = StorageNMap<226 Key = (227 Key<Twox64Concat, CollectionId>,228 Key<Twox64Concat, TokenId>,229 // Owner230 Key<Blake2_128, T::CrossAccountId>,231 // Spender232 Key<Blake2_128Concat, T::CrossAccountId>,233 ),234 Value = u128,235 QueryKind = ValueQuery,236 >;237238 #[pallet::hooks]239 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {240 fn on_runtime_upgrade() -> Weight {241 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {242 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {243 Some(<ItemDataVersion2>::from(v))244 })245 }246247 0248 }249 }250}251252pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);253impl<T: Config> RefungibleHandle<T> {254 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {255 Self(inner)256 }257 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {258 self.0259 }260}261impl<T: Config> Deref for RefungibleHandle<T> {262 type Target = pallet_common::CollectionHandle<T>;263264 fn deref(&self) -> &Self::Target {265 &self.0266 }267}268269impl<T: Config> Pallet<T> {270 /// Get number of RFT tokens in collection271 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {272 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)273 }274275 /// Check that RFT token exists276 ///277 /// - `token`: Token ID.278 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {279 <TotalSupply<T>>::contains_key((collection.id, token))280 }281}282283// unchecked calls skips any permission checks284impl<T: Config> Pallet<T> {285 /// Create RFT collection286 ///287 /// `init_collection` will take non-refundable deposit for collection creation.288 ///289 /// - `data`: Contains settings for collection limits and permissions.290 pub fn init_collection(291 owner: T::CrossAccountId,292 data: CreateCollectionData<T::AccountId>,293 ) -> Result<CollectionId, DispatchError> {294 <PalletCommon<T>>::init_collection(owner, data, false)295 }296297 /// Destroy RFT collection298 ///299 /// `destroy_collection` will throw error if collection contains any tokens.300 /// Only owner can destroy collection.301 pub fn destroy_collection(302 collection: RefungibleHandle<T>,303 sender: &T::CrossAccountId,304 ) -> DispatchResult {305 let id = collection.id;306307 if Self::collection_has_tokens(id) {308 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());309 }310311 // =========312313 PalletCommon::destroy_collection(collection.0, sender)?;314315 <TokensMinted<T>>::remove(id);316 <TokensBurnt<T>>::remove(id);317 <TokenData<T>>::remove_prefix((id,), None);318 <TotalSupply<T>>::remove_prefix((id,), None);319 <Balance<T>>::remove_prefix((id,), None);320 <Allowance<T>>::remove_prefix((id,), None);321 <Owned<T>>::remove_prefix((id,), None);322 <AccountBalance<T>>::remove_prefix((id,), None);323 Ok(())324 }325326 fn collection_has_tokens(collection_id: CollectionId) -> bool {327 <TokenData<T>>::iter_prefix((collection_id,))328 .next()329 .is_some()330 }331332 pub fn burn_token_unchecked(333 collection: &RefungibleHandle<T>,334 token_id: TokenId,335 ) -> DispatchResult {336 let burnt = <TokensBurnt<T>>::get(collection.id)337 .checked_add(1)338 .ok_or(ArithmeticError::Overflow)?;339340 <TokensBurnt<T>>::insert(collection.id, burnt);341 <TokenData<T>>::remove((collection.id, token_id));342 <TotalSupply<T>>::remove((collection.id, token_id));343 <Balance<T>>::remove_prefix((collection.id, token_id), None);344 <Allowance<T>>::remove_prefix((collection.id, token_id), None);345 // TODO: ERC721 transfer event346 Ok(())347 }348349 /// Burn RFT token pieces350 ///351 /// `burn` will decrease total amount of token pieces and amount owned by sender.352 /// If sender wouldn't have any pieces left after `burn` than she will stop being353 /// one of the owners of the token. If there is no account that owns any pieces of354 /// the token than token will be burned too.355 ///356 /// - `amount`: Amount of token pieces to burn.357 /// - `token`: Token who's pieces should be burned358 /// - `collection`: Collection that contains the token359 pub fn burn(360 collection: &RefungibleHandle<T>,361 owner: &T::CrossAccountId,362 token: TokenId,363 amount: u128,364 ) -> DispatchResult {365 let total_supply = <TotalSupply<T>>::get((collection.id, token))366 .checked_sub(amount)367 .ok_or(<CommonError<T>>::TokenValueTooLow)?;368369 // This was probally last owner of this token?370 if total_supply == 0 {371 // Ensure user actually owns this amount372 ensure!(373 <Balance<T>>::get((collection.id, token, owner)) == amount,374 <CommonError<T>>::TokenValueTooLow375 );376 let account_balance = <AccountBalance<T>>::get((collection.id, owner))377 .checked_sub(1)378 // Should not occur379 .ok_or(ArithmeticError::Underflow)?;380381 // =========382383 <Owned<T>>::remove((collection.id, owner, token));384 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);385 <AccountBalance<T>>::insert((collection.id, owner), account_balance);386 Self::burn_token_unchecked(collection, token)?;387 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(388 collection.id,389 token,390 owner.clone(),391 amount,392 ));393 return Ok(());394 }395396 let balance = <Balance<T>>::get((collection.id, token, owner))397 .checked_sub(amount)398 .ok_or(<CommonError<T>>::TokenValueTooLow)?;399 let account_balance = if balance == 0 {400 <AccountBalance<T>>::get((collection.id, owner))401 .checked_sub(1)402 // Should not occur403 .ok_or(ArithmeticError::Underflow)?404 } else {405 0406 };407408 // =========409410 if balance == 0 {411 <Owned<T>>::remove((collection.id, owner, token));412 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);413 <Balance<T>>::remove((collection.id, token, owner));414 <AccountBalance<T>>::insert((collection.id, owner), account_balance);415 } else {416 <Balance<T>>::insert((collection.id, token, owner), balance);417 }418 <TotalSupply<T>>::insert((collection.id, token), total_supply);419 // TODO: ERC20 transfer event420 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(421 collection.id,422 token,423 owner.clone(),424 amount,425 ));426 Ok(())427 }428429 /// Transfer RFT token pieces from one account to another.430 ///431 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.432 ///433 /// - `from`: Owner of token pieces to transfer.434 /// - `to`: Recepient of transfered token pieces.435 /// - `amount`: Amount of token pieces to transfer.436 /// - `token`: Token whos pieces should be transfered437 /// - `collection`: Collection that contains the token438 pub fn transfer(439 collection: &RefungibleHandle<T>,440 from: &T::CrossAccountId,441 to: &T::CrossAccountId,442 token: TokenId,443 amount: u128,444 nesting_budget: &dyn Budget,445 ) -> DispatchResult {446 ensure!(447 collection.limits.transfers_enabled(),448 <CommonError<T>>::TransferNotAllowed449 );450451 if collection.permissions.access() == AccessMode::AllowList {452 collection.check_allowlist(from)?;453 collection.check_allowlist(to)?;454 }455 <PalletCommon<T>>::ensure_correct_receiver(to)?;456457 let balance_from = <Balance<T>>::get((collection.id, token, from))458 .checked_sub(amount)459 .ok_or(<CommonError<T>>::TokenValueTooLow)?;460 let mut create_target = false;461 let from_to_differ = from != to;462 let balance_to = if from != to {463 let old_balance = <Balance<T>>::get((collection.id, token, to));464 if old_balance == 0 {465 create_target = true;466 }467 Some(468 old_balance469 .checked_add(amount)470 .ok_or(ArithmeticError::Overflow)?,471 )472 } else {473 None474 };475476 let account_balance_from = if balance_from == 0 {477 Some(478 <AccountBalance<T>>::get((collection.id, from))479 .checked_sub(1)480 // Should not occur481 .ok_or(ArithmeticError::Underflow)?,482 )483 } else {484 None485 };486 // Account data is created in token, AccountBalance should be increased487 // But only if from != to as we shouldn't check overflow in this case488 let account_balance_to = if create_target && from_to_differ {489 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))490 .checked_add(1)491 .ok_or(ArithmeticError::Overflow)?;492 ensure!(493 account_balance_to < collection.limits.account_token_ownership_limit(),494 <CommonError<T>>::AccountTokenLimitExceeded,495 );496497 Some(account_balance_to)498 } else {499 None500 };501502 // =========503504 <PalletStructure<T>>::nest_if_sent_to_token(505 from.clone(),506 to,507 collection.id,508 token,509 nesting_budget,510 )?;511512 if let Some(balance_to) = balance_to {513 // from != to514 if balance_from == 0 {515 <Balance<T>>::remove((collection.id, token, from));516 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);517 } else {518 <Balance<T>>::insert((collection.id, token, from), balance_from);519 }520 <Balance<T>>::insert((collection.id, token, to), balance_to);521 if let Some(account_balance_from) = account_balance_from {522 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);523 <Owned<T>>::remove((collection.id, from, token));524 }525 if let Some(account_balance_to) = account_balance_to {526 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);527 <Owned<T>>::insert((collection.id, to, token), true);528 }529 }530531 // TODO: ERC20 transfer event532 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(533 collection.id,534 token,535 from.clone(),536 to.clone(),537 amount,538 ));539 Ok(())540 }541542 /// Batched operation to create multiple RFT tokens.543 ///544 /// Same as `create_item` but creates multiple tokens.545 ///546 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.547 pub fn create_multiple_items(548 collection: &RefungibleHandle<T>,549 sender: &T::CrossAccountId,550 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,551 nesting_budget: &dyn Budget,552 ) -> DispatchResult {553 if !collection.is_owner_or_admin(sender) {554 ensure!(555 collection.permissions.mint_mode(),556 <CommonError<T>>::PublicMintingNotAllowed557 );558 collection.check_allowlist(sender)?;559560 for item in data.iter() {561 for user in item.users.keys() {562 collection.check_allowlist(user)?;563 }564 }565 }566567 for item in data.iter() {568 for (owner, _) in item.users.iter() {569 <PalletCommon<T>>::ensure_correct_receiver(owner)?;570 }571 }572573 // Total pieces per tokens574 let totals = data575 .iter()576 .map(|data| {577 Ok(data578 .users579 .iter()580 .map(|u| u.1)581 .try_fold(0u128, |acc, v| acc.checked_add(*v))582 .ok_or(ArithmeticError::Overflow)?)583 })584 .collect::<Result<Vec<_>, DispatchError>>()?;585 for total in &totals {586 ensure!(587 *total <= MAX_REFUNGIBLE_PIECES,588 <Error<T>>::WrongRefungiblePieces589 );590 }591592 let first_token_id = <TokensMinted<T>>::get(collection.id);593 let tokens_minted = first_token_id594 .checked_add(data.len() as u32)595 .ok_or(ArithmeticError::Overflow)?;596 ensure!(597 tokens_minted < collection.limits.token_limit(),598 <CommonError<T>>::CollectionTokenLimitExceeded599 );600601 let mut balances = BTreeMap::new();602 for data in &data {603 for owner in data.users.keys() {604 let balance = balances605 .entry(owner)606 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));607 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;608609 ensure!(610 *balance <= collection.limits.account_token_ownership_limit(),611 <CommonError<T>>::AccountTokenLimitExceeded,612 );613 }614 }615616 for (i, token) in data.iter().enumerate() {617 let token_id = TokenId(first_token_id + i as u32 + 1);618 for (to, _) in token.users.iter() {619 <PalletStructure<T>>::check_nesting(620 sender.clone(),621 to,622 collection.id,623 token_id,624 nesting_budget,625 )?;626 }627 }628629 // =========630631 <TokensMinted<T>>::insert(collection.id, tokens_minted);632 for (account, balance) in balances {633 <AccountBalance<T>>::insert((collection.id, account), balance);634 }635 for (i, token) in data.into_iter().enumerate() {636 let token_id = first_token_id + i as u32 + 1;637 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);638639 <TokenData<T>>::insert(640 (collection.id, token_id),641 ItemData {642 const_data: token.const_data,643 },644 );645646 for (user, amount) in token.users.into_iter() {647 if amount == 0 {648 continue;649 }650 <Balance<T>>::insert((collection.id, token_id, &user), amount);651 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);652 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(653 &user,654 collection.id,655 TokenId(token_id),656 );657658 // TODO: ERC20 transfer event659 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(660 collection.id,661 TokenId(token_id),662 user,663 amount,664 ));665 }666 }667 Ok(())668 }669670 pub fn set_allowance_unchecked(671 collection: &RefungibleHandle<T>,672 sender: &T::CrossAccountId,673 spender: &T::CrossAccountId,674 token: TokenId,675 amount: u128,676 ) {677 if amount == 0 {678 <Allowance<T>>::remove((collection.id, token, sender, spender));679 } else {680 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);681 }682 // TODO: ERC20 approval event683 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(684 collection.id,685 token,686 sender.clone(),687 spender.clone(),688 amount,689 ))690 }691692 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.693 ///694 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.695 pub fn set_allowance(696 collection: &RefungibleHandle<T>,697 sender: &T::CrossAccountId,698 spender: &T::CrossAccountId,699 token: TokenId,700 amount: u128,701 ) -> DispatchResult {702 if collection.permissions.access() == AccessMode::AllowList {703 collection.check_allowlist(sender)?;704 collection.check_allowlist(spender)?;705 }706707 <PalletCommon<T>>::ensure_correct_receiver(spender)?;708709 if <Balance<T>>::get((collection.id, token, sender)) < amount {710 ensure!(711 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),712 <CommonError<T>>::CantApproveMoreThanOwned713 );714 }715716 // =========717718 Self::set_allowance_unchecked(collection, sender, spender, token, amount);719 Ok(())720 }721722 /// Returns allowance, which should be set after transaction723 fn check_allowed(724 collection: &RefungibleHandle<T>,725 spender: &T::CrossAccountId,726 from: &T::CrossAccountId,727 token: TokenId,728 amount: u128,729 nesting_budget: &dyn Budget,730 ) -> Result<Option<u128>, DispatchError> {731 if spender.conv_eq(from) {732 return Ok(None);733 }734 if collection.permissions.access() == AccessMode::AllowList {735 // `from`, `to` checked in [`transfer`]736 collection.check_allowlist(spender)?;737 }738 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {739 // TODO: should collection owner be allowed to perform this transfer?740 ensure!(741 <PalletStructure<T>>::check_indirectly_owned(742 spender.clone(),743 source.0,744 source.1,745 None,746 nesting_budget747 )?,748 <CommonError<T>>::ApprovedValueTooLow,749 );750 return Ok(None);751 }752 let allowance =753 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);754 if allowance.is_none() {755 ensure!(756 collection.ignores_allowance(spender),757 <CommonError<T>>::ApprovedValueTooLow758 );759 }760 Ok(allowance)761 }762763 /// Transfer RFT token pieces from one account to another.764 ///765 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.766 /// The owner should set allowance for the spender to transfer pieces.767 ///768 /// [`transfer`]: struct.Pallet.html#method.transfer769 pub fn transfer_from(770 collection: &RefungibleHandle<T>,771 spender: &T::CrossAccountId,772 from: &T::CrossAccountId,773 to: &T::CrossAccountId,774 token: TokenId,775 amount: u128,776 nesting_budget: &dyn Budget,777 ) -> DispatchResult {778 let allowance =779 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;780781 // =========782783 Self::transfer(collection, from, to, token, amount, nesting_budget)?;784 if let Some(allowance) = allowance {785 Self::set_allowance_unchecked(collection, from, spender, token, allowance);786 }787 Ok(())788 }789790 /// Burn RFT token pieces from the account.791 ///792 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should793 /// set allowance for the spender to burn pieces794 ///795 /// [`burn`]: struct.Pallet.html#method.burn796 pub fn burn_from(797 collection: &RefungibleHandle<T>,798 spender: &T::CrossAccountId,799 from: &T::CrossAccountId,800 token: TokenId,801 amount: u128,802 nesting_budget: &dyn Budget,803 ) -> DispatchResult {804 let allowance =805 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;806807 // =========808809 Self::burn(collection, from, token, amount)?;810 if let Some(allowance) = allowance {811 Self::set_allowance_unchecked(collection, from, spender, token, allowance);812 }813 Ok(())814 }815816 /// Create RFT token.817 ///818 /// The sender should be the owner/admin of the collection or collection should be configured819 /// to allow public minting.820 ///821 /// - `data`: Contains list of users who will become the owners of the token pieces and amount822 /// of token pieces they will receive.823 pub fn create_item(824 collection: &RefungibleHandle<T>,825 sender: &T::CrossAccountId,826 data: CreateRefungibleExData<T::CrossAccountId>,827 nesting_budget: &dyn Budget,828 ) -> DispatchResult {829 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)830 }831832 /// Repartition RFT token.833 ///834 /// Repartition will set token balance of the sender and total amount of token pieces.835 /// Sender should own all of the token pieces.836 ///837 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.838 pub fn repartition(839 collection: &RefungibleHandle<T>,840 owner: &T::CrossAccountId,841 token: TokenId,842 amount: u128,843 ) -> DispatchResult {844 ensure!(845 amount <= MAX_REFUNGIBLE_PIECES,846 <Error<T>>::WrongRefungiblePieces847 );848 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);849 // Ensure user owns all pieces850 let total_supply = <TotalSupply<T>>::get((collection.id, token));851 let balance = <Balance<T>>::get((collection.id, token, owner));852 ensure!(853 total_supply == balance,854 <Error<T>>::RepartitionWhileNotOwningAllPieces855 );856857 <Balance<T>>::insert((collection.id, token, owner), amount);858 <TotalSupply<T>>::insert((collection.id, token), amount);859 Ok(())860 }861862 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {863 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()864 }865}