difftreelog
fieat: add repair_item extrinsic + test
in: master
15 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1815,6 +1815,9 @@
/// The price of setting approval for all
fn set_allowance_for_all() -> Weight;
+
+ /// The price of repairing an item.
+ fn repair_item() -> Weight;
}
/// Weight info extension trait for refungible pallet.
@@ -2136,6 +2139,9 @@
/// Tells whether the given `owner` approves the `operator`.
fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;
+
+ /// Repairs a possibly broken item.
+ fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;
}
/// Extension for RFT collection.
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -111,6 +111,10 @@
fn set_allowance_for_all() -> Weight {
Weight::zero()
}
+
+ fn repair_item() -> Weight {
+ Weight::zero()
+ }
}
/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete
@@ -441,4 +445,9 @@
fn allowance_for_all(&self, _owner: T::CrossAccountId, _operator: T::CrossAccountId) -> bool {
false
}
+
+ /// Repairs a possibly broken item.
+ fn repair_item(&self, _token: TokenId) -> DispatchResultWithPostInfo {
+ fail!(<Error<T>>::FungibleTokensAreAlwaysValid)
+ }
}
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, CollectionFlags, TokenId, CreateCollectionData,87 mapping::TokenAddressMapping, 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::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 /// Setting allowance for all is not allowed.131 SettingAllowanceForAllNotAllowed,132 }133134 #[pallet::config]135 pub trait Config:136 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config137 {138 type WeightInfo: WeightInfo;139 }140141 #[pallet::pallet]142 #[pallet::generate_store(pub(super) trait Store)]143 pub struct Pallet<T>(_);144145 /// Total amount of fungible tokens inside a collection.146 #[pallet::storage]147 pub type TotalSupply<T: Config> =148 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;149150 /// Amount of tokens owned by an account inside a collection.151 #[pallet::storage]152 pub type Balance<T: Config> = StorageNMap<153 Key = (154 Key<Twox64Concat, CollectionId>,155 Key<Blake2_128Concat, T::CrossAccountId>,156 ),157 Value = u128,158 QueryKind = ValueQuery,159 >;160161 /// Storage for assets delegated to a limited extent to other users.162 #[pallet::storage]163 pub type Allowance<T: Config> = StorageNMap<164 Key = (165 Key<Twox64Concat, CollectionId>,166 Key<Blake2_128, T::CrossAccountId>,167 Key<Blake2_128Concat, T::CrossAccountId>,168 ),169 Value = u128,170 QueryKind = ValueQuery,171 >;172}173174/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.175/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].176pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);177178/// Implementation of methods required for dispatching during runtime.179impl<T: Config> FungibleHandle<T> {180 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].181 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {182 Self(inner)183 }184185 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].186 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {187 self.0188 }189 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].190 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {191 &mut self.0192 }193}194impl<T: Config> WithRecorder<T> for FungibleHandle<T> {195 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {196 self.0.recorder()197 }198 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {199 self.0.into_recorder()200 }201}202impl<T: Config> Deref for FungibleHandle<T> {203 type Target = pallet_common::CollectionHandle<T>;204205 fn deref(&self) -> &Self::Target {206 &self.0207 }208}209210/// Pallet implementation for fungible assets211impl<T: Config> Pallet<T> {212 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.213 pub fn init_collection(214 owner: T::CrossAccountId,215 payer: T::CrossAccountId,216 data: CreateCollectionData<T::AccountId>,217 flags: CollectionFlags,218 ) -> Result<CollectionId, DispatchError> {219 <PalletCommon<T>>::init_collection(owner, payer, data, flags)220 }221222 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.223 pub fn init_foreign_collection(224 owner: T::CrossAccountId,225 payer: T::CrossAccountId,226 data: CreateCollectionData<T::AccountId>,227 ) -> Result<CollectionId, DispatchError> {228 let id = <PalletCommon<T>>::init_collection(229 owner,230 payer,231 data,232 CollectionFlags {233 foreign: true,234 ..Default::default()235 },236 )?;237 Ok(id)238 }239240 /// Destroys a collection.241 pub fn destroy_collection(242 collection: FungibleHandle<T>,243 sender: &T::CrossAccountId,244 ) -> DispatchResult {245 let id = collection.id;246247 if Self::collection_has_tokens(id) {248 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());249 }250251 // =========252253 PalletCommon::destroy_collection(collection.0, sender)?;254255 <TotalSupply<T>>::remove(id);256 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);257 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);258 Ok(())259 }260261 ///Checks if collection has tokens. Return `true` if it has.262 fn collection_has_tokens(collection_id: CollectionId) -> bool {263 <TotalSupply<T>>::get(collection_id) != 0264 }265266 /// Burns the specified amount of the token. If the token balance267 /// or total supply is less than the given value,268 /// it will return [DispatchError].269 pub fn burn(270 collection: &FungibleHandle<T>,271 owner: &T::CrossAccountId,272 amount: u128,273 ) -> DispatchResult {274 let total_supply = <TotalSupply<T>>::get(collection.id)275 .checked_sub(amount)276 .ok_or(<CommonError<T>>::TokenValueTooLow)?;277278 let balance = <Balance<T>>::get((collection.id, owner))279 .checked_sub(amount)280 .ok_or(<CommonError<T>>::TokenValueTooLow)?;281282 // Foreign collection check283 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);284285 if collection.permissions.access() == AccessMode::AllowList {286 collection.check_allowlist(owner)?;287 }288289 // =========290291 if balance == 0 {292 <Balance<T>>::remove((collection.id, owner));293 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());294 } else {295 <Balance<T>>::insert((collection.id, owner), balance);296 }297 <TotalSupply<T>>::insert(collection.id, total_supply);298299 <PalletEvm<T>>::deposit_log(300 ERC20Events::Transfer {301 from: *owner.as_eth(),302 to: H160::default(),303 value: amount.into(),304 }305 .to_log(collection_id_to_address(collection.id)),306 );307 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(308 collection.id,309 TokenId::default(),310 owner.clone(),311 amount,312 ));313 Ok(())314 }315316 /// Burns the specified amount of the token.317 pub fn burn_foreign(318 collection: &FungibleHandle<T>,319 owner: &T::CrossAccountId,320 amount: u128,321 ) -> DispatchResult {322 let total_supply = <TotalSupply<T>>::get(collection.id)323 .checked_sub(amount)324 .ok_or(<CommonError<T>>::TokenValueTooLow)?;325326 let balance = <Balance<T>>::get((collection.id, owner))327 .checked_sub(amount)328 .ok_or(<CommonError<T>>::TokenValueTooLow)?;329 // =========330331 if balance == 0 {332 <Balance<T>>::remove((collection.id, owner));333 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());334 } else {335 <Balance<T>>::insert((collection.id, owner), balance);336 }337 <TotalSupply<T>>::insert(collection.id, total_supply);338339 <PalletEvm<T>>::deposit_log(340 ERC20Events::Transfer {341 from: *owner.as_eth(),342 to: H160::default(),343 value: amount.into(),344 }345 .to_log(collection_id_to_address(collection.id)),346 );347 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(348 collection.id,349 TokenId::default(),350 owner.clone(),351 amount,352 ));353 Ok(())354 }355356 /// Transfers the specified amount of tokens. Will check that357 /// the transfer is allowed for the token.358 ///359 /// - `from`: Owner of tokens to transfer.360 /// - `to`: Recepient of transfered tokens.361 /// - `amount`: Amount of tokens to transfer.362 /// - `collection`: Collection that contains the token363 pub fn transfer(364 collection: &FungibleHandle<T>,365 from: &T::CrossAccountId,366 to: &T::CrossAccountId,367 amount: u128,368 nesting_budget: &dyn Budget,369 ) -> DispatchResult {370 ensure!(371 collection.limits.transfers_enabled(),372 <CommonError<T>>::TransferNotAllowed,373 );374375 if collection.permissions.access() == AccessMode::AllowList {376 collection.check_allowlist(from)?;377 collection.check_allowlist(to)?;378 }379 <PalletCommon<T>>::ensure_correct_receiver(to)?;380381 let balance_from = <Balance<T>>::get((collection.id, from))382 .checked_sub(amount)383 .ok_or(<CommonError<T>>::TokenValueTooLow)?;384 let balance_to = if from != to && amount != 0 {385 Some(386 <Balance<T>>::get((collection.id, to))387 .checked_add(amount)388 .ok_or(ArithmeticError::Overflow)?,389 )390 } else {391 None392 };393394 // =========395396 if let Some(balance_to) = balance_to {397 // from != to && amount != 0398399 <PalletStructure<T>>::nest_if_sent_to_token(400 from.clone(),401 to,402 collection.id,403 TokenId::default(),404 nesting_budget,405 )?;406407 if balance_from == 0 {408 <Balance<T>>::remove((collection.id, from));409 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());410 } else {411 <Balance<T>>::insert((collection.id, from), balance_from);412 }413 <Balance<T>>::insert((collection.id, to), balance_to);414 }415416 <PalletEvm<T>>::deposit_log(417 ERC20Events::Transfer {418 from: *from.as_eth(),419 to: *to.as_eth(),420 value: amount.into(),421 }422 .to_log(collection_id_to_address(collection.id)),423 );424 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(425 collection.id,426 TokenId::default(),427 from.clone(),428 to.clone(),429 amount,430 ));431 Ok(())432 }433434 /// Minting tokens for multiple IDs.435 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]436 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]437 pub fn create_multiple_items_common(438 collection: &FungibleHandle<T>,439 sender: &T::CrossAccountId,440 data: BTreeMap<T::CrossAccountId, u128>,441 nesting_budget: &dyn Budget,442 ) -> DispatchResult {443 let total_supply = data444 .iter()445 .map(|(_, v)| *v)446 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {447 acc.checked_add(v)448 })449 .ok_or(ArithmeticError::Overflow)?;450451 for (to, _) in data.iter() {452 <PalletStructure<T>>::check_nesting(453 sender.clone(),454 to,455 collection.id,456 TokenId::default(),457 nesting_budget,458 )?;459 }460461 let updated_balances = data462 .into_iter()463 .map(|(user, amount)| {464 let updated_balance = <Balance<T>>::get((collection.id, &user))465 .checked_add(amount)466 .ok_or(ArithmeticError::Overflow)?;467 Ok((user, amount, updated_balance))468 })469 .collect::<Result<Vec<_>, DispatchError>>()?;470471 // =========472473 <TotalSupply<T>>::insert(collection.id, total_supply);474 for (user, amount, updated_balance) in updated_balances {475 <Balance<T>>::insert((collection.id, &user), updated_balance);476 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(477 &user,478 collection.id,479 TokenId::default(),480 );481 <PalletEvm<T>>::deposit_log(482 ERC20Events::Transfer {483 from: H160::default(),484 to: *user.as_eth(),485 value: amount.into(),486 }487 .to_log(collection_id_to_address(collection.id)),488 );489 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(490 collection.id,491 TokenId::default(),492 user.clone(),493 amount,494 ));495 }496497 Ok(())498 }499500 /// Minting tokens for multiple IDs.501 /// See [`create_item`][`Pallet::create_item`] for more details.502 pub fn create_multiple_items(503 collection: &FungibleHandle<T>,504 sender: &T::CrossAccountId,505 data: BTreeMap<T::CrossAccountId, u128>,506 nesting_budget: &dyn Budget,507 ) -> DispatchResult {508 // Foreign collection check509 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);510511 if !collection.is_owner_or_admin(sender) {512 ensure!(513 collection.permissions.mint_mode(),514 <CommonError<T>>::PublicMintingNotAllowed515 );516 collection.check_allowlist(sender)?;517518 for (owner, _) in data.iter() {519 collection.check_allowlist(owner)?;520 }521 }522523 Self::create_multiple_items_common(collection, sender, data, nesting_budget)524 }525526 /// Minting tokens for multiple IDs.527 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.528 pub fn create_multiple_items_foreign(529 collection: &FungibleHandle<T>,530 sender: &T::CrossAccountId,531 data: BTreeMap<T::CrossAccountId, u128>,532 nesting_budget: &dyn Budget,533 ) -> DispatchResult {534 Self::create_multiple_items_common(collection, sender, data, nesting_budget)535 }536537 fn set_allowance_unchecked(538 collection: &FungibleHandle<T>,539 owner: &T::CrossAccountId,540 spender: &T::CrossAccountId,541 amount: u128,542 ) {543 if amount == 0 {544 <Allowance<T>>::remove((collection.id, owner, spender));545 } else {546 <Allowance<T>>::insert((collection.id, owner, spender), amount);547 }548549 <PalletEvm<T>>::deposit_log(550 ERC20Events::Approval {551 owner: *owner.as_eth(),552 spender: *spender.as_eth(),553 value: amount.into(),554 }555 .to_log(collection_id_to_address(collection.id)),556 );557 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(558 collection.id,559 TokenId(0),560 owner.clone(),561 spender.clone(),562 amount,563 ));564 }565566 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.567 ///568 /// - `collection`: Collection that contains the token569 /// - `owner`: Owner of tokens that sets the allowance.570 /// - `spender`: Recipient of the allowance rights.571 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.572 pub fn set_allowance(573 collection: &FungibleHandle<T>,574 owner: &T::CrossAccountId,575 spender: &T::CrossAccountId,576 amount: u128,577 ) -> DispatchResult {578 if collection.permissions.access() == AccessMode::AllowList {579 collection.check_allowlist(owner)?;580 collection.check_allowlist(spender)?;581 }582583 if <Balance<T>>::get((collection.id, owner)) < amount {584 ensure!(585 collection.ignores_owned_amount(owner),586 <CommonError<T>>::CantApproveMoreThanOwned587 );588 }589590 // =========591592 Self::set_allowance_unchecked(collection, owner, spender, amount);593 Ok(())594 }595596 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.597 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.598 ///599 /// - `collection`: Collection that contains the token.600 /// - `spender`: CrossAccountId who has the allowance rights.601 /// - `from`: The owner of the tokens who sets the allowance.602 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.603 fn check_allowed(604 collection: &FungibleHandle<T>,605 spender: &T::CrossAccountId,606 from: &T::CrossAccountId,607 amount: u128,608 nesting_budget: &dyn Budget,609 ) -> Result<Option<u128>, DispatchError> {610 if spender.conv_eq(from) {611 return Ok(None);612 }613 if collection.permissions.access() == AccessMode::AllowList {614 // `from`, `to` checked in [`transfer`]615 collection.check_allowlist(spender)?;616 }617 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {618 // TODO: should collection owner be allowed to perform this transfer?619 ensure!(620 <PalletStructure<T>>::check_indirectly_owned(621 spender.clone(),622 source.0,623 source.1,624 None,625 nesting_budget626 )?,627 <CommonError<T>>::ApprovedValueTooLow,628 );629 return Ok(None);630 }631 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);632 if allowance.is_none() {633 ensure!(634 collection.ignores_allowance(spender),635 <CommonError<T>>::ApprovedValueTooLow636 );637 }638639 Ok(allowance)640 }641642 /// Transfer fungible tokens from one account to another.643 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.644 /// The owner should set allowance for the spender to transfer pieces.645 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.646647 pub fn transfer_from(648 collection: &FungibleHandle<T>,649 spender: &T::CrossAccountId,650 from: &T::CrossAccountId,651 to: &T::CrossAccountId,652 amount: u128,653 nesting_budget: &dyn Budget,654 ) -> DispatchResult {655 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;656657 // =========658659 Self::transfer(collection, from, to, amount, nesting_budget)?;660 if let Some(allowance) = allowance {661 Self::set_allowance_unchecked(collection, from, spender, allowance);662 }663 Ok(())664 }665666 /// Burn fungible tokens from the account.667 ///668 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should669 /// set allowance for the spender to burn tokens.670 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.671 pub fn burn_from(672 collection: &FungibleHandle<T>,673 spender: &T::CrossAccountId,674 from: &T::CrossAccountId,675 amount: u128,676 nesting_budget: &dyn Budget,677 ) -> DispatchResult {678 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;679680 // =========681682 Self::burn(collection, from, amount)?;683 if let Some(allowance) = allowance {684 Self::set_allowance_unchecked(collection, from, spender, allowance);685 }686 Ok(())687 }688689 /// Creates fungible token.690 ///691 /// The sender should be the owner/admin of the collection or collection should be configured692 /// to allow public minting.693 ///694 /// - `data`: Contains user who will become the owners of the tokens and amount695 /// of tokens he will receive.696 pub fn create_item(697 collection: &FungibleHandle<T>,698 sender: &T::CrossAccountId,699 data: CreateItemData<T>,700 nesting_budget: &dyn Budget,701 ) -> DispatchResult {702 Self::create_multiple_items(703 collection,704 sender,705 [(data.0, data.1)].into_iter().collect(),706 nesting_budget,707 )708 }709710 /// Creates fungible token.711 ///712 /// - `data`: Contains user who will become the owners of the tokens and amount713 /// of tokens he will receive.714 pub fn create_item_foreign(715 collection: &FungibleHandle<T>,716 sender: &T::CrossAccountId,717 data: CreateItemData<T>,718 nesting_budget: &dyn Budget,719 ) -> DispatchResult {720 Self::create_multiple_items_foreign(721 collection,722 sender,723 [(data.0, data.1)].into_iter().collect(),724 nesting_budget,725 )726 }727728 /// Returns 10 tokens owners in no particular order729 ///730 /// There is no direct way to get token holders in ascending order,731 /// since `iter_prefix` returns values in no particular order.732 /// Therefore, getting the 10 largest holders with a large value of holders733 /// can lead to impact memory allocation + sorting with `n * log (n)`.734 pub fn token_owners(735 collection: CollectionId,736 _token: TokenId,737 ) -> Option<Vec<T::CrossAccountId>> {738 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))739 .map(|(owner, _amount)| owner)740 .take(10)741 .collect();742743 if res.is_empty() {744 None745 } else {746 Some(res)747 }748 }749}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, CollectionFlags, TokenId, CreateCollectionData,87 mapping::TokenAddressMapping, 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::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 /// Setting allowance for all is not allowed.131 SettingAllowanceForAllNotAllowed,132 /// Only a fungible collection could be possibly broken; any fungible token is valid.133 FungibleTokensAreAlwaysValid,134 }135136 #[pallet::config]137 pub trait Config:138 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config139 {140 type WeightInfo: WeightInfo;141 }142143 #[pallet::pallet]144 #[pallet::generate_store(pub(super) trait Store)]145 pub struct Pallet<T>(_);146147 /// Total amount of fungible tokens inside a collection.148 #[pallet::storage]149 pub type TotalSupply<T: Config> =150 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;151152 /// Amount of tokens owned by an account inside a collection.153 #[pallet::storage]154 pub type Balance<T: Config> = StorageNMap<155 Key = (156 Key<Twox64Concat, CollectionId>,157 Key<Blake2_128Concat, T::CrossAccountId>,158 ),159 Value = u128,160 QueryKind = ValueQuery,161 >;162163 /// Storage for assets delegated to a limited extent to other users.164 #[pallet::storage]165 pub type Allowance<T: Config> = StorageNMap<166 Key = (167 Key<Twox64Concat, CollectionId>,168 Key<Blake2_128, T::CrossAccountId>,169 Key<Blake2_128Concat, T::CrossAccountId>,170 ),171 Value = u128,172 QueryKind = ValueQuery,173 >;174}175176/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.177/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].178pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);179180/// Implementation of methods required for dispatching during runtime.181impl<T: Config> FungibleHandle<T> {182 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].183 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {184 Self(inner)185 }186187 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].188 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {189 self.0190 }191 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].192 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {193 &mut self.0194 }195}196impl<T: Config> WithRecorder<T> for FungibleHandle<T> {197 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {198 self.0.recorder()199 }200 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {201 self.0.into_recorder()202 }203}204impl<T: Config> Deref for FungibleHandle<T> {205 type Target = pallet_common::CollectionHandle<T>;206207 fn deref(&self) -> &Self::Target {208 &self.0209 }210}211212/// Pallet implementation for fungible assets213impl<T: Config> Pallet<T> {214 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.215 pub fn init_collection(216 owner: T::CrossAccountId,217 payer: T::CrossAccountId,218 data: CreateCollectionData<T::AccountId>,219 flags: CollectionFlags,220 ) -> Result<CollectionId, DispatchError> {221 <PalletCommon<T>>::init_collection(owner, payer, data, flags)222 }223224 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.225 pub fn init_foreign_collection(226 owner: T::CrossAccountId,227 payer: T::CrossAccountId,228 data: CreateCollectionData<T::AccountId>,229 ) -> Result<CollectionId, DispatchError> {230 let id = <PalletCommon<T>>::init_collection(231 owner,232 payer,233 data,234 CollectionFlags {235 foreign: true,236 ..Default::default()237 },238 )?;239 Ok(id)240 }241242 /// Destroys a collection.243 pub fn destroy_collection(244 collection: FungibleHandle<T>,245 sender: &T::CrossAccountId,246 ) -> DispatchResult {247 let id = collection.id;248249 if Self::collection_has_tokens(id) {250 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());251 }252253 // =========254255 PalletCommon::destroy_collection(collection.0, sender)?;256257 <TotalSupply<T>>::remove(id);258 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);259 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);260 Ok(())261 }262263 ///Checks if collection has tokens. Return `true` if it has.264 fn collection_has_tokens(collection_id: CollectionId) -> bool {265 <TotalSupply<T>>::get(collection_id) != 0266 }267268 /// Burns the specified amount of the token. If the token balance269 /// or total supply is less than the given value,270 /// it will return [DispatchError].271 pub fn burn(272 collection: &FungibleHandle<T>,273 owner: &T::CrossAccountId,274 amount: u128,275 ) -> DispatchResult {276 let total_supply = <TotalSupply<T>>::get(collection.id)277 .checked_sub(amount)278 .ok_or(<CommonError<T>>::TokenValueTooLow)?;279280 let balance = <Balance<T>>::get((collection.id, owner))281 .checked_sub(amount)282 .ok_or(<CommonError<T>>::TokenValueTooLow)?;283284 // Foreign collection check285 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);286287 if collection.permissions.access() == AccessMode::AllowList {288 collection.check_allowlist(owner)?;289 }290291 // =========292293 if balance == 0 {294 <Balance<T>>::remove((collection.id, owner));295 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());296 } else {297 <Balance<T>>::insert((collection.id, owner), balance);298 }299 <TotalSupply<T>>::insert(collection.id, total_supply);300301 <PalletEvm<T>>::deposit_log(302 ERC20Events::Transfer {303 from: *owner.as_eth(),304 to: H160::default(),305 value: amount.into(),306 }307 .to_log(collection_id_to_address(collection.id)),308 );309 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(310 collection.id,311 TokenId::default(),312 owner.clone(),313 amount,314 ));315 Ok(())316 }317318 /// Burns the specified amount of the token.319 pub fn burn_foreign(320 collection: &FungibleHandle<T>,321 owner: &T::CrossAccountId,322 amount: u128,323 ) -> DispatchResult {324 let total_supply = <TotalSupply<T>>::get(collection.id)325 .checked_sub(amount)326 .ok_or(<CommonError<T>>::TokenValueTooLow)?;327328 let balance = <Balance<T>>::get((collection.id, owner))329 .checked_sub(amount)330 .ok_or(<CommonError<T>>::TokenValueTooLow)?;331 // =========332333 if balance == 0 {334 <Balance<T>>::remove((collection.id, owner));335 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());336 } else {337 <Balance<T>>::insert((collection.id, owner), balance);338 }339 <TotalSupply<T>>::insert(collection.id, total_supply);340341 <PalletEvm<T>>::deposit_log(342 ERC20Events::Transfer {343 from: *owner.as_eth(),344 to: H160::default(),345 value: amount.into(),346 }347 .to_log(collection_id_to_address(collection.id)),348 );349 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(350 collection.id,351 TokenId::default(),352 owner.clone(),353 amount,354 ));355 Ok(())356 }357358 /// Transfers the specified amount of tokens. Will check that359 /// the transfer is allowed for the token.360 ///361 /// - `from`: Owner of tokens to transfer.362 /// - `to`: Recepient of transfered tokens.363 /// - `amount`: Amount of tokens to transfer.364 /// - `collection`: Collection that contains the token365 pub fn transfer(366 collection: &FungibleHandle<T>,367 from: &T::CrossAccountId,368 to: &T::CrossAccountId,369 amount: u128,370 nesting_budget: &dyn Budget,371 ) -> DispatchResult {372 ensure!(373 collection.limits.transfers_enabled(),374 <CommonError<T>>::TransferNotAllowed,375 );376377 if collection.permissions.access() == AccessMode::AllowList {378 collection.check_allowlist(from)?;379 collection.check_allowlist(to)?;380 }381 <PalletCommon<T>>::ensure_correct_receiver(to)?;382383 let balance_from = <Balance<T>>::get((collection.id, from))384 .checked_sub(amount)385 .ok_or(<CommonError<T>>::TokenValueTooLow)?;386 let balance_to = if from != to && amount != 0 {387 Some(388 <Balance<T>>::get((collection.id, to))389 .checked_add(amount)390 .ok_or(ArithmeticError::Overflow)?,391 )392 } else {393 None394 };395396 // =========397398 if let Some(balance_to) = balance_to {399 // from != to && amount != 0400401 <PalletStructure<T>>::nest_if_sent_to_token(402 from.clone(),403 to,404 collection.id,405 TokenId::default(),406 nesting_budget,407 )?;408409 if balance_from == 0 {410 <Balance<T>>::remove((collection.id, from));411 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());412 } else {413 <Balance<T>>::insert((collection.id, from), balance_from);414 }415 <Balance<T>>::insert((collection.id, to), balance_to);416 }417418 <PalletEvm<T>>::deposit_log(419 ERC20Events::Transfer {420 from: *from.as_eth(),421 to: *to.as_eth(),422 value: amount.into(),423 }424 .to_log(collection_id_to_address(collection.id)),425 );426 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(427 collection.id,428 TokenId::default(),429 from.clone(),430 to.clone(),431 amount,432 ));433 Ok(())434 }435436 /// Minting tokens for multiple IDs.437 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]438 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]439 pub fn create_multiple_items_common(440 collection: &FungibleHandle<T>,441 sender: &T::CrossAccountId,442 data: BTreeMap<T::CrossAccountId, u128>,443 nesting_budget: &dyn Budget,444 ) -> DispatchResult {445 let total_supply = data446 .iter()447 .map(|(_, v)| *v)448 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {449 acc.checked_add(v)450 })451 .ok_or(ArithmeticError::Overflow)?;452453 for (to, _) in data.iter() {454 <PalletStructure<T>>::check_nesting(455 sender.clone(),456 to,457 collection.id,458 TokenId::default(),459 nesting_budget,460 )?;461 }462463 let updated_balances = data464 .into_iter()465 .map(|(user, amount)| {466 let updated_balance = <Balance<T>>::get((collection.id, &user))467 .checked_add(amount)468 .ok_or(ArithmeticError::Overflow)?;469 Ok((user, amount, updated_balance))470 })471 .collect::<Result<Vec<_>, DispatchError>>()?;472473 // =========474475 <TotalSupply<T>>::insert(collection.id, total_supply);476 for (user, amount, updated_balance) in updated_balances {477 <Balance<T>>::insert((collection.id, &user), updated_balance);478 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(479 &user,480 collection.id,481 TokenId::default(),482 );483 <PalletEvm<T>>::deposit_log(484 ERC20Events::Transfer {485 from: H160::default(),486 to: *user.as_eth(),487 value: amount.into(),488 }489 .to_log(collection_id_to_address(collection.id)),490 );491 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(492 collection.id,493 TokenId::default(),494 user.clone(),495 amount,496 ));497 }498499 Ok(())500 }501502 /// Minting tokens for multiple IDs.503 /// See [`create_item`][`Pallet::create_item`] for more details.504 pub fn create_multiple_items(505 collection: &FungibleHandle<T>,506 sender: &T::CrossAccountId,507 data: BTreeMap<T::CrossAccountId, u128>,508 nesting_budget: &dyn Budget,509 ) -> DispatchResult {510 // Foreign collection check511 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);512513 if !collection.is_owner_or_admin(sender) {514 ensure!(515 collection.permissions.mint_mode(),516 <CommonError<T>>::PublicMintingNotAllowed517 );518 collection.check_allowlist(sender)?;519520 for (owner, _) in data.iter() {521 collection.check_allowlist(owner)?;522 }523 }524525 Self::create_multiple_items_common(collection, sender, data, nesting_budget)526 }527528 /// Minting tokens for multiple IDs.529 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.530 pub fn create_multiple_items_foreign(531 collection: &FungibleHandle<T>,532 sender: &T::CrossAccountId,533 data: BTreeMap<T::CrossAccountId, u128>,534 nesting_budget: &dyn Budget,535 ) -> DispatchResult {536 Self::create_multiple_items_common(collection, sender, data, nesting_budget)537 }538539 fn set_allowance_unchecked(540 collection: &FungibleHandle<T>,541 owner: &T::CrossAccountId,542 spender: &T::CrossAccountId,543 amount: u128,544 ) {545 if amount == 0 {546 <Allowance<T>>::remove((collection.id, owner, spender));547 } else {548 <Allowance<T>>::insert((collection.id, owner, spender), amount);549 }550551 <PalletEvm<T>>::deposit_log(552 ERC20Events::Approval {553 owner: *owner.as_eth(),554 spender: *spender.as_eth(),555 value: amount.into(),556 }557 .to_log(collection_id_to_address(collection.id)),558 );559 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(560 collection.id,561 TokenId(0),562 owner.clone(),563 spender.clone(),564 amount,565 ));566 }567568 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.569 ///570 /// - `collection`: Collection that contains the token571 /// - `owner`: Owner of tokens that sets the allowance.572 /// - `spender`: Recipient of the allowance rights.573 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.574 pub fn set_allowance(575 collection: &FungibleHandle<T>,576 owner: &T::CrossAccountId,577 spender: &T::CrossAccountId,578 amount: u128,579 ) -> DispatchResult {580 if collection.permissions.access() == AccessMode::AllowList {581 collection.check_allowlist(owner)?;582 collection.check_allowlist(spender)?;583 }584585 if <Balance<T>>::get((collection.id, owner)) < amount {586 ensure!(587 collection.ignores_owned_amount(owner),588 <CommonError<T>>::CantApproveMoreThanOwned589 );590 }591592 // =========593594 Self::set_allowance_unchecked(collection, owner, spender, amount);595 Ok(())596 }597598 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.599 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.600 ///601 /// - `collection`: Collection that contains the token.602 /// - `spender`: CrossAccountId who has the allowance rights.603 /// - `from`: The owner of the tokens who sets the allowance.604 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.605 fn check_allowed(606 collection: &FungibleHandle<T>,607 spender: &T::CrossAccountId,608 from: &T::CrossAccountId,609 amount: u128,610 nesting_budget: &dyn Budget,611 ) -> Result<Option<u128>, DispatchError> {612 if spender.conv_eq(from) {613 return Ok(None);614 }615 if collection.permissions.access() == AccessMode::AllowList {616 // `from`, `to` checked in [`transfer`]617 collection.check_allowlist(spender)?;618 }619 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {620 // TODO: should collection owner be allowed to perform this transfer?621 ensure!(622 <PalletStructure<T>>::check_indirectly_owned(623 spender.clone(),624 source.0,625 source.1,626 None,627 nesting_budget628 )?,629 <CommonError<T>>::ApprovedValueTooLow,630 );631 return Ok(None);632 }633 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);634 if allowance.is_none() {635 ensure!(636 collection.ignores_allowance(spender),637 <CommonError<T>>::ApprovedValueTooLow638 );639 }640641 Ok(allowance)642 }643644 /// Transfer fungible tokens from one account to another.645 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.646 /// The owner should set allowance for the spender to transfer pieces.647 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.648649 pub fn transfer_from(650 collection: &FungibleHandle<T>,651 spender: &T::CrossAccountId,652 from: &T::CrossAccountId,653 to: &T::CrossAccountId,654 amount: u128,655 nesting_budget: &dyn Budget,656 ) -> DispatchResult {657 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;658659 // =========660661 Self::transfer(collection, from, to, amount, nesting_budget)?;662 if let Some(allowance) = allowance {663 Self::set_allowance_unchecked(collection, from, spender, allowance);664 }665 Ok(())666 }667668 /// Burn fungible tokens from the account.669 ///670 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should671 /// set allowance for the spender to burn tokens.672 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.673 pub fn burn_from(674 collection: &FungibleHandle<T>,675 spender: &T::CrossAccountId,676 from: &T::CrossAccountId,677 amount: u128,678 nesting_budget: &dyn Budget,679 ) -> DispatchResult {680 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;681682 // =========683684 Self::burn(collection, from, amount)?;685 if let Some(allowance) = allowance {686 Self::set_allowance_unchecked(collection, from, spender, allowance);687 }688 Ok(())689 }690691 /// Creates fungible token.692 ///693 /// The sender should be the owner/admin of the collection or collection should be configured694 /// to allow public minting.695 ///696 /// - `data`: Contains user who will become the owners of the tokens and amount697 /// of tokens he will receive.698 pub fn create_item(699 collection: &FungibleHandle<T>,700 sender: &T::CrossAccountId,701 data: CreateItemData<T>,702 nesting_budget: &dyn Budget,703 ) -> DispatchResult {704 Self::create_multiple_items(705 collection,706 sender,707 [(data.0, data.1)].into_iter().collect(),708 nesting_budget,709 )710 }711712 /// Creates fungible token.713 ///714 /// - `data`: Contains user who will become the owners of the tokens and amount715 /// of tokens he will receive.716 pub fn create_item_foreign(717 collection: &FungibleHandle<T>,718 sender: &T::CrossAccountId,719 data: CreateItemData<T>,720 nesting_budget: &dyn Budget,721 ) -> DispatchResult {722 Self::create_multiple_items_foreign(723 collection,724 sender,725 [(data.0, data.1)].into_iter().collect(),726 nesting_budget,727 )728 }729730 /// Returns 10 tokens owners in no particular order731 ///732 /// There is no direct way to get token holders in ascending order,733 /// since `iter_prefix` returns values in no particular order.734 /// Therefore, getting the 10 largest holders with a large value of holders735 /// can lead to impact memory allocation + sorting with `n * log (n)`.736 pub fn token_owners(737 collection: CollectionId,738 _token: TokenId,739 ) -> Option<Vec<T::CrossAccountId>> {740 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))741 .map(|(owner, _amount)| owner)742 .take(10)743 .collect();744745 if res.is_empty() {746 None747 } else {748 Some(res)749 }750 }751}pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -236,4 +236,12 @@
operator: cross_sub;
};
}: {<Pallet<T>>::allowance_for_all(&collection, &owner, &operator)}
+
+ repair_item {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let item = create_max_item(&collection, &owner, owner.clone())?;
+ }: {<Pallet<T>>::repair_item(&collection, item)?}
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -126,6 +126,10 @@
fn set_allowance_for_all() -> Weight {
<SelfWeightOf<T>>::set_allowance_for_all()
}
+
+ fn repair_item() -> Weight {
+ <SelfWeightOf<T>>::repair_item()
+ }
}
fn map_create_data<T: Config>(
@@ -532,4 +536,11 @@
fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {
<Pallet<T>>::allowance_for_all(self, &owner, &operator)
}
+
+ fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::repair_item(self, token),
+ <CommonWeights<T>>::repair_item(),
+ )
+ }
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -1398,4 +1398,12 @@
) -> bool {
<CollectionAllowance<T>>::get((collection.id, owner, operator))
}
+
+ pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {
+ <TokenProperties<T>>::mutate((collection.id, token), |properties| {
+ properties.recompute_consumed_space();
+ });
+
+ Ok(())
+ }
}
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -50,6 +50,7 @@
fn token_owner() -> Weight;
fn set_allowance_for_all() -> Weight;
fn allowance_for_all() -> Weight;
+ fn repair_item() -> Weight;
}
/// Weights for pallet_nonfungible using the Substrate node and recommended hardware.
@@ -208,6 +209,12 @@
Weight::from_ref_time(6_161_000 as u64)
.saturating_add(T::DbWeight::get().reads(1 as u64))
}
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
+ fn repair_item() -> Weight {
+ Weight::from_ref_time(5_701_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
}
// For backwards compatibility and tests
@@ -365,4 +372,10 @@
Weight::from_ref_time(6_161_000 as u64)
.saturating_add(RocksDbWeight::get().reads(1 as u64))
}
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
+ fn repair_item() -> Weight {
+ Weight::from_ref_time(5_701_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
}
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -304,4 +304,12 @@
operator: cross_sub;
};
}: {<Pallet<T>>::allowance_for_all(&collection, &owner, &operator)}
+
+ repair_item {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let item = create_max_item(&collection, &owner, [(owner.clone(), 100)])?;
+ }: {<Pallet<T>>::repair_item(&collection, item)?}
}
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -156,6 +156,10 @@
fn set_allowance_for_all() -> Weight {
<SelfWeightOf<T>>::set_allowance_for_all()
}
+
+ fn repair_item() -> Weight {
+ <SelfWeightOf<T>>::repair_item()
+ }
}
fn map_create_data<T: Config>(
@@ -536,6 +540,13 @@
fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {
<Pallet<T>>::allowance_for_all(self, &owner, &operator)
}
+
+ fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::repair_item(self, token),
+ <CommonWeights<T>>::repair_item(),
+ )
+ }
}
impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1461,4 +1461,12 @@
) -> bool {
<CollectionAllowance<T>>::get((collection.id, owner, operator))
}
+
+ pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {
+ <TokenProperties<T>>::mutate((collection.id, token), |properties| {
+ properties.recompute_consumed_space();
+ });
+
+ Ok(())
+ }
}
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -57,6 +57,7 @@
fn token_owner() -> Weight;
fn set_allowance_for_all() -> Weight;
fn allowance_for_all() -> Weight;
+ fn repair_item() -> Weight;
}
/// Weights for pallet_refungible using the Substrate node and recommended hardware.
@@ -272,6 +273,12 @@
Weight::from_ref_time(5_901_000 as u64)
.saturating_add(T::DbWeight::get().reads(1 as u64))
}
+ // Storage: Refungible TokenProperties (r:1 w:1)
+ fn repair_item() -> Weight {
+ Weight::from_ref_time(5_489_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
}
// For backwards compatibility and tests
@@ -486,4 +493,10 @@
Weight::from_ref_time(5_901_000 as u64)
.saturating_add(RocksDbWeight::get().reads(1 as u64))
}
+ // Storage: Refungible TokenProperties (r:1 w:1)
+ fn repair_item() -> Weight {
+ Weight::from_ref_time(5_489_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -982,6 +982,23 @@
d.set_allowance_for_all(sender, operator, approve)
})
}
+
+ /// Repairs a broken item
+ ///
+ /// # Arguments
+ ///
+ /// * `collection_id`: ID of the collection the item belongs to.
+ /// * `item_id`: ID of the item.
+ #[weight = T::CommonWeightInfo::repair_item()]
+ pub fn repair_item(
+ _origin,
+ collection_id: CollectionId,
+ item_id: TokenId,
+ ) -> DispatchResultWithPostInfo {
+ dispatch_tx::<T, _>(collection_id, |d| {
+ d.repair_item(item_id)
+ })
+ }
}
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1218,6 +1218,10 @@
Ok(())
}
+
+ pub fn values(&self) -> impl Iterator<Item = &Value> {
+ self.0.values()
+ }
}
impl<Value> IntoIterator for PropertiesMap<Value> {
@@ -1290,6 +1294,12 @@
pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {
self.map.get(key)
}
+
+ /// Recomputes the consumed space for the current properties state.
+ /// Needed to repair a token due to a bug fixed in the [PR #733](https://github.com/UniqueNetwork/unique-chain/pull/773).
+ pub fn recompute_consumed_space(&mut self) {
+ self.consumed_space = self.map.values().map(|value| value.len() as u32).sum();
+ }
}
impl IntoIterator for Properties {
runtime/common/weights.rsdiffbeforeafterboth--- a/runtime/common/weights.rs
+++ b/runtime/common/weights.rs
@@ -124,6 +124,10 @@
fn set_allowance_for_all() -> Weight {
max_weight_of!(set_allowance_for_all())
}
+
+ fn repair_item() -> Weight {
+ max_weight_of!(repair_item())
+ }
}
#[cfg(feature = "refungible")]
tests/src/nesting/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/tokenProperties.test.ts
+++ b/tests/src/nesting/tokenProperties.test.ts
@@ -28,7 +28,7 @@
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ [alice, bob, charlie] = await helper.arrange.createAccounts([200n, 100n, 100n], donor);
});
permissions = [
@@ -401,6 +401,39 @@
consumedSpace = await token.getTokenPropertiesConsumedSpace();
expect(consumedSpace).to.be.equal(originalSpace);
}));
+
+ [
+ {mode: 'nft' as const, pieces: undefined, requiredPallets: []},
+ {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itSub.ifWithPallets(`repair_item preserves valid consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ const propKey = 'tok-prop';
+
+ const collection = await helper[testCase.mode].mintCollection(alice, {
+ tokenPropertyPermissions: [
+ {
+ key: propKey,
+ permission: {mutable: true, tokenOwner: true},
+ },
+ ],
+ });
+ const token = await (
+ testCase.pieces
+ ? collection.mintToken(alice, testCase.pieces)
+ : collection.mintToken(alice)
+ );
+
+ const propDataSize = 4096;
+ const propData = 'a'.repeat(propDataSize);
+
+ await token.setProperties(alice, [{key: propKey, value: propData}]);
+ const originalSpace = await token.getTokenPropertiesConsumedSpace();
+ expect(originalSpace).to.be.equal(propDataSize);
+
+ await helper.executeExtrinsic(alice, 'api.tx.unique.repairItem', [token.collectionId, token.tokenId], true);
+ const recomputedSpace = await token.getTokenPropertiesConsumedSpace();
+ expect(recomputedSpace).to.be.equal(originalSpace);
+ }));
});
describe('Negative Integration Test: Token Properties', () => {