difftreelog
Merge pull request #432 from UniqueNetwork/doc/refungible-pallet
in: master
Doc for refungible pallet
2 files changed
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -145,6 +145,8 @@
}
}
+/// Implementation of `CommonCollectionOperations` for `RefungibleHandle`. It wraps Refungible Pallete
+/// methods and adds weight info.
impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {
fn create_item(
&self,
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#![cfg_attr(not(feature = "std"), no_std)]1819use frame_support::{ensure, BoundedVec};20use up_data_structs::{21 AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,22 CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,23};24use pallet_evm::account::CrossAccountId;25use pallet_common::{Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};26use pallet_structure::Pallet as PalletStructure;27use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};28use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};29use core::ops::Deref;30use codec::{Encode, Decode, MaxEncodedLen};31use scale_info::TypeInfo;3233pub use pallet::*;34#[cfg(feature = "runtime-benchmarks")]35pub mod benchmarking;36pub mod common;37pub mod erc;38pub mod weights;39pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4041#[struct_versioning::versioned(version = 2, upper)]42#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]43pub struct ItemData {44 pub const_data: BoundedVec<u8, CustomDataLimit>,4546 #[version(..2)]47 pub variable_data: BoundedVec<u8, CustomDataLimit>,48}4950#[frame_support::pallet]51pub mod pallet {52 use super::*;53 use frame_support::{54 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,55 traits::StorageVersion,56 };57 use frame_system::pallet_prelude::*;58 use up_data_structs::{CollectionId, TokenId};59 use super::weights::WeightInfo;6061 #[pallet::error]62 pub enum Error<T> {63 /// Not Refungible item data used to mint in Refungible collection.64 NotRefungibleDataUsedToMintFungibleCollectionToken,65 /// Maximum refungibility exceeded66 WrongRefungiblePieces,67 /// Refungible token can't be repartitioned by user who isn't owns all pieces68 RepartitionWhileNotOwningAllPieces,69 /// Refungible token can't nest other tokens70 RefungibleDisallowsNesting,71 /// Setting item properties is not allowed72 SettingPropertiesNotAllowed,73 }7475 #[pallet::config]76 pub trait Config:77 frame_system::Config + pallet_common::Config + pallet_structure::Config78 {79 type WeightInfo: WeightInfo;80 }8182 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8384 #[pallet::pallet]85 #[pallet::storage_version(STORAGE_VERSION)]86 #[pallet::generate_store(pub(super) trait Store)]87 pub struct Pallet<T>(_);8889 #[pallet::storage]90 pub type TokensMinted<T: Config> =91 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;92 #[pallet::storage]93 pub type TokensBurnt<T: Config> =94 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;9596 #[pallet::storage]97 pub type TokenData<T: Config> = StorageNMap<98 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),99 Value = ItemData,100 QueryKind = ValueQuery,101 >;102103 #[pallet::storage]104 pub type TotalSupply<T: Config> = StorageNMap<105 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),106 Value = u128,107 QueryKind = ValueQuery,108 >;109110 /// Used to enumerate tokens owned by account111 #[pallet::storage]112 pub type Owned<T: Config> = StorageNMap<113 Key = (114 Key<Twox64Concat, CollectionId>,115 Key<Blake2_128Concat, T::CrossAccountId>,116 Key<Twox64Concat, TokenId>,117 ),118 Value = bool,119 QueryKind = ValueQuery,120 >;121122 #[pallet::storage]123 pub type AccountBalance<T: Config> = StorageNMap<124 Key = (125 Key<Twox64Concat, CollectionId>,126 // Owner127 Key<Blake2_128Concat, T::CrossAccountId>,128 ),129 Value = u32,130 QueryKind = ValueQuery,131 >;132133 #[pallet::storage]134 pub type Balance<T: Config> = StorageNMap<135 Key = (136 Key<Twox64Concat, CollectionId>,137 Key<Twox64Concat, TokenId>,138 // Owner139 Key<Blake2_128Concat, T::CrossAccountId>,140 ),141 Value = u128,142 QueryKind = ValueQuery,143 >;144145 #[pallet::storage]146 pub type Allowance<T: Config> = StorageNMap<147 Key = (148 Key<Twox64Concat, CollectionId>,149 Key<Twox64Concat, TokenId>,150 // Owner151 Key<Blake2_128, T::CrossAccountId>,152 // Spender153 Key<Blake2_128Concat, T::CrossAccountId>,154 ),155 Value = u128,156 QueryKind = ValueQuery,157 >;158159 #[pallet::hooks]160 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {161 fn on_runtime_upgrade() -> Weight {162 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {163 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {164 Some(<ItemDataVersion2>::from(v))165 })166 }167168 0169 }170 }171}172173pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);174impl<T: Config> RefungibleHandle<T> {175 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {176 Self(inner)177 }178 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {179 self.0180 }181}182impl<T: Config> Deref for RefungibleHandle<T> {183 type Target = pallet_common::CollectionHandle<T>;184185 fn deref(&self) -> &Self::Target {186 &self.0187 }188}189190impl<T: Config> Pallet<T> {191 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {192 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)193 }194 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {195 <TotalSupply<T>>::contains_key((collection.id, token))196 }197}198199// unchecked calls skips any permission checks200impl<T: Config> Pallet<T> {201 pub fn init_collection(202 owner: T::CrossAccountId,203 data: CreateCollectionData<T::AccountId>,204 ) -> Result<CollectionId, DispatchError> {205 <PalletCommon<T>>::init_collection(owner, data, false)206 }207 pub fn destroy_collection(208 collection: RefungibleHandle<T>,209 sender: &T::CrossAccountId,210 ) -> DispatchResult {211 let id = collection.id;212213 if Self::collection_has_tokens(id) {214 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());215 }216217 // =========218219 PalletCommon::destroy_collection(collection.0, sender)?;220221 <TokensMinted<T>>::remove(id);222 <TokensBurnt<T>>::remove(id);223 <TokenData<T>>::remove_prefix((id,), None);224 <TotalSupply<T>>::remove_prefix((id,), None);225 <Balance<T>>::remove_prefix((id,), None);226 <Allowance<T>>::remove_prefix((id,), None);227 <Owned<T>>::remove_prefix((id,), None);228 <AccountBalance<T>>::remove_prefix((id,), None);229 Ok(())230 }231232 fn collection_has_tokens(collection_id: CollectionId) -> bool {233 <TokenData<T>>::iter_prefix((collection_id,))234 .next()235 .is_some()236 }237238 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {239 let burnt = <TokensBurnt<T>>::get(collection.id)240 .checked_add(1)241 .ok_or(ArithmeticError::Overflow)?;242243 <TokensBurnt<T>>::insert(collection.id, burnt);244 <TokenData<T>>::remove((collection.id, token_id));245 <TotalSupply<T>>::remove((collection.id, token_id));246 <Balance<T>>::remove_prefix((collection.id, token_id), None);247 <Allowance<T>>::remove_prefix((collection.id, token_id), None);248 // TODO: ERC721 transfer event249 Ok(())250 }251252 pub fn burn(253 collection: &RefungibleHandle<T>,254 owner: &T::CrossAccountId,255 token: TokenId,256 amount: u128,257 ) -> DispatchResult {258 let total_supply = <TotalSupply<T>>::get((collection.id, token))259 .checked_sub(amount)260 .ok_or(<CommonError<T>>::TokenValueTooLow)?;261262 // This was probally last owner of this token?263 if total_supply == 0 {264 // Ensure user actually owns this amount265 ensure!(266 <Balance<T>>::get((collection.id, token, owner)) == amount,267 <CommonError<T>>::TokenValueTooLow268 );269 let account_balance = <AccountBalance<T>>::get((collection.id, owner))270 .checked_sub(1)271 // Should not occur272 .ok_or(ArithmeticError::Underflow)?;273274 // =========275276 <Owned<T>>::remove((collection.id, owner, token));277 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);278 <AccountBalance<T>>::insert((collection.id, owner), account_balance);279 Self::burn_token(collection, token)?;280 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(281 collection.id,282 token,283 owner.clone(),284 amount,285 ));286 return Ok(());287 }288289 let balance = <Balance<T>>::get((collection.id, token, owner))290 .checked_sub(amount)291 .ok_or(<CommonError<T>>::TokenValueTooLow)?;292 let account_balance = if balance == 0 {293 <AccountBalance<T>>::get((collection.id, owner))294 .checked_sub(1)295 // Should not occur296 .ok_or(ArithmeticError::Underflow)?297 } else {298 0299 };300301 // =========302303 if balance == 0 {304 <Owned<T>>::remove((collection.id, owner, token));305 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);306 <Balance<T>>::remove((collection.id, token, owner));307 <AccountBalance<T>>::insert((collection.id, owner), account_balance);308 } else {309 <Balance<T>>::insert((collection.id, token, owner), balance);310 }311 <TotalSupply<T>>::insert((collection.id, token), total_supply);312 // TODO: ERC20 transfer event313 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(314 collection.id,315 token,316 owner.clone(),317 amount,318 ));319 Ok(())320 }321322 pub fn transfer(323 collection: &RefungibleHandle<T>,324 from: &T::CrossAccountId,325 to: &T::CrossAccountId,326 token: TokenId,327 amount: u128,328 nesting_budget: &dyn Budget,329 ) -> DispatchResult {330 ensure!(331 collection.limits.transfers_enabled(),332 <CommonError<T>>::TransferNotAllowed333 );334335 if collection.permissions.access() == AccessMode::AllowList {336 collection.check_allowlist(from)?;337 collection.check_allowlist(to)?;338 }339 <PalletCommon<T>>::ensure_correct_receiver(to)?;340341 let balance_from = <Balance<T>>::get((collection.id, token, from))342 .checked_sub(amount)343 .ok_or(<CommonError<T>>::TokenValueTooLow)?;344 let mut create_target = false;345 let from_to_differ = from != to;346 let balance_to = if from != to {347 let old_balance = <Balance<T>>::get((collection.id, token, to));348 if old_balance == 0 {349 create_target = true;350 }351 Some(352 old_balance353 .checked_add(amount)354 .ok_or(ArithmeticError::Overflow)?,355 )356 } else {357 None358 };359360 let account_balance_from = if balance_from == 0 {361 Some(362 <AccountBalance<T>>::get((collection.id, from))363 .checked_sub(1)364 // Should not occur365 .ok_or(ArithmeticError::Underflow)?,366 )367 } else {368 None369 };370 // Account data is created in token, AccountBalance should be increased371 // But only if from != to as we shouldn't check overflow in this case372 let account_balance_to = if create_target && from_to_differ {373 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))374 .checked_add(1)375 .ok_or(ArithmeticError::Overflow)?;376 ensure!(377 account_balance_to < collection.limits.account_token_ownership_limit(),378 <CommonError<T>>::AccountTokenLimitExceeded,379 );380381 Some(account_balance_to)382 } else {383 None384 };385386 // =========387388 <PalletStructure<T>>::nest_if_sent_to_token(389 from.clone(),390 to,391 collection.id,392 token,393 nesting_budget,394 )?;395396 if let Some(balance_to) = balance_to {397 // from != to398 if balance_from == 0 {399 <Balance<T>>::remove((collection.id, token, from));400 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);401 } else {402 <Balance<T>>::insert((collection.id, token, from), balance_from);403 }404 <Balance<T>>::insert((collection.id, token, to), balance_to);405 if let Some(account_balance_from) = account_balance_from {406 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);407 <Owned<T>>::remove((collection.id, from, token));408 }409 if let Some(account_balance_to) = account_balance_to {410 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);411 <Owned<T>>::insert((collection.id, to, token), true);412 }413 }414415 // TODO: ERC20 transfer event416 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(417 collection.id,418 token,419 from.clone(),420 to.clone(),421 amount,422 ));423 Ok(())424 }425426 pub fn create_multiple_items(427 collection: &RefungibleHandle<T>,428 sender: &T::CrossAccountId,429 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,430 nesting_budget: &dyn Budget,431 ) -> DispatchResult {432 if !collection.is_owner_or_admin(sender) {433 ensure!(434 collection.permissions.mint_mode(),435 <CommonError<T>>::PublicMintingNotAllowed436 );437 collection.check_allowlist(sender)?;438439 for item in data.iter() {440 for user in item.users.keys() {441 collection.check_allowlist(user)?;442 }443 }444 }445446 for item in data.iter() {447 for (owner, _) in item.users.iter() {448 <PalletCommon<T>>::ensure_correct_receiver(owner)?;449 }450 }451452 // Total pieces per tokens453 let totals = data454 .iter()455 .map(|data| {456 Ok(data457 .users458 .iter()459 .map(|u| u.1)460 .try_fold(0u128, |acc, v| acc.checked_add(*v))461 .ok_or(ArithmeticError::Overflow)?)462 })463 .collect::<Result<Vec<_>, DispatchError>>()?;464 for total in &totals {465 ensure!(466 *total <= MAX_REFUNGIBLE_PIECES,467 <Error<T>>::WrongRefungiblePieces468 );469 }470471 let first_token_id = <TokensMinted<T>>::get(collection.id);472 let tokens_minted = first_token_id473 .checked_add(data.len() as u32)474 .ok_or(ArithmeticError::Overflow)?;475 ensure!(476 tokens_minted < collection.limits.token_limit(),477 <CommonError<T>>::CollectionTokenLimitExceeded478 );479480 let mut balances = BTreeMap::new();481 for data in &data {482 for owner in data.users.keys() {483 let balance = balances484 .entry(owner)485 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));486 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;487488 ensure!(489 *balance <= collection.limits.account_token_ownership_limit(),490 <CommonError<T>>::AccountTokenLimitExceeded,491 );492 }493 }494495 for (i, token) in data.iter().enumerate() {496 let token_id = TokenId(first_token_id + i as u32 + 1);497 for (to, _) in token.users.iter() {498 <PalletStructure<T>>::check_nesting(499 sender.clone(),500 to,501 collection.id,502 token_id,503 nesting_budget,504 )?;505 }506 }507508 // =========509510 <TokensMinted<T>>::insert(collection.id, tokens_minted);511 for (account, balance) in balances {512 <AccountBalance<T>>::insert((collection.id, account), balance);513 }514 for (i, token) in data.into_iter().enumerate() {515 let token_id = first_token_id + i as u32 + 1;516 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);517518 <TokenData<T>>::insert(519 (collection.id, token_id),520 ItemData {521 const_data: token.const_data,522 },523 );524525 for (user, amount) in token.users.into_iter() {526 if amount == 0 {527 continue;528 }529 <Balance<T>>::insert((collection.id, token_id, &user), amount);530 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);531 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(532 &user,533 collection.id,534 TokenId(token_id),535 );536537 // TODO: ERC20 transfer event538 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(539 collection.id,540 TokenId(token_id),541 user,542 amount,543 ));544 }545 }546 Ok(())547 }548549 pub fn set_allowance_unchecked(550 collection: &RefungibleHandle<T>,551 sender: &T::CrossAccountId,552 spender: &T::CrossAccountId,553 token: TokenId,554 amount: u128,555 ) {556 if amount == 0 {557 <Allowance<T>>::remove((collection.id, token, sender, spender));558 } else {559 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);560 }561 // TODO: ERC20 approval event562 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(563 collection.id,564 token,565 sender.clone(),566 spender.clone(),567 amount,568 ))569 }570571 pub fn set_allowance(572 collection: &RefungibleHandle<T>,573 sender: &T::CrossAccountId,574 spender: &T::CrossAccountId,575 token: TokenId,576 amount: u128,577 ) -> DispatchResult {578 if collection.permissions.access() == AccessMode::AllowList {579 collection.check_allowlist(sender)?;580 collection.check_allowlist(spender)?;581 }582583 <PalletCommon<T>>::ensure_correct_receiver(spender)?;584585 if <Balance<T>>::get((collection.id, token, sender)) < amount {586 ensure!(587 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),588 <CommonError<T>>::CantApproveMoreThanOwned589 );590 }591592 // =========593594 Self::set_allowance_unchecked(collection, sender, spender, token, amount);595 Ok(())596 }597598 /// Returns allowance, which should be set after transaction599 fn check_allowed(600 collection: &RefungibleHandle<T>,601 spender: &T::CrossAccountId,602 from: &T::CrossAccountId,603 token: TokenId,604 amount: u128,605 nesting_budget: &dyn Budget,606 ) -> Result<Option<u128>, DispatchError> {607 if spender.conv_eq(from) {608 return Ok(None);609 }610 if collection.permissions.access() == AccessMode::AllowList {611 // `from`, `to` checked in [`transfer`]612 collection.check_allowlist(spender)?;613 }614 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {615 // TODO: should collection owner be allowed to perform this transfer?616 ensure!(617 <PalletStructure<T>>::check_indirectly_owned(618 spender.clone(),619 source.0,620 source.1,621 None,622 nesting_budget623 )?,624 <CommonError<T>>::ApprovedValueTooLow,625 );626 return Ok(None);627 }628 let allowance =629 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);630 if allowance.is_none() {631 ensure!(632 collection.ignores_allowance(spender),633 <CommonError<T>>::ApprovedValueTooLow634 );635 }636 Ok(allowance)637 }638639 pub fn transfer_from(640 collection: &RefungibleHandle<T>,641 spender: &T::CrossAccountId,642 from: &T::CrossAccountId,643 to: &T::CrossAccountId,644 token: TokenId,645 amount: u128,646 nesting_budget: &dyn Budget,647 ) -> DispatchResult {648 let allowance =649 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;650651 // =========652653 Self::transfer(collection, from, to, token, amount, nesting_budget)?;654 if let Some(allowance) = allowance {655 Self::set_allowance_unchecked(collection, from, spender, token, allowance);656 }657 Ok(())658 }659660 pub fn burn_from(661 collection: &RefungibleHandle<T>,662 spender: &T::CrossAccountId,663 from: &T::CrossAccountId,664 token: TokenId,665 amount: u128,666 nesting_budget: &dyn Budget,667 ) -> DispatchResult {668 let allowance =669 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;670671 // =========672673 Self::burn(collection, from, token, amount)?;674 if let Some(allowance) = allowance {675 Self::set_allowance_unchecked(collection, from, spender, token, allowance);676 }677 Ok(())678 }679680 /// Delegated to `create_multiple_items`681 pub fn create_item(682 collection: &RefungibleHandle<T>,683 sender: &T::CrossAccountId,684 data: CreateRefungibleExData<T::CrossAccountId>,685 nesting_budget: &dyn Budget,686 ) -> DispatchResult {687 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)688 }689690 pub fn repartition(691 collection: &RefungibleHandle<T>,692 owner: &T::CrossAccountId,693 token: TokenId,694 amount: u128,695 ) -> DispatchResult {696 ensure!(697 amount <= MAX_REFUNGIBLE_PIECES,698 <Error<T>>::WrongRefungiblePieces699 );700 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);701 // Ensure user owns all pieces702 let total_supply = <TotalSupply<T>>::get((collection.id, token));703 let balance = <Balance<T>>::get((collection.id, token, owner));704 ensure!(705 total_supply == balance,706 <Error<T>>::RepartitionWhileNotOwningAllPieces707 );708709 <Balance<T>>::insert((collection.id, token, owner), amount);710 <TotalSupply<T>>::insert((collection.id, token), amount);711 Ok(())712 }713714 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {715 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()716 }717}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`]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 /// `burn` can be called even if there are multiple owners of the RFT token.353 /// If sender wouldn't have any pieces left after `burn` than she will stop being354 /// one of the owners of the token. If there is no account that owns any pieces of355 /// the token than token will be burned too.356 ///357 /// - `amount`: Amount of token pieces to burn.358 /// - `token`: Token who's pieces should be burned359 /// - `collection`: Collection that contains the token360 pub fn burn(361 collection: &RefungibleHandle<T>,362 owner: &T::CrossAccountId,363 token: TokenId,364 amount: u128,365 ) -> DispatchResult {366 let total_supply = <TotalSupply<T>>::get((collection.id, token))367 .checked_sub(amount)368 .ok_or(<CommonError<T>>::TokenValueTooLow)?;369370 // This was probally last owner of this token?371 if total_supply == 0 {372 // Ensure user actually owns this amount373 ensure!(374 <Balance<T>>::get((collection.id, token, owner)) == amount,375 <CommonError<T>>::TokenValueTooLow376 );377 let account_balance = <AccountBalance<T>>::get((collection.id, owner))378 .checked_sub(1)379 // Should not occur380 .ok_or(ArithmeticError::Underflow)?;381382 // =========383384 <Owned<T>>::remove((collection.id, owner, token));385 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);386 <AccountBalance<T>>::insert((collection.id, owner), account_balance);387 Self::burn_token_unchecked(collection, token)?;388 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(389 collection.id,390 token,391 owner.clone(),392 amount,393 ));394 return Ok(());395 }396397 let balance = <Balance<T>>::get((collection.id, token, owner))398 .checked_sub(amount)399 .ok_or(<CommonError<T>>::TokenValueTooLow)?;400 let account_balance = if balance == 0 {401 <AccountBalance<T>>::get((collection.id, owner))402 .checked_sub(1)403 // Should not occur404 .ok_or(ArithmeticError::Underflow)?405 } else {406 0407 };408409 // =========410411 if balance == 0 {412 <Owned<T>>::remove((collection.id, owner, token));413 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);414 <Balance<T>>::remove((collection.id, token, owner));415 <AccountBalance<T>>::insert((collection.id, owner), account_balance);416 } else {417 <Balance<T>>::insert((collection.id, token, owner), balance);418 }419 <TotalSupply<T>>::insert((collection.id, token), total_supply);420 // TODO: ERC20 transfer event421 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(422 collection.id,423 token,424 owner.clone(),425 amount,426 ));427 Ok(())428 }429430 /// Transfer RFT token pieces from one account to another.431 ///432 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.433 ///434 /// - `from`: Owner of token pieces to transfer.435 /// - `to`: Recepient of transfered token pieces.436 /// - `amount`: Amount of token pieces to transfer.437 /// - `token`: Token whos pieces should be transfered438 /// - `collection`: Collection that contains the token439 pub fn transfer(440 collection: &RefungibleHandle<T>,441 from: &T::CrossAccountId,442 to: &T::CrossAccountId,443 token: TokenId,444 amount: u128,445 nesting_budget: &dyn Budget,446 ) -> DispatchResult {447 ensure!(448 collection.limits.transfers_enabled(),449 <CommonError<T>>::TransferNotAllowed450 );451452 if collection.permissions.access() == AccessMode::AllowList {453 collection.check_allowlist(from)?;454 collection.check_allowlist(to)?;455 }456 <PalletCommon<T>>::ensure_correct_receiver(to)?;457458 let balance_from = <Balance<T>>::get((collection.id, token, from))459 .checked_sub(amount)460 .ok_or(<CommonError<T>>::TokenValueTooLow)?;461 let mut create_target = false;462 let from_to_differ = from != to;463 let balance_to = if from != to {464 let old_balance = <Balance<T>>::get((collection.id, token, to));465 if old_balance == 0 {466 create_target = true;467 }468 Some(469 old_balance470 .checked_add(amount)471 .ok_or(ArithmeticError::Overflow)?,472 )473 } else {474 None475 };476477 let account_balance_from = if balance_from == 0 {478 Some(479 <AccountBalance<T>>::get((collection.id, from))480 .checked_sub(1)481 // Should not occur482 .ok_or(ArithmeticError::Underflow)?,483 )484 } else {485 None486 };487 // Account data is created in token, AccountBalance should be increased488 // But only if from != to as we shouldn't check overflow in this case489 let account_balance_to = if create_target && from_to_differ {490 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))491 .checked_add(1)492 .ok_or(ArithmeticError::Overflow)?;493 ensure!(494 account_balance_to < collection.limits.account_token_ownership_limit(),495 <CommonError<T>>::AccountTokenLimitExceeded,496 );497498 Some(account_balance_to)499 } else {500 None501 };502503 // =========504505 <PalletStructure<T>>::nest_if_sent_to_token(506 from.clone(),507 to,508 collection.id,509 token,510 nesting_budget,511 )?;512513 if let Some(balance_to) = balance_to {514 // from != to515 if balance_from == 0 {516 <Balance<T>>::remove((collection.id, token, from));517 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);518 } else {519 <Balance<T>>::insert((collection.id, token, from), balance_from);520 }521 <Balance<T>>::insert((collection.id, token, to), balance_to);522 if let Some(account_balance_from) = account_balance_from {523 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);524 <Owned<T>>::remove((collection.id, from, token));525 }526 if let Some(account_balance_to) = account_balance_to {527 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);528 <Owned<T>>::insert((collection.id, to, token), true);529 }530 }531532 // TODO: ERC20 transfer event533 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(534 collection.id,535 token,536 from.clone(),537 to.clone(),538 amount,539 ));540 Ok(())541 }542543 /// Batched operation to create multiple RFT tokens.544 ///545 /// Same as `create_item` but creates multiple tokens.546 ///547 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.548 pub fn create_multiple_items(549 collection: &RefungibleHandle<T>,550 sender: &T::CrossAccountId,551 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,552 nesting_budget: &dyn Budget,553 ) -> DispatchResult {554 if !collection.is_owner_or_admin(sender) {555 ensure!(556 collection.permissions.mint_mode(),557 <CommonError<T>>::PublicMintingNotAllowed558 );559 collection.check_allowlist(sender)?;560561 for item in data.iter() {562 for user in item.users.keys() {563 collection.check_allowlist(user)?;564 }565 }566 }567568 for item in data.iter() {569 for (owner, _) in item.users.iter() {570 <PalletCommon<T>>::ensure_correct_receiver(owner)?;571 }572 }573574 // Total pieces per tokens575 let totals = data576 .iter()577 .map(|data| {578 Ok(data579 .users580 .iter()581 .map(|u| u.1)582 .try_fold(0u128, |acc, v| acc.checked_add(*v))583 .ok_or(ArithmeticError::Overflow)?)584 })585 .collect::<Result<Vec<_>, DispatchError>>()?;586 for total in &totals {587 ensure!(588 *total <= MAX_REFUNGIBLE_PIECES,589 <Error<T>>::WrongRefungiblePieces590 );591 }592593 let first_token_id = <TokensMinted<T>>::get(collection.id);594 let tokens_minted = first_token_id595 .checked_add(data.len() as u32)596 .ok_or(ArithmeticError::Overflow)?;597 ensure!(598 tokens_minted < collection.limits.token_limit(),599 <CommonError<T>>::CollectionTokenLimitExceeded600 );601602 let mut balances = BTreeMap::new();603 for data in &data {604 for owner in data.users.keys() {605 let balance = balances606 .entry(owner)607 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));608 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;609610 ensure!(611 *balance <= collection.limits.account_token_ownership_limit(),612 <CommonError<T>>::AccountTokenLimitExceeded,613 );614 }615 }616617 for (i, token) in data.iter().enumerate() {618 let token_id = TokenId(first_token_id + i as u32 + 1);619 for (to, _) in token.users.iter() {620 <PalletStructure<T>>::check_nesting(621 sender.clone(),622 to,623 collection.id,624 token_id,625 nesting_budget,626 )?;627 }628 }629630 // =========631632 <TokensMinted<T>>::insert(collection.id, tokens_minted);633 for (account, balance) in balances {634 <AccountBalance<T>>::insert((collection.id, account), balance);635 }636 for (i, token) in data.into_iter().enumerate() {637 let token_id = first_token_id + i as u32 + 1;638 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);639640 <TokenData<T>>::insert(641 (collection.id, token_id),642 ItemData {643 const_data: token.const_data,644 },645 );646647 for (user, amount) in token.users.into_iter() {648 if amount == 0 {649 continue;650 }651 <Balance<T>>::insert((collection.id, token_id, &user), amount);652 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);653 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(654 &user,655 collection.id,656 TokenId(token_id),657 );658659 // TODO: ERC20 transfer event660 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(661 collection.id,662 TokenId(token_id),663 user,664 amount,665 ));666 }667 }668 Ok(())669 }670671 pub fn set_allowance_unchecked(672 collection: &RefungibleHandle<T>,673 sender: &T::CrossAccountId,674 spender: &T::CrossAccountId,675 token: TokenId,676 amount: u128,677 ) {678 if amount == 0 {679 <Allowance<T>>::remove((collection.id, token, sender, spender));680 } else {681 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);682 }683 // TODO: ERC20 approval event684 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(685 collection.id,686 token,687 sender.clone(),688 spender.clone(),689 amount,690 ))691 }692693 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.694 ///695 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.696 pub fn set_allowance(697 collection: &RefungibleHandle<T>,698 sender: &T::CrossAccountId,699 spender: &T::CrossAccountId,700 token: TokenId,701 amount: u128,702 ) -> DispatchResult {703 if collection.permissions.access() == AccessMode::AllowList {704 collection.check_allowlist(sender)?;705 collection.check_allowlist(spender)?;706 }707708 <PalletCommon<T>>::ensure_correct_receiver(spender)?;709710 if <Balance<T>>::get((collection.id, token, sender)) < amount {711 ensure!(712 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),713 <CommonError<T>>::CantApproveMoreThanOwned714 );715 }716717 // =========718719 Self::set_allowance_unchecked(collection, sender, spender, token, amount);720 Ok(())721 }722723 /// Returns allowance, which should be set after transaction724 fn check_allowed(725 collection: &RefungibleHandle<T>,726 spender: &T::CrossAccountId,727 from: &T::CrossAccountId,728 token: TokenId,729 amount: u128,730 nesting_budget: &dyn Budget,731 ) -> Result<Option<u128>, DispatchError> {732 if spender.conv_eq(from) {733 return Ok(None);734 }735 if collection.permissions.access() == AccessMode::AllowList {736 // `from`, `to` checked in [`transfer`]737 collection.check_allowlist(spender)?;738 }739 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {740 // TODO: should collection owner be allowed to perform this transfer?741 ensure!(742 <PalletStructure<T>>::check_indirectly_owned(743 spender.clone(),744 source.0,745 source.1,746 None,747 nesting_budget748 )?,749 <CommonError<T>>::ApprovedValueTooLow,750 );751 return Ok(None);752 }753 let allowance =754 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);755 if allowance.is_none() {756 ensure!(757 collection.ignores_allowance(spender),758 <CommonError<T>>::ApprovedValueTooLow759 );760 }761 Ok(allowance)762 }763764 /// Transfer RFT token pieces from one account to another.765 ///766 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.767 /// The owner should set allowance for the spender to transfer pieces.768 ///769 /// [`transfer`]: struct.Pallet.html#method.transfer770 pub fn transfer_from(771 collection: &RefungibleHandle<T>,772 spender: &T::CrossAccountId,773 from: &T::CrossAccountId,774 to: &T::CrossAccountId,775 token: TokenId,776 amount: u128,777 nesting_budget: &dyn Budget,778 ) -> DispatchResult {779 let allowance =780 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;781782 // =========783784 Self::transfer(collection, from, to, token, amount, nesting_budget)?;785 if let Some(allowance) = allowance {786 Self::set_allowance_unchecked(collection, from, spender, token, allowance);787 }788 Ok(())789 }790791 /// Burn RFT token pieces from the account.792 ///793 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should794 /// set allowance for the spender to burn pieces795 ///796 /// [`burn`]: struct.Pallet.html#method.burn797 pub fn burn_from(798 collection: &RefungibleHandle<T>,799 spender: &T::CrossAccountId,800 from: &T::CrossAccountId,801 token: TokenId,802 amount: u128,803 nesting_budget: &dyn Budget,804 ) -> DispatchResult {805 let allowance =806 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;807808 // =========809810 Self::burn(collection, from, token, amount)?;811 if let Some(allowance) = allowance {812 Self::set_allowance_unchecked(collection, from, spender, token, allowance);813 }814 Ok(())815 }816817 /// Create RFT token.818 ///819 /// The sender should be the owner/admin of the collection or collection should be configured820 /// to allow public minting.821 ///822 /// - `data`: Contains list of users who will become the owners of the token pieces and amount823 /// of token pieces they will receive.824 pub fn create_item(825 collection: &RefungibleHandle<T>,826 sender: &T::CrossAccountId,827 data: CreateRefungibleExData<T::CrossAccountId>,828 nesting_budget: &dyn Budget,829 ) -> DispatchResult {830 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)831 }832833 /// Repartition RFT token.834 ///835 /// `repartition` will set token balance of the sender and total amount of token pieces.836 /// Sender should own all of the token pieces. `repartition' could be done even if some837 /// token pieces were burned before.838 ///839 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.840 pub fn repartition(841 collection: &RefungibleHandle<T>,842 owner: &T::CrossAccountId,843 token: TokenId,844 amount: u128,845 ) -> DispatchResult {846 ensure!(847 amount <= MAX_REFUNGIBLE_PIECES,848 <Error<T>>::WrongRefungiblePieces849 );850 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);851 // Ensure user owns all pieces852 let total_supply = <TotalSupply<T>>::get((collection.id, token));853 let balance = <Balance<T>>::get((collection.id, token, owner));854 ensure!(855 total_supply == balance,856 <Error<T>>::RepartitionWhileNotOwningAllPieces857 );858859 <Balance<T>>::insert((collection.id, token, owner), amount);860 <TotalSupply<T>>::insert((collection.id, token), amount);861 Ok(())862 }863864 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {865 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()866 }867}