difftreelog
fix add create_multiple_items_common
in: master
1 file changed
pallets/fungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::{ensure};84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86 AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,87 budget::Budget,88};89use pallet_common::{90 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91 eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115 use up_data_structs::CollectionId;116 use super::weights::WeightInfo;117118 #[pallet::error]119 pub enum Error<T> {120 /// Not Fungible item data used to mint in Fungible collection.121 NotFungibleDataUsedToMintFungibleCollectionToken,122 /// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.123 FungibleItemsHaveNoId,124 /// Tried to set data for fungible item.125 FungibleItemsDontHaveData,126 /// Fungible token does not support nesting.127 FungibleDisallowsNesting,128 /// Setting item properties is not allowed.129 SettingPropertiesNotAllowed,130 }131132 #[pallet::config]133 pub trait Config:134 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config135 {136 type WeightInfo: WeightInfo;137 }138139 #[pallet::pallet]140 #[pallet::generate_store(pub(super) trait Store)]141 pub struct Pallet<T>(_);142143 /// Total amount of fungible tokens inside a collection.144 #[pallet::storage]145 pub type TotalSupply<T: Config> =146 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;147148 /// Amount of tokens owned by an account inside a collection.149 #[pallet::storage]150 pub type Balance<T: Config> = StorageNMap<151 Key = (152 Key<Twox64Concat, CollectionId>,153 Key<Blake2_128Concat, T::CrossAccountId>,154 ),155 Value = u128,156 QueryKind = ValueQuery,157 >;158159 /// Storage for assets delegated to a limited extent to other users.160 #[pallet::storage]161 pub type Allowance<T: Config> = StorageNMap<162 Key = (163 Key<Twox64Concat, CollectionId>,164 Key<Blake2_128, T::CrossAccountId>,165 Key<Blake2_128Concat, T::CrossAccountId>,166 ),167 Value = u128,168 QueryKind = ValueQuery,169 >;170171 /// Foreign collection flag172 #[pallet::storage]173 pub type ForeignCollection<T: Config> =174 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = bool, QueryKind = ValueQuery>;175}176177/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.178/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].179pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);180181/// Implementation of methods required for dispatching during runtime.182impl<T: Config> FungibleHandle<T> {183 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].184 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {185 Self(inner)186 }187188 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].189 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {190 self.0191 }192 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].193 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {194 &mut self.0195 }196}197impl<T: Config> WithRecorder<T> for FungibleHandle<T> {198 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {199 self.0.recorder()200 }201 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {202 self.0.into_recorder()203 }204}205impl<T: Config> Deref for FungibleHandle<T> {206 type Target = pallet_common::CollectionHandle<T>;207208 fn deref(&self) -> &Self::Target {209 &self.0210 }211}212213/// Pallet implementation for fungible assets214impl<T: Config> Pallet<T> {215 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.216 pub fn init_collection(217 owner: T::CrossAccountId,218 data: CreateCollectionData<T::AccountId>,219 ) -> Result<CollectionId, DispatchError> {220 <PalletCommon<T>>::init_collection(owner, data, false)221 }222223 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.224 pub fn init_foreign_collection(225 owner: T::CrossAccountId,226 data: CreateCollectionData<T::AccountId>,227 ) -> Result<CollectionId, DispatchError> {228 let id = <PalletCommon<T>>::init_collection(owner, data, false)?;229 <ForeignCollection<T>>::insert(id, true);230 Ok(id)231 }232233 /// Destroys a collection.234 pub fn destroy_collection(235 collection: FungibleHandle<T>,236 sender: &T::CrossAccountId,237 ) -> DispatchResult {238 let id = collection.id;239240 if Self::collection_has_tokens(id) {241 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());242 }243244 // =========245246 PalletCommon::destroy_collection(collection.0, sender)?;247248 <ForeignCollection<T>>::remove(id);249 <TotalSupply<T>>::remove(id);250 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);251 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);252 Ok(())253 }254255 ///Checks if collection has tokens. Return `true` if it has.256 fn collection_has_tokens(collection_id: CollectionId) -> bool {257 <TotalSupply<T>>::get(collection_id) != 0258 }259260 /// Burns the specified amount of the token. If the token balance261 /// or total supply is less than the given value,262 /// it will return [DispatchError].263 pub fn burn(264 collection: &FungibleHandle<T>,265 owner: &T::CrossAccountId,266 amount: u128,267 ) -> DispatchResult {268 let total_supply = <TotalSupply<T>>::get(collection.id)269 .checked_sub(amount)270 .ok_or(<CommonError<T>>::TokenValueTooLow)?;271272 let balance = <Balance<T>>::get((collection.id, owner))273 .checked_sub(amount)274 .ok_or(<CommonError<T>>::TokenValueTooLow)?;275276 // Foreign collection check277 ensure!(278 !<ForeignCollection<T>>::get(collection.id),279 <CommonError<T>>::NoPermission280 );281282 if collection.permissions.access() == AccessMode::AllowList {283 collection.check_allowlist(owner)?;284 }285286 // =========287288 if balance == 0 {289 <Balance<T>>::remove((collection.id, owner));290 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());291 } else {292 <Balance<T>>::insert((collection.id, owner), balance);293 }294 <TotalSupply<T>>::insert(collection.id, total_supply);295296 <PalletEvm<T>>::deposit_log(297 ERC20Events::Transfer {298 from: *owner.as_eth(),299 to: H160::default(),300 value: amount.into(),301 }302 .to_log(collection_id_to_address(collection.id)),303 );304 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(305 collection.id,306 TokenId::default(),307 owner.clone(),308 amount,309 ));310 Ok(())311 }312313 /// Burns the specified amount of the token.314 pub fn burn_foreign(315 collection: &FungibleHandle<T>,316 owner: &T::CrossAccountId,317 amount: u128,318 ) -> DispatchResult {319 let total_supply = <TotalSupply<T>>::get(collection.id)320 .checked_sub(amount)321 .ok_or(<CommonError<T>>::TokenValueTooLow)?;322323 let balance = <Balance<T>>::get((collection.id, owner))324 .checked_sub(amount)325 .ok_or(<CommonError<T>>::TokenValueTooLow)?;326 // =========327328 if balance == 0 {329 <Balance<T>>::remove((collection.id, owner));330 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());331 } else {332 <Balance<T>>::insert((collection.id, owner), balance);333 }334 <TotalSupply<T>>::insert(collection.id, total_supply);335336 <PalletEvm<T>>::deposit_log(337 ERC20Events::Transfer {338 from: *owner.as_eth(),339 to: H160::default(),340 value: amount.into(),341 }342 .to_log(collection_id_to_address(collection.id)),343 );344 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(345 collection.id,346 TokenId::default(),347 owner.clone(),348 amount,349 ));350 Ok(())351 }352353 /// Transfers the specified amount of tokens. Will check that354 /// the transfer is allowed for the token.355 ///356 /// - `from`: Owner of tokens to transfer.357 /// - `to`: Recepient of transfered tokens.358 /// - `amount`: Amount of tokens to transfer.359 /// - `collection`: Collection that contains the token360 pub fn transfer(361 collection: &FungibleHandle<T>,362 from: &T::CrossAccountId,363 to: &T::CrossAccountId,364 amount: u128,365 nesting_budget: &dyn Budget,366 ) -> DispatchResult {367 ensure!(368 collection.limits.transfers_enabled(),369 <CommonError<T>>::TransferNotAllowed,370 );371372 if collection.permissions.access() == AccessMode::AllowList {373 collection.check_allowlist(from)?;374 collection.check_allowlist(to)?;375 }376 <PalletCommon<T>>::ensure_correct_receiver(to)?;377378 let balance_from = <Balance<T>>::get((collection.id, from))379 .checked_sub(amount)380 .ok_or(<CommonError<T>>::TokenValueTooLow)?;381 let balance_to = if from != to {382 Some(383 <Balance<T>>::get((collection.id, to))384 .checked_add(amount)385 .ok_or(ArithmeticError::Overflow)?,386 )387 } else {388 None389 };390391 // =========392393 <PalletStructure<T>>::nest_if_sent_to_token(394 from.clone(),395 to,396 collection.id,397 TokenId::default(),398 nesting_budget,399 )?;400401 if let Some(balance_to) = balance_to {402 // from != to403 if balance_from == 0 {404 <Balance<T>>::remove((collection.id, from));405 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());406 } else {407 <Balance<T>>::insert((collection.id, from), balance_from);408 }409 <Balance<T>>::insert((collection.id, to), balance_to);410 }411412 <PalletEvm<T>>::deposit_log(413 ERC20Events::Transfer {414 from: *from.as_eth(),415 to: *to.as_eth(),416 value: amount.into(),417 }418 .to_log(collection_id_to_address(collection.id)),419 );420 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(421 collection.id,422 TokenId::default(),423 from.clone(),424 to.clone(),425 amount,426 ));427 Ok(())428 }429430 /// Minting tokens for multiple IDs.431 /// See [`create_item`][`Pallet::create_item`] for more details.432 pub fn create_multiple_items(433 collection: &FungibleHandle<T>,434 sender: &T::CrossAccountId,435 data: BTreeMap<T::CrossAccountId, u128>,436 nesting_budget: &dyn Budget,437 ) -> DispatchResult {438 // Foreign collection check439 ensure!(440 !<ForeignCollection<T>>::get(collection.id),441 <CommonError<T>>::NoPermission442 );443444 if !collection.is_owner_or_admin(sender) {445 ensure!(446 collection.permissions.mint_mode(),447 <CommonError<T>>::PublicMintingNotAllowed448 );449 collection.check_allowlist(sender)?;450451 for (owner, _) in data.iter() {452 collection.check_allowlist(owner)?;453 }454 }455456 let total_supply = data457 .iter()458 .map(|(_, v)| *v)459 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {460 acc.checked_add(v)461 })462 .ok_or(ArithmeticError::Overflow)?;463464 for (to, _) in data.iter() {465 <PalletStructure<T>>::check_nesting(466 sender.clone(),467 to,468 collection.id,469 TokenId::default(),470 nesting_budget,471 )?;472 }473474 let updated_balances = data475 .into_iter()476 .map(|(user, amount)| {477 let updated_balance = <Balance<T>>::get((collection.id, &user))478 .checked_add(amount)479 .ok_or(ArithmeticError::Overflow)?;480 Ok((user, amount, updated_balance))481 })482 .collect::<Result<Vec<_>, DispatchError>>()?;483484 // =========485486 <TotalSupply<T>>::insert(collection.id, total_supply);487 for (user, amount, updated_balance) in updated_balances {488 <Balance<T>>::insert((collection.id, &user), updated_balance);489 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(490 &user,491 collection.id,492 TokenId::default(),493 );494 <PalletEvm<T>>::deposit_log(495 ERC20Events::Transfer {496 from: H160::default(),497 to: *user.as_eth(),498 value: amount.into(),499 }500 .to_log(collection_id_to_address(collection.id)),501 );502 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(503 collection.id,504 TokenId::default(),505 user.clone(),506 amount,507 ));508 }509510 Ok(())511 }512513 /// Minting tokens for multiple IDs.514 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.515 pub fn create_multiple_items_foreign(516 collection: &FungibleHandle<T>,517 sender: &T::CrossAccountId,518 data: BTreeMap<T::CrossAccountId, u128>,519 nesting_budget: &dyn Budget,520 ) -> DispatchResult {521 let total_supply = data522 .iter()523 .map(|(_, v)| *v)524 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {525 acc.checked_add(v)526 })527 .ok_or(ArithmeticError::Overflow)?;528529 let mut balances = data;530 for (k, v) in balances.iter_mut() {531 *v = <Balance<T>>::get((collection.id, &k))532 .checked_add(*v)533 .ok_or(ArithmeticError::Overflow)?;534 }535536 for (to, _) in balances.iter() {537 <PalletStructure<T>>::check_nesting(538 sender.clone(),539 to,540 collection.id,541 TokenId::default(),542 nesting_budget,543 )?;544 }545546 // =========547548 <TotalSupply<T>>::insert(collection.id, total_supply);549 for (user, amount) in balances {550 <Balance<T>>::insert((collection.id, &user), amount);551 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(552 &user,553 collection.id,554 TokenId::default(),555 );556 <PalletEvm<T>>::deposit_log(557 ERC20Events::Transfer {558 from: H160::default(),559 to: *user.as_eth(),560 value: amount.into(),561 }562 .to_log(collection_id_to_address(collection.id)),563 );564 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(565 collection.id,566 TokenId::default(),567 user.clone(),568 amount,569 ));570 }571572 Ok(())573 }574575 fn set_allowance_unchecked(576 collection: &FungibleHandle<T>,577 owner: &T::CrossAccountId,578 spender: &T::CrossAccountId,579 amount: u128,580 ) {581 if amount == 0 {582 <Allowance<T>>::remove((collection.id, owner, spender));583 } else {584 <Allowance<T>>::insert((collection.id, owner, spender), amount);585 }586587 <PalletEvm<T>>::deposit_log(588 ERC20Events::Approval {589 owner: *owner.as_eth(),590 spender: *spender.as_eth(),591 value: amount.into(),592 }593 .to_log(collection_id_to_address(collection.id)),594 );595 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(596 collection.id,597 TokenId(0),598 owner.clone(),599 spender.clone(),600 amount,601 ));602 }603604 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.605 ///606 /// - `collection`: Collection that contains the token607 /// - `owner`: Owner of tokens that sets the allowance.608 /// - `spender`: Recipient of the allowance rights.609 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.610 pub fn set_allowance(611 collection: &FungibleHandle<T>,612 owner: &T::CrossAccountId,613 spender: &T::CrossAccountId,614 amount: u128,615 ) -> DispatchResult {616 if collection.permissions.access() == AccessMode::AllowList {617 collection.check_allowlist(owner)?;618 collection.check_allowlist(spender)?;619 }620621 if <Balance<T>>::get((collection.id, owner)) < amount {622 ensure!(623 collection.ignores_owned_amount(owner),624 <CommonError<T>>::CantApproveMoreThanOwned625 );626 }627628 // =========629630 Self::set_allowance_unchecked(collection, owner, spender, amount);631 Ok(())632 }633634 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.635 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.636 ///637 /// - `collection`: Collection that contains the token.638 /// - `spender`: CrossAccountId who has the allowance rights.639 /// - `from`: The owner of the tokens who sets the allowance.640 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.641 fn check_allowed(642 collection: &FungibleHandle<T>,643 spender: &T::CrossAccountId,644 from: &T::CrossAccountId,645 amount: u128,646 nesting_budget: &dyn Budget,647 ) -> Result<Option<u128>, DispatchError> {648 if spender.conv_eq(from) {649 return Ok(None);650 }651 if collection.permissions.access() == AccessMode::AllowList {652 // `from`, `to` checked in [`transfer`]653 collection.check_allowlist(spender)?;654 }655 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {656 // TODO: should collection owner be allowed to perform this transfer?657 ensure!(658 <PalletStructure<T>>::check_indirectly_owned(659 spender.clone(),660 source.0,661 source.1,662 None,663 nesting_budget664 )?,665 <CommonError<T>>::ApprovedValueTooLow,666 );667 return Ok(None);668 }669 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);670 if allowance.is_none() {671 ensure!(672 collection.ignores_allowance(spender),673 <CommonError<T>>::ApprovedValueTooLow674 );675 }676677 Ok(allowance)678 }679680 /// Transfer fungible tokens from one account to another.681 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.682 /// The owner should set allowance for the spender to transfer pieces.683 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.684685 pub fn transfer_from(686 collection: &FungibleHandle<T>,687 spender: &T::CrossAccountId,688 from: &T::CrossAccountId,689 to: &T::CrossAccountId,690 amount: u128,691 nesting_budget: &dyn Budget,692 ) -> DispatchResult {693 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;694695 // =========696697 Self::transfer(collection, from, to, amount, nesting_budget)?;698 if let Some(allowance) = allowance {699 Self::set_allowance_unchecked(collection, from, spender, allowance);700 }701 Ok(())702 }703704 /// Burn fungible tokens from the account.705 ///706 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should707 /// set allowance for the spender to burn tokens.708 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.709 pub fn burn_from(710 collection: &FungibleHandle<T>,711 spender: &T::CrossAccountId,712 from: &T::CrossAccountId,713 amount: u128,714 nesting_budget: &dyn Budget,715 ) -> DispatchResult {716 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;717718 // =========719720 Self::burn(collection, from, amount)?;721 if let Some(allowance) = allowance {722 Self::set_allowance_unchecked(collection, from, spender, allowance);723 }724 Ok(())725 }726727 /// Creates fungible token.728 ///729 /// The sender should be the owner/admin of the collection or collection should be configured730 /// to allow public minting.731 ///732 /// - `data`: Contains user who will become the owners of the tokens and amount733 /// of tokens he will receive.734 pub fn create_item(735 collection: &FungibleHandle<T>,736 sender: &T::CrossAccountId,737 data: CreateItemData<T>,738 nesting_budget: &dyn Budget,739 ) -> DispatchResult {740 Self::create_multiple_items(741 collection,742 sender,743 [(data.0, data.1)].into_iter().collect(),744 nesting_budget,745 )746 }747748 /// Creates fungible token.749 ///750 /// - `data`: Contains user who will become the owners of the tokens and amount751 /// of tokens he will receive.752 pub fn create_item_foreign(753 collection: &FungibleHandle<T>,754 sender: &T::CrossAccountId,755 data: CreateItemData<T>,756 nesting_budget: &dyn Budget,757 ) -> DispatchResult {758 Self::create_multiple_items_foreign(759 collection,760 sender,761 [(data.0, data.1)].into_iter().collect(),762 nesting_budget,763 )764 }765766 /// Returns 10 tokens owners in no particular order767 ///768 /// There is no direct way to get token holders in ascending order,769 /// since `iter_prefix` returns values in no particular order.770 /// Therefore, getting the 10 largest holders with a large value of holders771 /// can lead to impact memory allocation + sorting with `n * log (n)`.772 pub fn token_owners(773 collection: CollectionId,774 _token: TokenId,775 ) -> Option<Vec<T::CrossAccountId>> {776 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))777 .map(|(owner, _amount)| owner)778 .take(10)779 .collect();780781 if res.is_empty() {782 None783 } else {784 Some(res)785 }786 }787}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//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::{ensure};84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86 AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,87 budget::Budget,88};89use pallet_common::{90 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91 eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115 use up_data_structs::CollectionId;116 use super::weights::WeightInfo;117118 #[pallet::error]119 pub enum Error<T> {120 /// Not Fungible item data used to mint in Fungible collection.121 NotFungibleDataUsedToMintFungibleCollectionToken,122 /// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.123 FungibleItemsHaveNoId,124 /// Tried to set data for fungible item.125 FungibleItemsDontHaveData,126 /// Fungible token does not support nesting.127 FungibleDisallowsNesting,128 /// Setting item properties is not allowed.129 SettingPropertiesNotAllowed,130 }131132 #[pallet::config]133 pub trait Config:134 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config135 {136 type WeightInfo: WeightInfo;137 }138139 #[pallet::pallet]140 #[pallet::generate_store(pub(super) trait Store)]141 pub struct Pallet<T>(_);142143 /// Total amount of fungible tokens inside a collection.144 #[pallet::storage]145 pub type TotalSupply<T: Config> =146 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;147148 /// Amount of tokens owned by an account inside a collection.149 #[pallet::storage]150 pub type Balance<T: Config> = StorageNMap<151 Key = (152 Key<Twox64Concat, CollectionId>,153 Key<Blake2_128Concat, T::CrossAccountId>,154 ),155 Value = u128,156 QueryKind = ValueQuery,157 >;158159 /// Storage for assets delegated to a limited extent to other users.160 #[pallet::storage]161 pub type Allowance<T: Config> = StorageNMap<162 Key = (163 Key<Twox64Concat, CollectionId>,164 Key<Blake2_128, T::CrossAccountId>,165 Key<Blake2_128Concat, T::CrossAccountId>,166 ),167 Value = u128,168 QueryKind = ValueQuery,169 >;170171 /// Foreign collection flag172 #[pallet::storage]173 pub type ForeignCollection<T: Config> =174 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = bool, QueryKind = ValueQuery>;175}176177/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.178/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].179pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);180181/// Implementation of methods required for dispatching during runtime.182impl<T: Config> FungibleHandle<T> {183 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].184 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {185 Self(inner)186 }187188 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].189 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {190 self.0191 }192 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].193 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {194 &mut self.0195 }196}197impl<T: Config> WithRecorder<T> for FungibleHandle<T> {198 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {199 self.0.recorder()200 }201 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {202 self.0.into_recorder()203 }204}205impl<T: Config> Deref for FungibleHandle<T> {206 type Target = pallet_common::CollectionHandle<T>;207208 fn deref(&self) -> &Self::Target {209 &self.0210 }211}212213/// Pallet implementation for fungible assets214impl<T: Config> Pallet<T> {215 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.216 pub fn init_collection(217 owner: T::CrossAccountId,218 data: CreateCollectionData<T::AccountId>,219 ) -> Result<CollectionId, DispatchError> {220 <PalletCommon<T>>::init_collection(owner, data, false)221 }222223 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.224 pub fn init_foreign_collection(225 owner: T::CrossAccountId,226 data: CreateCollectionData<T::AccountId>,227 ) -> Result<CollectionId, DispatchError> {228 let id = <PalletCommon<T>>::init_collection(owner, data, false)?;229 <ForeignCollection<T>>::insert(id, true);230 Ok(id)231 }232233 /// Destroys a collection.234 pub fn destroy_collection(235 collection: FungibleHandle<T>,236 sender: &T::CrossAccountId,237 ) -> DispatchResult {238 let id = collection.id;239240 if Self::collection_has_tokens(id) {241 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());242 }243244 // =========245246 PalletCommon::destroy_collection(collection.0, sender)?;247248 <ForeignCollection<T>>::remove(id);249 <TotalSupply<T>>::remove(id);250 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);251 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);252 Ok(())253 }254255 ///Checks if collection has tokens. Return `true` if it has.256 fn collection_has_tokens(collection_id: CollectionId) -> bool {257 <TotalSupply<T>>::get(collection_id) != 0258 }259260 /// Burns the specified amount of the token. If the token balance261 /// or total supply is less than the given value,262 /// it will return [DispatchError].263 pub fn burn(264 collection: &FungibleHandle<T>,265 owner: &T::CrossAccountId,266 amount: u128,267 ) -> DispatchResult {268 let total_supply = <TotalSupply<T>>::get(collection.id)269 .checked_sub(amount)270 .ok_or(<CommonError<T>>::TokenValueTooLow)?;271272 let balance = <Balance<T>>::get((collection.id, owner))273 .checked_sub(amount)274 .ok_or(<CommonError<T>>::TokenValueTooLow)?;275276 // Foreign collection check277 ensure!(278 !<ForeignCollection<T>>::get(collection.id),279 <CommonError<T>>::NoPermission280 );281282 if collection.permissions.access() == AccessMode::AllowList {283 collection.check_allowlist(owner)?;284 }285286 // =========287288 if balance == 0 {289 <Balance<T>>::remove((collection.id, owner));290 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());291 } else {292 <Balance<T>>::insert((collection.id, owner), balance);293 }294 <TotalSupply<T>>::insert(collection.id, total_supply);295296 <PalletEvm<T>>::deposit_log(297 ERC20Events::Transfer {298 from: *owner.as_eth(),299 to: H160::default(),300 value: amount.into(),301 }302 .to_log(collection_id_to_address(collection.id)),303 );304 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(305 collection.id,306 TokenId::default(),307 owner.clone(),308 amount,309 ));310 Ok(())311 }312313 /// Burns the specified amount of the token.314 pub fn burn_foreign(315 collection: &FungibleHandle<T>,316 owner: &T::CrossAccountId,317 amount: u128,318 ) -> DispatchResult {319 let total_supply = <TotalSupply<T>>::get(collection.id)320 .checked_sub(amount)321 .ok_or(<CommonError<T>>::TokenValueTooLow)?;322323 let balance = <Balance<T>>::get((collection.id, owner))324 .checked_sub(amount)325 .ok_or(<CommonError<T>>::TokenValueTooLow)?;326 // =========327328 if balance == 0 {329 <Balance<T>>::remove((collection.id, owner));330 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());331 } else {332 <Balance<T>>::insert((collection.id, owner), balance);333 }334 <TotalSupply<T>>::insert(collection.id, total_supply);335336 <PalletEvm<T>>::deposit_log(337 ERC20Events::Transfer {338 from: *owner.as_eth(),339 to: H160::default(),340 value: amount.into(),341 }342 .to_log(collection_id_to_address(collection.id)),343 );344 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(345 collection.id,346 TokenId::default(),347 owner.clone(),348 amount,349 ));350 Ok(())351 }352353 /// Transfers the specified amount of tokens. Will check that354 /// the transfer is allowed for the token.355 ///356 /// - `from`: Owner of tokens to transfer.357 /// - `to`: Recepient of transfered tokens.358 /// - `amount`: Amount of tokens to transfer.359 /// - `collection`: Collection that contains the token360 pub fn transfer(361 collection: &FungibleHandle<T>,362 from: &T::CrossAccountId,363 to: &T::CrossAccountId,364 amount: u128,365 nesting_budget: &dyn Budget,366 ) -> DispatchResult {367 ensure!(368 collection.limits.transfers_enabled(),369 <CommonError<T>>::TransferNotAllowed,370 );371372 if collection.permissions.access() == AccessMode::AllowList {373 collection.check_allowlist(from)?;374 collection.check_allowlist(to)?;375 }376 <PalletCommon<T>>::ensure_correct_receiver(to)?;377378 let balance_from = <Balance<T>>::get((collection.id, from))379 .checked_sub(amount)380 .ok_or(<CommonError<T>>::TokenValueTooLow)?;381 let balance_to = if from != to {382 Some(383 <Balance<T>>::get((collection.id, to))384 .checked_add(amount)385 .ok_or(ArithmeticError::Overflow)?,386 )387 } else {388 None389 };390391 // =========392393 <PalletStructure<T>>::nest_if_sent_to_token(394 from.clone(),395 to,396 collection.id,397 TokenId::default(),398 nesting_budget,399 )?;400401 if let Some(balance_to) = balance_to {402 // from != to403 if balance_from == 0 {404 <Balance<T>>::remove((collection.id, from));405 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());406 } else {407 <Balance<T>>::insert((collection.id, from), balance_from);408 }409 <Balance<T>>::insert((collection.id, to), balance_to);410 }411412 <PalletEvm<T>>::deposit_log(413 ERC20Events::Transfer {414 from: *from.as_eth(),415 to: *to.as_eth(),416 value: amount.into(),417 }418 .to_log(collection_id_to_address(collection.id)),419 );420 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(421 collection.id,422 TokenId::default(),423 from.clone(),424 to.clone(),425 amount,426 ));427 Ok(())428 }429430 /// Minting tokens for multiple IDs.431 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]432 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]433 pub fn create_multiple_items_common(434 collection: &FungibleHandle<T>,435 sender: &T::CrossAccountId,436 data: BTreeMap<T::CrossAccountId, u128>,437 nesting_budget: &dyn Budget,438 ) -> DispatchResult {439 let total_supply = data440 .iter()441 .map(|(_, v)| *v)442 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {443 acc.checked_add(v)444 })445 .ok_or(ArithmeticError::Overflow)?;446447 for (to, _) in data.iter() {448 <PalletStructure<T>>::check_nesting(449 sender.clone(),450 to,451 collection.id,452 TokenId::default(),453 nesting_budget,454 )?;455 }456457 let updated_balances = data458 .into_iter()459 .map(|(user, amount)| {460 let updated_balance = <Balance<T>>::get((collection.id, &user))461 .checked_add(amount)462 .ok_or(ArithmeticError::Overflow)?;463 Ok((user, amount, updated_balance))464 })465 .collect::<Result<Vec<_>, DispatchError>>()?;466467 // =========468469 <TotalSupply<T>>::insert(collection.id, total_supply);470 for (user, amount, updated_balance) in updated_balances {471 <Balance<T>>::insert((collection.id, &user), updated_balance);472 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(473 &user,474 collection.id,475 TokenId::default(),476 );477 <PalletEvm<T>>::deposit_log(478 ERC20Events::Transfer {479 from: H160::default(),480 to: *user.as_eth(),481 value: amount.into(),482 }483 .to_log(collection_id_to_address(collection.id)),484 );485 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(486 collection.id,487 TokenId::default(),488 user.clone(),489 amount,490 ));491 }492493 Ok(())494 }495496 /// Minting tokens for multiple IDs.497 /// See [`create_item`][`Pallet::create_item`] for more details.498 pub fn create_multiple_items(499 collection: &FungibleHandle<T>,500 sender: &T::CrossAccountId,501 data: BTreeMap<T::CrossAccountId, u128>,502 nesting_budget: &dyn Budget,503 ) -> DispatchResult {504 // Foreign collection check505 ensure!(506 !<ForeignCollection<T>>::get(collection.id),507 <CommonError<T>>::NoPermission508 );509510 if !collection.is_owner_or_admin(sender) {511 ensure!(512 collection.permissions.mint_mode(),513 <CommonError<T>>::PublicMintingNotAllowed514 );515 collection.check_allowlist(sender)?;516517 for (owner, _) in data.iter() {518 collection.check_allowlist(owner)?;519 }520 }521522 Self::create_multiple_items_common(523 collection,524 sender,525 data,526 nesting_budget,527 )528 }529530 /// Minting tokens for multiple IDs.531 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.532 pub fn create_multiple_items_foreign(533 collection: &FungibleHandle<T>,534 sender: &T::CrossAccountId,535 data: BTreeMap<T::CrossAccountId, u128>,536 nesting_budget: &dyn Budget,537 ) -> DispatchResult {538 Self::create_multiple_items_common(539 collection,540 sender,541 data,542 nesting_budget,543 )544 }545546 fn set_allowance_unchecked(547 collection: &FungibleHandle<T>,548 owner: &T::CrossAccountId,549 spender: &T::CrossAccountId,550 amount: u128,551 ) {552 if amount == 0 {553 <Allowance<T>>::remove((collection.id, owner, spender));554 } else {555 <Allowance<T>>::insert((collection.id, owner, spender), amount);556 }557558 <PalletEvm<T>>::deposit_log(559 ERC20Events::Approval {560 owner: *owner.as_eth(),561 spender: *spender.as_eth(),562 value: amount.into(),563 }564 .to_log(collection_id_to_address(collection.id)),565 );566 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(567 collection.id,568 TokenId(0),569 owner.clone(),570 spender.clone(),571 amount,572 ));573 }574575 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.576 ///577 /// - `collection`: Collection that contains the token578 /// - `owner`: Owner of tokens that sets the allowance.579 /// - `spender`: Recipient of the allowance rights.580 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.581 pub fn set_allowance(582 collection: &FungibleHandle<T>,583 owner: &T::CrossAccountId,584 spender: &T::CrossAccountId,585 amount: u128,586 ) -> DispatchResult {587 if collection.permissions.access() == AccessMode::AllowList {588 collection.check_allowlist(owner)?;589 collection.check_allowlist(spender)?;590 }591592 if <Balance<T>>::get((collection.id, owner)) < amount {593 ensure!(594 collection.ignores_owned_amount(owner),595 <CommonError<T>>::CantApproveMoreThanOwned596 );597 }598599 // =========600601 Self::set_allowance_unchecked(collection, owner, spender, amount);602 Ok(())603 }604605 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.606 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.607 ///608 /// - `collection`: Collection that contains the token.609 /// - `spender`: CrossAccountId who has the allowance rights.610 /// - `from`: The owner of the tokens who sets the allowance.611 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.612 fn check_allowed(613 collection: &FungibleHandle<T>,614 spender: &T::CrossAccountId,615 from: &T::CrossAccountId,616 amount: u128,617 nesting_budget: &dyn Budget,618 ) -> Result<Option<u128>, DispatchError> {619 if spender.conv_eq(from) {620 return Ok(None);621 }622 if collection.permissions.access() == AccessMode::AllowList {623 // `from`, `to` checked in [`transfer`]624 collection.check_allowlist(spender)?;625 }626 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {627 // TODO: should collection owner be allowed to perform this transfer?628 ensure!(629 <PalletStructure<T>>::check_indirectly_owned(630 spender.clone(),631 source.0,632 source.1,633 None,634 nesting_budget635 )?,636 <CommonError<T>>::ApprovedValueTooLow,637 );638 return Ok(None);639 }640 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);641 if allowance.is_none() {642 ensure!(643 collection.ignores_allowance(spender),644 <CommonError<T>>::ApprovedValueTooLow645 );646 }647648 Ok(allowance)649 }650651 /// Transfer fungible tokens from one account to another.652 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.653 /// The owner should set allowance for the spender to transfer pieces.654 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.655656 pub fn transfer_from(657 collection: &FungibleHandle<T>,658 spender: &T::CrossAccountId,659 from: &T::CrossAccountId,660 to: &T::CrossAccountId,661 amount: u128,662 nesting_budget: &dyn Budget,663 ) -> DispatchResult {664 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;665666 // =========667668 Self::transfer(collection, from, to, amount, nesting_budget)?;669 if let Some(allowance) = allowance {670 Self::set_allowance_unchecked(collection, from, spender, allowance);671 }672 Ok(())673 }674675 /// Burn fungible tokens from the account.676 ///677 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should678 /// set allowance for the spender to burn tokens.679 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.680 pub fn burn_from(681 collection: &FungibleHandle<T>,682 spender: &T::CrossAccountId,683 from: &T::CrossAccountId,684 amount: u128,685 nesting_budget: &dyn Budget,686 ) -> DispatchResult {687 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;688689 // =========690691 Self::burn(collection, from, amount)?;692 if let Some(allowance) = allowance {693 Self::set_allowance_unchecked(collection, from, spender, allowance);694 }695 Ok(())696 }697698 /// Creates fungible token.699 ///700 /// The sender should be the owner/admin of the collection or collection should be configured701 /// to allow public minting.702 ///703 /// - `data`: Contains user who will become the owners of the tokens and amount704 /// of tokens he will receive.705 pub fn create_item(706 collection: &FungibleHandle<T>,707 sender: &T::CrossAccountId,708 data: CreateItemData<T>,709 nesting_budget: &dyn Budget,710 ) -> DispatchResult {711 Self::create_multiple_items(712 collection,713 sender,714 [(data.0, data.1)].into_iter().collect(),715 nesting_budget,716 )717 }718719 /// Creates fungible token.720 ///721 /// - `data`: Contains user who will become the owners of the tokens and amount722 /// of tokens he will receive.723 pub fn create_item_foreign(724 collection: &FungibleHandle<T>,725 sender: &T::CrossAccountId,726 data: CreateItemData<T>,727 nesting_budget: &dyn Budget,728 ) -> DispatchResult {729 Self::create_multiple_items_foreign(730 collection,731 sender,732 [(data.0, data.1)].into_iter().collect(),733 nesting_budget,734 )735 }736737 /// Returns 10 tokens owners in no particular order738 ///739 /// There is no direct way to get token holders in ascending order,740 /// since `iter_prefix` returns values in no particular order.741 /// Therefore, getting the 10 largest holders with a large value of holders742 /// can lead to impact memory allocation + sorting with `n * log (n)`.743 pub fn token_owners(744 collection: CollectionId,745 _token: TokenId,746 ) -> Option<Vec<T::CrossAccountId>> {747 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))748 .map(|(owner, _amount)| owner)749 .take(10)750 .collect();751752 if res.is_empty() {753 None754 } else {755 Some(res)756 }757 }758}