difftreelog
Merge pull request #747 from UniqueNetwork/tests/refungible
in: master
Transfer tests
14 files 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, 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 }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 >;170}171172/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.173/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].174pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);175176/// Implementation of methods required for dispatching during runtime.177impl<T: Config> FungibleHandle<T> {178 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].179 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {180 Self(inner)181 }182183 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].184 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {185 self.0186 }187 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].188 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {189 &mut self.0190 }191}192impl<T: Config> WithRecorder<T> for FungibleHandle<T> {193 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {194 self.0.recorder()195 }196 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {197 self.0.into_recorder()198 }199}200impl<T: Config> Deref for FungibleHandle<T> {201 type Target = pallet_common::CollectionHandle<T>;202203 fn deref(&self) -> &Self::Target {204 &self.0205 }206}207208/// Pallet implementation for fungible assets209impl<T: Config> Pallet<T> {210 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.211 pub fn init_collection(212 owner: T::CrossAccountId,213 payer: T::CrossAccountId,214 data: CreateCollectionData<T::AccountId>,215 flags: CollectionFlags,216 ) -> Result<CollectionId, DispatchError> {217 <PalletCommon<T>>::init_collection(owner, payer, data, flags)218 }219220 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.221 pub fn init_foreign_collection(222 owner: T::CrossAccountId,223 payer: T::CrossAccountId,224 data: CreateCollectionData<T::AccountId>,225 ) -> Result<CollectionId, DispatchError> {226 let id = <PalletCommon<T>>::init_collection(227 owner,228 payer,229 data,230 CollectionFlags {231 foreign: true,232 ..Default::default()233 },234 )?;235 Ok(id)236 }237238 /// Destroys a collection.239 pub fn destroy_collection(240 collection: FungibleHandle<T>,241 sender: &T::CrossAccountId,242 ) -> DispatchResult {243 let id = collection.id;244245 if Self::collection_has_tokens(id) {246 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());247 }248249 // =========250251 PalletCommon::destroy_collection(collection.0, sender)?;252253 <TotalSupply<T>>::remove(id);254 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);255 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);256 Ok(())257 }258259 ///Checks if collection has tokens. Return `true` if it has.260 fn collection_has_tokens(collection_id: CollectionId) -> bool {261 <TotalSupply<T>>::get(collection_id) != 0262 }263264 /// Burns the specified amount of the token. If the token balance265 /// or total supply is less than the given value,266 /// it will return [DispatchError].267 pub fn burn(268 collection: &FungibleHandle<T>,269 owner: &T::CrossAccountId,270 amount: u128,271 ) -> DispatchResult {272 let total_supply = <TotalSupply<T>>::get(collection.id)273 .checked_sub(amount)274 .ok_or(<CommonError<T>>::TokenValueTooLow)?;275276 let balance = <Balance<T>>::get((collection.id, owner))277 .checked_sub(amount)278 .ok_or(<CommonError<T>>::TokenValueTooLow)?;279280 // Foreign collection check281 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);282283 if collection.permissions.access() == AccessMode::AllowList {284 collection.check_allowlist(owner)?;285 }286287 // =========288289 if balance == 0 {290 <Balance<T>>::remove((collection.id, owner));291 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());292 } else {293 <Balance<T>>::insert((collection.id, owner), balance);294 }295 <TotalSupply<T>>::insert(collection.id, total_supply);296297 <PalletEvm<T>>::deposit_log(298 ERC20Events::Transfer {299 from: *owner.as_eth(),300 to: H160::default(),301 value: amount.into(),302 }303 .to_log(collection_id_to_address(collection.id)),304 );305 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(306 collection.id,307 TokenId::default(),308 owner.clone(),309 amount,310 ));311 Ok(())312 }313314 /// Burns the specified amount of the token.315 pub fn burn_foreign(316 collection: &FungibleHandle<T>,317 owner: &T::CrossAccountId,318 amount: u128,319 ) -> DispatchResult {320 let total_supply = <TotalSupply<T>>::get(collection.id)321 .checked_sub(amount)322 .ok_or(<CommonError<T>>::TokenValueTooLow)?;323324 let balance = <Balance<T>>::get((collection.id, owner))325 .checked_sub(amount)326 .ok_or(<CommonError<T>>::TokenValueTooLow)?;327 // =========328329 if balance == 0 {330 <Balance<T>>::remove((collection.id, owner));331 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());332 } else {333 <Balance<T>>::insert((collection.id, owner), balance);334 }335 <TotalSupply<T>>::insert(collection.id, total_supply);336337 <PalletEvm<T>>::deposit_log(338 ERC20Events::Transfer {339 from: *owner.as_eth(),340 to: H160::default(),341 value: amount.into(),342 }343 .to_log(collection_id_to_address(collection.id)),344 );345 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(346 collection.id,347 TokenId::default(),348 owner.clone(),349 amount,350 ));351 Ok(())352 }353354 /// Transfers the specified amount of tokens. Will check that355 /// the transfer is allowed for the token.356 ///357 /// - `from`: Owner of tokens to transfer.358 /// - `to`: Recepient of transfered tokens.359 /// - `amount`: Amount of tokens to transfer.360 /// - `collection`: Collection that contains the token361 pub fn transfer(362 collection: &FungibleHandle<T>,363 from: &T::CrossAccountId,364 to: &T::CrossAccountId,365 amount: u128,366 nesting_budget: &dyn Budget,367 ) -> DispatchResult {368 ensure!(369 collection.limits.transfers_enabled(),370 <CommonError<T>>::TransferNotAllowed,371 );372373 if collection.permissions.access() == AccessMode::AllowList {374 collection.check_allowlist(from)?;375 collection.check_allowlist(to)?;376 }377 <PalletCommon<T>>::ensure_correct_receiver(to)?;378379 let balance_from = <Balance<T>>::get((collection.id, from))380 .checked_sub(amount)381 .ok_or(<CommonError<T>>::TokenValueTooLow)?;382 let balance_to = if from != to {383 Some(384 <Balance<T>>::get((collection.id, to))385 .checked_add(amount)386 .ok_or(ArithmeticError::Overflow)?,387 )388 } else {389 None390 };391392 // =========393394 <PalletStructure<T>>::nest_if_sent_to_token(395 from.clone(),396 to,397 collection.id,398 TokenId::default(),399 nesting_budget,400 )?;401402 if let Some(balance_to) = balance_to {403 // from != to404 if balance_from == 0 {405 <Balance<T>>::remove((collection.id, from));406 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());407 } else {408 <Balance<T>>::insert((collection.id, from), balance_from);409 }410 <Balance<T>>::insert((collection.id, to), balance_to);411 }412413 <PalletEvm<T>>::deposit_log(414 ERC20Events::Transfer {415 from: *from.as_eth(),416 to: *to.as_eth(),417 value: amount.into(),418 }419 .to_log(collection_id_to_address(collection.id)),420 );421 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(422 collection.id,423 TokenId::default(),424 from.clone(),425 to.clone(),426 amount,427 ));428 Ok(())429 }430431 /// Minting tokens for multiple IDs.432 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]433 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]434 pub fn create_multiple_items_common(435 collection: &FungibleHandle<T>,436 sender: &T::CrossAccountId,437 data: BTreeMap<T::CrossAccountId, u128>,438 nesting_budget: &dyn Budget,439 ) -> DispatchResult {440 let total_supply = data441 .iter()442 .map(|(_, v)| *v)443 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {444 acc.checked_add(v)445 })446 .ok_or(ArithmeticError::Overflow)?;447448 for (to, _) in data.iter() {449 <PalletStructure<T>>::check_nesting(450 sender.clone(),451 to,452 collection.id,453 TokenId::default(),454 nesting_budget,455 )?;456 }457458 let updated_balances = data459 .into_iter()460 .map(|(user, amount)| {461 let updated_balance = <Balance<T>>::get((collection.id, &user))462 .checked_add(amount)463 .ok_or(ArithmeticError::Overflow)?;464 Ok((user, amount, updated_balance))465 })466 .collect::<Result<Vec<_>, DispatchError>>()?;467468 // =========469470 <TotalSupply<T>>::insert(collection.id, total_supply);471 for (user, amount, updated_balance) in updated_balances {472 <Balance<T>>::insert((collection.id, &user), updated_balance);473 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(474 &user,475 collection.id,476 TokenId::default(),477 );478 <PalletEvm<T>>::deposit_log(479 ERC20Events::Transfer {480 from: H160::default(),481 to: *user.as_eth(),482 value: amount.into(),483 }484 .to_log(collection_id_to_address(collection.id)),485 );486 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(487 collection.id,488 TokenId::default(),489 user.clone(),490 amount,491 ));492 }493494 Ok(())495 }496497 /// Minting tokens for multiple IDs.498 /// See [`create_item`][`Pallet::create_item`] for more details.499 pub fn create_multiple_items(500 collection: &FungibleHandle<T>,501 sender: &T::CrossAccountId,502 data: BTreeMap<T::CrossAccountId, u128>,503 nesting_budget: &dyn Budget,504 ) -> DispatchResult {505 // Foreign collection check506 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);507508 if !collection.is_owner_or_admin(sender) {509 ensure!(510 collection.permissions.mint_mode(),511 <CommonError<T>>::PublicMintingNotAllowed512 );513 collection.check_allowlist(sender)?;514515 for (owner, _) in data.iter() {516 collection.check_allowlist(owner)?;517 }518 }519520 Self::create_multiple_items_common(collection, sender, data, nesting_budget)521 }522523 /// Minting tokens for multiple IDs.524 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.525 pub fn create_multiple_items_foreign(526 collection: &FungibleHandle<T>,527 sender: &T::CrossAccountId,528 data: BTreeMap<T::CrossAccountId, u128>,529 nesting_budget: &dyn Budget,530 ) -> DispatchResult {531 Self::create_multiple_items_common(collection, sender, data, nesting_budget)532 }533534 fn set_allowance_unchecked(535 collection: &FungibleHandle<T>,536 owner: &T::CrossAccountId,537 spender: &T::CrossAccountId,538 amount: u128,539 ) {540 if amount == 0 {541 <Allowance<T>>::remove((collection.id, owner, spender));542 } else {543 <Allowance<T>>::insert((collection.id, owner, spender), amount);544 }545546 <PalletEvm<T>>::deposit_log(547 ERC20Events::Approval {548 owner: *owner.as_eth(),549 spender: *spender.as_eth(),550 value: amount.into(),551 }552 .to_log(collection_id_to_address(collection.id)),553 );554 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(555 collection.id,556 TokenId(0),557 owner.clone(),558 spender.clone(),559 amount,560 ));561 }562563 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.564 ///565 /// - `collection`: Collection that contains the token566 /// - `owner`: Owner of tokens that sets the allowance.567 /// - `spender`: Recipient of the allowance rights.568 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.569 pub fn set_allowance(570 collection: &FungibleHandle<T>,571 owner: &T::CrossAccountId,572 spender: &T::CrossAccountId,573 amount: u128,574 ) -> DispatchResult {575 if collection.permissions.access() == AccessMode::AllowList {576 collection.check_allowlist(owner)?;577 collection.check_allowlist(spender)?;578 }579580 if <Balance<T>>::get((collection.id, owner)) < amount {581 ensure!(582 collection.ignores_owned_amount(owner),583 <CommonError<T>>::CantApproveMoreThanOwned584 );585 }586587 // =========588589 Self::set_allowance_unchecked(collection, owner, spender, amount);590 Ok(())591 }592593 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.594 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.595 ///596 /// - `collection`: Collection that contains the token.597 /// - `spender`: CrossAccountId who has the allowance rights.598 /// - `from`: The owner of the tokens who sets the allowance.599 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.600 fn check_allowed(601 collection: &FungibleHandle<T>,602 spender: &T::CrossAccountId,603 from: &T::CrossAccountId,604 amount: u128,605 nesting_budget: &dyn Budget,606 ) -> Result<Option<u128>, DispatchError> {607 if spender.conv_eq(from) {608 return Ok(None);609 }610 if collection.permissions.access() == AccessMode::AllowList {611 // `from`, `to` checked in [`transfer`]612 collection.check_allowlist(spender)?;613 }614 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {615 // TODO: should collection owner be allowed to perform this transfer?616 ensure!(617 <PalletStructure<T>>::check_indirectly_owned(618 spender.clone(),619 source.0,620 source.1,621 None,622 nesting_budget623 )?,624 <CommonError<T>>::ApprovedValueTooLow,625 );626 return Ok(None);627 }628 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);629 if allowance.is_none() {630 ensure!(631 collection.ignores_allowance(spender),632 <CommonError<T>>::ApprovedValueTooLow633 );634 }635636 Ok(allowance)637 }638639 /// Transfer fungible tokens from one account to another.640 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.641 /// The owner should set allowance for the spender to transfer pieces.642 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.643644 pub fn transfer_from(645 collection: &FungibleHandle<T>,646 spender: &T::CrossAccountId,647 from: &T::CrossAccountId,648 to: &T::CrossAccountId,649 amount: u128,650 nesting_budget: &dyn Budget,651 ) -> DispatchResult {652 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;653654 // =========655656 Self::transfer(collection, from, to, amount, nesting_budget)?;657 if let Some(allowance) = allowance {658 Self::set_allowance_unchecked(collection, from, spender, allowance);659 }660 Ok(())661 }662663 /// Burn fungible tokens from the account.664 ///665 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should666 /// set allowance for the spender to burn tokens.667 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.668 pub fn burn_from(669 collection: &FungibleHandle<T>,670 spender: &T::CrossAccountId,671 from: &T::CrossAccountId,672 amount: u128,673 nesting_budget: &dyn Budget,674 ) -> DispatchResult {675 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;676677 // =========678679 Self::burn(collection, from, amount)?;680 if let Some(allowance) = allowance {681 Self::set_allowance_unchecked(collection, from, spender, allowance);682 }683 Ok(())684 }685686 /// Creates fungible token.687 ///688 /// The sender should be the owner/admin of the collection or collection should be configured689 /// to allow public minting.690 ///691 /// - `data`: Contains user who will become the owners of the tokens and amount692 /// of tokens he will receive.693 pub fn create_item(694 collection: &FungibleHandle<T>,695 sender: &T::CrossAccountId,696 data: CreateItemData<T>,697 nesting_budget: &dyn Budget,698 ) -> DispatchResult {699 Self::create_multiple_items(700 collection,701 sender,702 [(data.0, data.1)].into_iter().collect(),703 nesting_budget,704 )705 }706707 /// Creates fungible token.708 ///709 /// - `data`: Contains user who will become the owners of the tokens and amount710 /// of tokens he will receive.711 pub fn create_item_foreign(712 collection: &FungibleHandle<T>,713 sender: &T::CrossAccountId,714 data: CreateItemData<T>,715 nesting_budget: &dyn Budget,716 ) -> DispatchResult {717 Self::create_multiple_items_foreign(718 collection,719 sender,720 [(data.0, data.1)].into_iter().collect(),721 nesting_budget,722 )723 }724725 /// Returns 10 tokens owners in no particular order726 ///727 /// There is no direct way to get token holders in ascending order,728 /// since `iter_prefix` returns values in no particular order.729 /// Therefore, getting the 10 largest holders with a large value of holders730 /// can lead to impact memory allocation + sorting with `n * log (n)`.731 pub fn token_owners(732 collection: CollectionId,733 _token: TokenId,734 ) -> Option<Vec<T::CrossAccountId>> {735 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))736 .map(|(owner, _amount)| owner)737 .take(10)738 .collect();739740 if res.is_empty() {741 None742 } else {743 Some(res)744 }745 }746}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 }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 >;170}171172/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.173/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].174pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);175176/// Implementation of methods required for dispatching during runtime.177impl<T: Config> FungibleHandle<T> {178 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].179 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {180 Self(inner)181 }182183 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].184 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {185 self.0186 }187 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].188 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {189 &mut self.0190 }191}192impl<T: Config> WithRecorder<T> for FungibleHandle<T> {193 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {194 self.0.recorder()195 }196 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {197 self.0.into_recorder()198 }199}200impl<T: Config> Deref for FungibleHandle<T> {201 type Target = pallet_common::CollectionHandle<T>;202203 fn deref(&self) -> &Self::Target {204 &self.0205 }206}207208/// Pallet implementation for fungible assets209impl<T: Config> Pallet<T> {210 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.211 pub fn init_collection(212 owner: T::CrossAccountId,213 payer: T::CrossAccountId,214 data: CreateCollectionData<T::AccountId>,215 flags: CollectionFlags,216 ) -> Result<CollectionId, DispatchError> {217 <PalletCommon<T>>::init_collection(owner, payer, data, flags)218 }219220 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.221 pub fn init_foreign_collection(222 owner: T::CrossAccountId,223 payer: T::CrossAccountId,224 data: CreateCollectionData<T::AccountId>,225 ) -> Result<CollectionId, DispatchError> {226 let id = <PalletCommon<T>>::init_collection(227 owner,228 payer,229 data,230 CollectionFlags {231 foreign: true,232 ..Default::default()233 },234 )?;235 Ok(id)236 }237238 /// Destroys a collection.239 pub fn destroy_collection(240 collection: FungibleHandle<T>,241 sender: &T::CrossAccountId,242 ) -> DispatchResult {243 let id = collection.id;244245 if Self::collection_has_tokens(id) {246 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());247 }248249 // =========250251 PalletCommon::destroy_collection(collection.0, sender)?;252253 <TotalSupply<T>>::remove(id);254 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);255 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);256 Ok(())257 }258259 ///Checks if collection has tokens. Return `true` if it has.260 fn collection_has_tokens(collection_id: CollectionId) -> bool {261 <TotalSupply<T>>::get(collection_id) != 0262 }263264 /// Burns the specified amount of the token. If the token balance265 /// or total supply is less than the given value,266 /// it will return [DispatchError].267 pub fn burn(268 collection: &FungibleHandle<T>,269 owner: &T::CrossAccountId,270 amount: u128,271 ) -> DispatchResult {272 let total_supply = <TotalSupply<T>>::get(collection.id)273 .checked_sub(amount)274 .ok_or(<CommonError<T>>::TokenValueTooLow)?;275276 let balance = <Balance<T>>::get((collection.id, owner))277 .checked_sub(amount)278 .ok_or(<CommonError<T>>::TokenValueTooLow)?;279280 // Foreign collection check281 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);282283 if collection.permissions.access() == AccessMode::AllowList {284 collection.check_allowlist(owner)?;285 }286287 // =========288289 if balance == 0 {290 <Balance<T>>::remove((collection.id, owner));291 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());292 } else {293 <Balance<T>>::insert((collection.id, owner), balance);294 }295 <TotalSupply<T>>::insert(collection.id, total_supply);296297 <PalletEvm<T>>::deposit_log(298 ERC20Events::Transfer {299 from: *owner.as_eth(),300 to: H160::default(),301 value: amount.into(),302 }303 .to_log(collection_id_to_address(collection.id)),304 );305 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(306 collection.id,307 TokenId::default(),308 owner.clone(),309 amount,310 ));311 Ok(())312 }313314 /// Burns the specified amount of the token.315 pub fn burn_foreign(316 collection: &FungibleHandle<T>,317 owner: &T::CrossAccountId,318 amount: u128,319 ) -> DispatchResult {320 let total_supply = <TotalSupply<T>>::get(collection.id)321 .checked_sub(amount)322 .ok_or(<CommonError<T>>::TokenValueTooLow)?;323324 let balance = <Balance<T>>::get((collection.id, owner))325 .checked_sub(amount)326 .ok_or(<CommonError<T>>::TokenValueTooLow)?;327 // =========328329 if balance == 0 {330 <Balance<T>>::remove((collection.id, owner));331 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());332 } else {333 <Balance<T>>::insert((collection.id, owner), balance);334 }335 <TotalSupply<T>>::insert(collection.id, total_supply);336337 <PalletEvm<T>>::deposit_log(338 ERC20Events::Transfer {339 from: *owner.as_eth(),340 to: H160::default(),341 value: amount.into(),342 }343 .to_log(collection_id_to_address(collection.id)),344 );345 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(346 collection.id,347 TokenId::default(),348 owner.clone(),349 amount,350 ));351 Ok(())352 }353354 /// Transfers the specified amount of tokens. Will check that355 /// the transfer is allowed for the token.356 ///357 /// - `from`: Owner of tokens to transfer.358 /// - `to`: Recepient of transfered tokens.359 /// - `amount`: Amount of tokens to transfer.360 /// - `collection`: Collection that contains the token361 pub fn transfer(362 collection: &FungibleHandle<T>,363 from: &T::CrossAccountId,364 to: &T::CrossAccountId,365 amount: u128,366 nesting_budget: &dyn Budget,367 ) -> DispatchResult {368 ensure!(369 collection.limits.transfers_enabled(),370 <CommonError<T>>::TransferNotAllowed,371 );372373 if collection.permissions.access() == AccessMode::AllowList {374 collection.check_allowlist(from)?;375 collection.check_allowlist(to)?;376 }377 <PalletCommon<T>>::ensure_correct_receiver(to)?;378379 let balance_from = <Balance<T>>::get((collection.id, from))380 .checked_sub(amount)381 .ok_or(<CommonError<T>>::TokenValueTooLow)?;382 let balance_to = if from != to && amount != 0 {383 Some(384 <Balance<T>>::get((collection.id, to))385 .checked_add(amount)386 .ok_or(ArithmeticError::Overflow)?,387 )388 } else {389 None390 };391392 // =========393394 if let Some(balance_to) = balance_to {395 // from != to && amount != 0396397 <PalletStructure<T>>::nest_if_sent_to_token(398 from.clone(),399 to,400 collection.id,401 TokenId::default(),402 nesting_budget,403 )?;404405 if balance_from == 0 {406 <Balance<T>>::remove((collection.id, from));407 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());408 } else {409 <Balance<T>>::insert((collection.id, from), balance_from);410 }411 <Balance<T>>::insert((collection.id, to), balance_to);412 }413414 <PalletEvm<T>>::deposit_log(415 ERC20Events::Transfer {416 from: *from.as_eth(),417 to: *to.as_eth(),418 value: amount.into(),419 }420 .to_log(collection_id_to_address(collection.id)),421 );422 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(423 collection.id,424 TokenId::default(),425 from.clone(),426 to.clone(),427 amount,428 ));429 Ok(())430 }431432 /// Minting tokens for multiple IDs.433 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]434 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]435 pub fn create_multiple_items_common(436 collection: &FungibleHandle<T>,437 sender: &T::CrossAccountId,438 data: BTreeMap<T::CrossAccountId, u128>,439 nesting_budget: &dyn Budget,440 ) -> DispatchResult {441 let total_supply = data442 .iter()443 .map(|(_, v)| *v)444 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {445 acc.checked_add(v)446 })447 .ok_or(ArithmeticError::Overflow)?;448449 for (to, _) in data.iter() {450 <PalletStructure<T>>::check_nesting(451 sender.clone(),452 to,453 collection.id,454 TokenId::default(),455 nesting_budget,456 )?;457 }458459 let updated_balances = data460 .into_iter()461 .map(|(user, amount)| {462 let updated_balance = <Balance<T>>::get((collection.id, &user))463 .checked_add(amount)464 .ok_or(ArithmeticError::Overflow)?;465 Ok((user, amount, updated_balance))466 })467 .collect::<Result<Vec<_>, DispatchError>>()?;468469 // =========470471 <TotalSupply<T>>::insert(collection.id, total_supply);472 for (user, amount, updated_balance) in updated_balances {473 <Balance<T>>::insert((collection.id, &user), updated_balance);474 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(475 &user,476 collection.id,477 TokenId::default(),478 );479 <PalletEvm<T>>::deposit_log(480 ERC20Events::Transfer {481 from: H160::default(),482 to: *user.as_eth(),483 value: amount.into(),484 }485 .to_log(collection_id_to_address(collection.id)),486 );487 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(488 collection.id,489 TokenId::default(),490 user.clone(),491 amount,492 ));493 }494495 Ok(())496 }497498 /// Minting tokens for multiple IDs.499 /// See [`create_item`][`Pallet::create_item`] for more details.500 pub fn create_multiple_items(501 collection: &FungibleHandle<T>,502 sender: &T::CrossAccountId,503 data: BTreeMap<T::CrossAccountId, u128>,504 nesting_budget: &dyn Budget,505 ) -> DispatchResult {506 // Foreign collection check507 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);508509 if !collection.is_owner_or_admin(sender) {510 ensure!(511 collection.permissions.mint_mode(),512 <CommonError<T>>::PublicMintingNotAllowed513 );514 collection.check_allowlist(sender)?;515516 for (owner, _) in data.iter() {517 collection.check_allowlist(owner)?;518 }519 }520521 Self::create_multiple_items_common(collection, sender, data, nesting_budget)522 }523524 /// Minting tokens for multiple IDs.525 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.526 pub fn create_multiple_items_foreign(527 collection: &FungibleHandle<T>,528 sender: &T::CrossAccountId,529 data: BTreeMap<T::CrossAccountId, u128>,530 nesting_budget: &dyn Budget,531 ) -> DispatchResult {532 Self::create_multiple_items_common(collection, sender, data, nesting_budget)533 }534535 fn set_allowance_unchecked(536 collection: &FungibleHandle<T>,537 owner: &T::CrossAccountId,538 spender: &T::CrossAccountId,539 amount: u128,540 ) {541 if amount == 0 {542 <Allowance<T>>::remove((collection.id, owner, spender));543 } else {544 <Allowance<T>>::insert((collection.id, owner, spender), amount);545 }546547 <PalletEvm<T>>::deposit_log(548 ERC20Events::Approval {549 owner: *owner.as_eth(),550 spender: *spender.as_eth(),551 value: amount.into(),552 }553 .to_log(collection_id_to_address(collection.id)),554 );555 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(556 collection.id,557 TokenId(0),558 owner.clone(),559 spender.clone(),560 amount,561 ));562 }563564 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.565 ///566 /// - `collection`: Collection that contains the token567 /// - `owner`: Owner of tokens that sets the allowance.568 /// - `spender`: Recipient of the allowance rights.569 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.570 pub fn set_allowance(571 collection: &FungibleHandle<T>,572 owner: &T::CrossAccountId,573 spender: &T::CrossAccountId,574 amount: u128,575 ) -> DispatchResult {576 if collection.permissions.access() == AccessMode::AllowList {577 collection.check_allowlist(owner)?;578 collection.check_allowlist(spender)?;579 }580581 if <Balance<T>>::get((collection.id, owner)) < amount {582 ensure!(583 collection.ignores_owned_amount(owner),584 <CommonError<T>>::CantApproveMoreThanOwned585 );586 }587588 // =========589590 Self::set_allowance_unchecked(collection, owner, spender, amount);591 Ok(())592 }593594 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.595 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.596 ///597 /// - `collection`: Collection that contains the token.598 /// - `spender`: CrossAccountId who has the allowance rights.599 /// - `from`: The owner of the tokens who sets the allowance.600 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.601 fn check_allowed(602 collection: &FungibleHandle<T>,603 spender: &T::CrossAccountId,604 from: &T::CrossAccountId,605 amount: u128,606 nesting_budget: &dyn Budget,607 ) -> Result<Option<u128>, DispatchError> {608 if spender.conv_eq(from) {609 return Ok(None);610 }611 if collection.permissions.access() == AccessMode::AllowList {612 // `from`, `to` checked in [`transfer`]613 collection.check_allowlist(spender)?;614 }615 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {616 // TODO: should collection owner be allowed to perform this transfer?617 ensure!(618 <PalletStructure<T>>::check_indirectly_owned(619 spender.clone(),620 source.0,621 source.1,622 None,623 nesting_budget624 )?,625 <CommonError<T>>::ApprovedValueTooLow,626 );627 return Ok(None);628 }629 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);630 if allowance.is_none() {631 ensure!(632 collection.ignores_allowance(spender),633 <CommonError<T>>::ApprovedValueTooLow634 );635 }636637 Ok(allowance)638 }639640 /// Transfer fungible tokens from one account to another.641 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.642 /// The owner should set allowance for the spender to transfer pieces.643 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.644645 pub fn transfer_from(646 collection: &FungibleHandle<T>,647 spender: &T::CrossAccountId,648 from: &T::CrossAccountId,649 to: &T::CrossAccountId,650 amount: u128,651 nesting_budget: &dyn Budget,652 ) -> DispatchResult {653 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;654655 // =========656657 Self::transfer(collection, from, to, amount, nesting_budget)?;658 if let Some(allowance) = allowance {659 Self::set_allowance_unchecked(collection, from, spender, allowance);660 }661 Ok(())662 }663664 /// Burn fungible tokens from the account.665 ///666 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should667 /// set allowance for the spender to burn tokens.668 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.669 pub fn burn_from(670 collection: &FungibleHandle<T>,671 spender: &T::CrossAccountId,672 from: &T::CrossAccountId,673 amount: u128,674 nesting_budget: &dyn Budget,675 ) -> DispatchResult {676 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;677678 // =========679680 Self::burn(collection, from, amount)?;681 if let Some(allowance) = allowance {682 Self::set_allowance_unchecked(collection, from, spender, allowance);683 }684 Ok(())685 }686687 /// Creates fungible token.688 ///689 /// The sender should be the owner/admin of the collection or collection should be configured690 /// to allow public minting.691 ///692 /// - `data`: Contains user who will become the owners of the tokens and amount693 /// of tokens he will receive.694 pub fn create_item(695 collection: &FungibleHandle<T>,696 sender: &T::CrossAccountId,697 data: CreateItemData<T>,698 nesting_budget: &dyn Budget,699 ) -> DispatchResult {700 Self::create_multiple_items(701 collection,702 sender,703 [(data.0, data.1)].into_iter().collect(),704 nesting_budget,705 )706 }707708 /// Creates fungible token.709 ///710 /// - `data`: Contains user who will become the owners of the tokens and amount711 /// of tokens he will receive.712 pub fn create_item_foreign(713 collection: &FungibleHandle<T>,714 sender: &T::CrossAccountId,715 data: CreateItemData<T>,716 nesting_budget: &dyn Budget,717 ) -> DispatchResult {718 Self::create_multiple_items_foreign(719 collection,720 sender,721 [(data.0, data.1)].into_iter().collect(),722 nesting_budget,723 )724 }725726 /// Returns 10 tokens owners in no particular order727 ///728 /// There is no direct way to get token holders in ascending order,729 /// since `iter_prefix` returns values in no particular order.730 /// Therefore, getting the 10 largest holders with a large value of holders731 /// can lead to impact memory allocation + sorting with `n * log (n)`.732 pub fn token_owners(733 collection: CollectionId,734 _token: TokenId,735 ) -> Option<Vec<T::CrossAccountId>> {736 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))737 .map(|(owner, _amount)| owner)738 .take(10)739 .collect();740741 if res.is_empty() {742 None743 } else {744 Some(res)745 }746 }747}pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -291,6 +291,7 @@
<CommonWeights<T>>::burn_item(),
)
} else {
+ <Pallet<T>>::check_token_immediate_ownership(self, token, &sender)?;
Ok(().into())
}
}
@@ -320,6 +321,7 @@
<CommonWeights<T>>::transfer(),
)
} else {
+ <Pallet<T>>::check_token_immediate_ownership(self, token, &from)?;
Ok(().into())
}
}
@@ -360,6 +362,8 @@
<CommonWeights<T>>::transfer_from(),
)
} else {
+ <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;
+
Ok(().into())
}
}
@@ -380,6 +384,8 @@
<CommonWeights<T>>::burn_from(),
)
} else {
+ <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;
+
Ok(().into())
}
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -814,6 +814,20 @@
<PalletCommon<T>>::set_property_permission(collection, sender, permission)
}
+ pub fn check_token_immediate_ownership(
+ collection: &NonfungibleHandle<T>,
+ token: TokenId,
+ possible_owner: &T::CrossAccountId,
+ ) -> DispatchResult {
+ let token_data =
+ <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
+ ensure!(
+ &token_data.owner == possible_owner,
+ <CommonError<T>>::NoPermission
+ );
+ Ok(())
+ }
+
/// Transfer NFT token from one account to another.
///
/// `from` account stops being the owner and `to` account becomes the owner of the token.
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -34,6 +34,7 @@
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
erc::{CommonEvmHandler, CollectionCall, static_property::key},
eth::EthCrossAccount,
+ Error as CommonError,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
@@ -508,6 +509,13 @@
) -> Result<()> {
collection.consume_store_reads(1)?;
let total_supply = <TotalSupply<T>>::get((collection.id, token));
+
+ if owner_balance == 0 {
+ return Err(dispatch_to_evm::<T>(
+ <CommonError<T>>::MustBeTokenOwner.into(),
+ ));
+ }
+
if total_supply != owner_balance {
return Err("token has multiple owners".into());
}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -452,6 +452,10 @@
token: TokenId,
amount: u128,
) -> DispatchResult {
+ if <Balance<T>>::get((collection.id, token, owner)) == 0 {
+ return Err(<CommonError<T>>::TokenValueTooLow.into());
+ }
+
let total_supply = <TotalSupply<T>>::get((collection.id, token))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
@@ -739,12 +743,17 @@
<PalletCommon<T>>::ensure_correct_receiver(to)?;
let initial_balance_from = <Balance<T>>::get((collection.id, token, from));
+
+ if initial_balance_from == 0 {
+ return Err(<CommonError<T>>::TokenValueTooLow.into());
+ }
+
let updated_balance_from = initial_balance_from
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
let mut create_target = false;
let from_to_differ = from != to;
- let updated_balance_to = if from != to {
+ let updated_balance_to = if from != to && amount != 0 {
let old_balance = <Balance<T>>::get((collection.id, token, to));
if old_balance == 0 {
create_target = true;
@@ -786,16 +795,17 @@
// =========
- <PalletStructure<T>>::nest_if_sent_to_token(
- from.clone(),
- to,
- collection.id,
- token,
- nesting_budget,
- )?;
+ if let Some(updated_balance_to) = updated_balance_to {
+ // from != to && amount != 0
+
+ <PalletStructure<T>>::nest_if_sent_to_token(
+ from.clone(),
+ to,
+ collection.id,
+ token,
+ nesting_budget,
+ )?;
- if let Some(updated_balance_to) = updated_balance_to {
- // from != to
if updated_balance_from == 0 {
<Balance<T>>::remove((collection.id, token, from));
<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);
tests/src/burnItem.test.tsdiffbeforeafterboth--- a/tests/src/burnItem.test.ts
+++ b/tests/src/burnItem.test.ts
@@ -140,6 +140,31 @@
await expect(token.burn(bob)).to.be.rejectedWith('common.NoPermission');
});
+ itSub.ifWithPallets('RFT: cannot burn non-owned token pieces', [Pallets.ReFungible], async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice);
+ const aliceToken = await collection.mintToken(alice, 10n, {Substrate: alice.address});
+ const bobToken = await collection.mintToken(alice, 10n, {Substrate: bob.address});
+
+ // 1. Cannot burn non-owned token:
+ await expect(bobToken.burn(alice, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(bobToken.burn(alice, 5n)).to.be.rejectedWith('common.TokenValueTooLow');
+ // 2. Cannot burn non-existing token:
+ await expect(helper.rft.burnToken(alice, 99999, 10)).to.be.rejectedWith('common.CollectionNotFound');
+ await expect(helper.rft.burnToken(alice, collection.collectionId, 99999)).to.be.rejectedWith('common.TokenValueTooLow');
+ // 3. Can burn zero amount of owned tokens (EIP-20)
+ await aliceToken.burn(alice, 0n);
+
+ // 4. Storage is not corrupted:
+ expect(await aliceToken.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
+ expect(await bobToken.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
+
+ // 4.1 Tokens can be transfered:
+ await aliceToken.transfer(alice, {Substrate: bob.address}, 10n);
+ await bobToken.transfer(bob, {Substrate: alice.address}, 10n);
+ expect(await aliceToken.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
+ expect(await bobToken.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
+ });
+
itSub('Transfer a burned token', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
const token = await collection.mintToken(alice);
@@ -155,4 +180,48 @@
await expect(collection.burnTokens(alice, 11n)).to.be.rejectedWith('common.TokenValueTooLow');
expect(await collection.getBalance({Substrate: alice.address})).to.eq(10n);
});
+
+ itSub('Zero burn NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Coll', description: 'Desc', tokenPrefix: 'T'});
+ const tokenAlice = await collection.mintToken(alice, {Substrate: alice.address});
+ const tokenBob = await collection.mintToken(alice, {Substrate: bob.address});
+
+ // 1. Zero burn of own tokens allowed:
+ await helper.executeExtrinsic(alice, 'api.tx.unique.burnItem', [collection.collectionId, tokenAlice.tokenId, 0]);
+ // 2. Zero burn of non-owned tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnItem', [collection.collectionId, tokenBob.tokenId, 0])).to.be.rejectedWith('common.NoPermission');
+ // 3. Zero burn of non-existing tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnItem', [collection.collectionId, 9999, 0])).to.be.rejectedWith('common.TokenNotFound');
+ expect(await tokenAlice.doesExist()).to.be.true;
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: alice.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4. Storage is not corrupted:
+ await tokenAlice.transfer(alice, {Substrate: bob.address});
+ await tokenBob.transfer(bob, {Substrate: alice.address});
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: alice.address});
+ });
+
+ itSub('zero burnFrom NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Zero', description: 'Zero transfer', tokenPrefix: 'TF'});
+ const notApprovedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ const approvedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ await approvedNft.approve(bob, {Substrate: alice.address});
+
+ // 1. Zero burnFrom of non-existing tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnFrom', [collection.collectionId, {Substrate: bob.address}, 9999, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 2. Zero burnFrom of not approved tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.burnFrom', [collection.collectionId, {Substrate: bob.address}, notApprovedNft.tokenId, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 3. Zero burnFrom of approved tokens allowed:
+ await helper.executeExtrinsic(alice, 'api.tx.unique.burnFrom', [collection.collectionId, {Substrate: bob.address}, approvedNft.tokenId, 0]);
+
+ // 4.1 approvedNft still approved:
+ expect(await approvedNft.isApproved({Substrate: alice.address})).to.be.true;
+ // 4.2 bob is still the owner:
+ expect(await approvedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await notApprovedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4.3 Alice can burn approved nft:
+ await approvedNft.burnFrom(alice, {Substrate: bob.address});
+ expect(await approvedNft.doesExist()).to.be.false;
+ });
});
tests/src/eth/fungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -277,7 +277,7 @@
}
});
- itEth('Cannot transferCross() more than have', async ({helper}) => {
+ ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} incorrect amount`, async ({helper}) => {
const sender = await helper.eth.createAccountWithBalance(donor);
const receiverEth = await helper.eth.createAccountWithBalance(donor);
const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);
@@ -289,8 +289,13 @@
const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'ft', sender);
- await expect(collectionEvm.methods.transferCross(receiverCrossEth, BALANCE_TO_TRANSFER).send({from: sender})).to.be.rejected;
- });
+ // 1. Cannot transfer more than have
+ const receiver = testCase === 'transfer' ? receiverEth : receiverCrossEth;
+ await expect(collectionEvm.methods[testCase](receiver, BALANCE_TO_TRANSFER).send({from: sender})).to.be.rejected;
+ // 2. Zero transfer allowed (EIP-20):
+ await collectionEvm.methods[testCase](receiver, 0n).send({from: sender});
+ }));
+
itEth('Can perform transfer()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -517,6 +517,26 @@
expect(receiverBalance).to.contain(tokenId);
}
});
+
+ ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} non-owned token`, async ({helper}) => {
+ const sender = await helper.eth.createAccountWithBalance(donor);
+ const tokenOwner = await helper.eth.createAccountWithBalance(donor);
+ const receiverSub = minter;
+ const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);
+
+ const collection = await helper.nft.mintCollection(minter, {});
+ const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', sender);
+
+ await collection.mintToken(minter, {Ethereum: sender});
+ const nonSendersToken = await collection.mintToken(minter, {Ethereum: tokenOwner});
+
+ // Cannot transferCross someone else's token:
+ const receiver = testCase === 'transfer' ? helper.address.substrateToEth(receiverSub.address) : receiverCrossSub;
+ await expect(collectionEvm.methods[testCase](receiver, nonSendersToken.tokenId).send({from: sender})).to.be.rejected;
+ // Cannot transfer token if it does not exist:
+ await expect(collectionEvm.methods[testCase](receiver, 999999).send({from: sender})).to.be.rejected;
+ }));
});
describe('NFT: Fees', () => {
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -413,9 +413,10 @@
}
});
- itEth.skip('Cannot transferCross with invalid params', async ({helper}) => {
+ ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} non-owned token`, async ({helper}) => {
const sender = await helper.eth.createAccountWithBalance(donor);
const tokenOwner = await helper.eth.createAccountWithBalance(donor);
+ const receiverSub = minter;
const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(minter);
const collection = await helper.rft.mintCollection(minter, {});
@@ -423,12 +424,14 @@
const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'rft', sender);
await collection.mintToken(minter, 50n, {Ethereum: sender});
- const notSendersToken = await collection.mintToken(minter, 50n, {Ethereum: tokenOwner});
+ const nonSendersToken = await collection.mintToken(minter, 50n, {Ethereum: tokenOwner});
+
// Cannot transferCross someone else's token:
- await expect(collectionEvm.methods.transferCross(receiverCrossSub, notSendersToken.tokenId).send({from: sender})).to.be.rejected;
- // FIXME: (transaction successful): Cannot transfer token if it does not exist:
- await expect(collectionEvm.methods.transferCross(receiverCrossSub, 999999).send({from: sender})).to.be.rejected;
- });
+ const receiver = testCase === 'transfer' ? helper.address.substrateToEth(receiverSub.address) : receiverCrossSub;
+ await expect(collectionEvm.methods[testCase](receiver, nonSendersToken.tokenId).send({from: sender})).to.be.rejected;
+ // Cannot transfer token if it does not exist:
+ await expect(collectionEvm.methods[testCase](receiver, 999999).send({from: sender})).to.be.rejected;
+ }));
itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -227,6 +227,46 @@
}
});
+ [
+ 'transfer',
+ // 'transferCross', // TODO
+ ].map(testCase =>
+ itEth(`Cannot ${testCase}() non-owned token`, async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const receiver = await helper.eth.createAccountWithBalance(donor);
+ const collection = await helper.rft.mintCollection(alice);
+ const rftOwner = await collection.mintToken(alice, 10n, {Ethereum: owner});
+ const rftReceiver = await collection.mintToken(alice, 10n, {Ethereum: receiver});
+ const tokenIdNonExist = 9999999;
+
+ const tokenAddress1 = helper.ethAddress.fromTokenId(collection.collectionId, rftOwner.tokenId);
+ const tokenAddress2 = helper.ethAddress.fromTokenId(collection.collectionId, rftReceiver.tokenId);
+ const tokenAddressNonExist = helper.ethAddress.fromTokenId(collection.collectionId, tokenIdNonExist);
+ const tokenEvmOwner = helper.ethNativeContract.rftToken(tokenAddress1, owner);
+ const tokenEvmReceiver = helper.ethNativeContract.rftToken(tokenAddress2, owner);
+ const tokenEvmNonExist = helper.ethNativeContract.rftToken(tokenAddressNonExist, owner);
+
+ // 1. Can transfer zero amount (EIP-20):
+ await tokenEvmOwner.methods[testCase](receiver, 0).send({from: owner});
+ // 2. Cannot transfer non-owned token:
+ await expect(tokenEvmReceiver.methods[testCase](owner, 0).send({from: owner})).to.be.rejected;
+ await expect(tokenEvmReceiver.methods[testCase](owner, 5).send({from: owner})).to.be.rejected;
+ // 3. Cannot transfer non-existing token:
+ await expect(tokenEvmNonExist.methods[testCase](owner, 0).send({from: owner})).to.be.rejected;
+ await expect(tokenEvmNonExist.methods[testCase](owner, 5).send({from: owner})).to.be.rejected;
+
+ // 4. Storage is not corrupted:
+ expect(await rftOwner.getTop10Owners()).to.deep.eq([{Ethereum: owner.toLowerCase()}]);
+ expect(await rftReceiver.getTop10Owners()).to.deep.eq([{Ethereum: receiver.toLowerCase()}]);
+ expect(await helper.rft.getTokenTop10Owners(collection.collectionId, tokenIdNonExist)).to.deep.eq([]); // TODO
+
+ // 4.1 Tokens can be transferred:
+ await tokenEvmOwner.methods[testCase](receiver, 10).send({from: owner});
+ await tokenEvmReceiver.methods[testCase](owner, 10).send({from: receiver});
+ expect(await rftOwner.getTop10Owners()).to.deep.eq([{Ethereum: receiver.toLowerCase()}]);
+ expect(await rftReceiver.getTop10Owners()).to.deep.eq([{Ethereum: owner.toLowerCase()}]);
+ }));
+
itEth('Can perform repartition()', async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = await helper.eth.createAccountWithBalance(donor);
tests/src/fungible.test.tsdiffbeforeafterboth--- a/tests/src/fungible.test.ts
+++ b/tests/src/fungible.test.ts
@@ -15,7 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {itSub, usingPlaygrounds, expect} from './util';
+import {itSub, usingPlaygrounds, expect, requirePalletsOrSkip, Pallets} from './util';
const U128_MAX = (1n << 128n) - 1n;
@@ -145,3 +145,42 @@
expect(await collection.getBalance(ethAcc)).to.be.equal(10n);
});
});
+
+describe('Fungible negative tests', () => {
+ let donor: IKeyringPair;
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async function() {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.Fungible]);
+
+ donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('Cannot transfer incorrect amount of tokens', async ({helper}) => {
+ const collection = await helper.ft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const nonExistingCollection = helper.ft.getCollectionObject(99999);
+ await collection.mint(alice, 10n, {Substrate: bob.address});
+
+ // 1. Alice cannot transfer more than 0 tokens if balance low:
+ await expect(collection.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(collection.transfer(alice, {Substrate: charlie.address}, 100n)).to.be.rejectedWith('common.TokenValueTooLow');
+
+ // 2. Alice cannot transfer non-existing token:
+ await expect(nonExistingCollection.transfer(alice, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.CollectionNotFound');
+ await expect(nonExistingCollection.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.CollectionNotFound');
+
+ // 3. Zero transfer allowed (EIP-20):
+ await collection.transfer(bob, {Substrate: charlie.address}, 0n);
+ // 3.1 even if the balance = 0
+ await collection.transfer(alice, {Substrate: charlie.address}, 0n);
+
+ expect(await collection.getBalance({Substrate: alice.address})).to.eq(0n);
+ expect(await collection.getBalance({Substrate: bob.address})).to.eq(10n);
+ expect(await collection.getBalance({Substrate: charlie.address})).to.eq(0n);
+ });
+});
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -255,3 +255,43 @@
});
});
+describe('Refungible negative tests', () => {
+ let donor: IKeyringPair;
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async function() {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+ donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('Cannot transfer incorrect amount of token pieces', async ({helper}) => {
+ const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
+ const tokenAlice = await collection.mintToken(alice, 10n, {Substrate: alice.address});
+ const tokenBob = await collection.mintToken(alice, 10n, {Substrate: bob.address});
+
+ // 1. Alice cannot transfer Bob's token:
+ await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 10n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(tokenBob.transfer(alice, {Substrate: charlie.address}, 100n)).to.be.rejectedWith('common.TokenValueTooLow');
+
+ // 2. Alice cannot transfer non-existing token:
+ await expect(collection.transferToken(alice, 100, {Substrate: charlie.address}, 0n)).to.be.rejectedWith('common.TokenValueTooLow');
+ await expect(collection.transferToken(alice, 100, {Substrate: charlie.address}, 1n)).to.be.rejectedWith('common.TokenValueTooLow');
+
+ // 3. Zero transfer allowed (EIP-20):
+ await tokenAlice.transfer(alice, {Substrate: charlie.address}, 0n);
+
+ expect(await tokenAlice.getTop10Owners()).to.deep.eq([{Substrate: alice.address}]);
+ expect(await tokenBob.getTop10Owners()).to.deep.eq([{Substrate: bob.address}]);
+ expect(await tokenAlice.getBalance({Substrate: alice.address})).to.eq(10n);
+ expect(await tokenBob.getBalance({Substrate: bob.address})).to.eq(10n);
+ expect(await tokenBob.getBalance({Substrate: charlie.address})).to.eq(0n);
+ });
+});
tests/src/transfer.test.tsdiffbeforeafterboth--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -122,6 +122,7 @@
});
});
+
itSub('[nft] Transfer with not existed collection_id', async ({helper}) => {
const collectionId = (1 << 32) - 1;
await expect(helper.nft.transferToken(alice, collectionId, 1, {Substrate: bob.address}))
@@ -191,6 +192,25 @@
.to.be.rejectedWith(/common\.TokenValueTooLow/);
});
+ itSub('Zero transfer NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-Neg-3-NFT', description: '', tokenPrefix: 'T'});
+ const tokenAlice = await collection.mintToken(alice, {Substrate: alice.address});
+ const tokenBob = await collection.mintToken(alice, {Substrate: bob.address});
+ // 1. Zero transfer of own tokens allowed:
+ await helper.executeExtrinsic(alice, 'api.tx.unique.transfer', [{Substrate: bob.address}, collection.collectionId, tokenAlice.tokenId, 0]);
+ // 2. Zero transfer of non-owned tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transfer', [{Substrate: alice.address}, collection.collectionId, tokenBob.tokenId, 0])).to.be.rejectedWith('common.NoPermission');
+ // 3. Zero transfer of non-existing tokens not allowed:
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transfer', [{Substrate: alice.address}, collection.collectionId, 10, 0])).to.be.rejectedWith('common.TokenNotFound');
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: alice.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4. Storage is not corrupted:
+ await tokenAlice.transfer(alice, {Substrate: bob.address});
+ await tokenBob.transfer(bob, {Substrate: alice.address});
+ expect(await tokenAlice.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await tokenBob.getOwner()).to.deep.eq({Substrate: alice.address});
+ });
+
itSub('[nft] Transfer with deleted item_id', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice, {name: 'Transfer-Neg-3-NFT', description: '', tokenPrefix: 'T'});
const nft = await collection.mintToken(alice);
tests/src/transferFrom.test.tsdiffbeforeafterboth--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -349,4 +349,27 @@
{Substrate: charlie.address},
)).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
});
+
+ itSub('zero transfer NFT', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'Zero', description: 'Zero transfer', tokenPrefix: 'TF'});
+ const notApprovedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ const approvedNft = await collection.mintToken(alice, {Substrate: bob.address});
+ await approvedNft.approve(bob, {Substrate: alice.address});
+
+ // 1. Cannot zero transferFrom (non-existing token)
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transferFrom', [{Substrate: bob.address}, {Substrate: alice.address}, collection.collectionId, 9999, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 2. Cannot zero transferFrom (not approved token)
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.transferFrom', [{Substrate: bob.address}, {Substrate: alice.address}, collection.collectionId, notApprovedNft.tokenId, 0])).to.be.rejectedWith('common.ApprovedValueTooLow');
+ // 3. Can zero transferFrom (approved token):
+ await helper.executeExtrinsic(alice, 'api.tx.unique.transferFrom', [{Substrate: bob.address}, {Substrate: alice.address}, collection.collectionId, approvedNft.tokenId, 0]);
+
+ // 4.1 approvedNft still approved:
+ expect(await approvedNft.isApproved({Substrate: alice.address})).to.be.true;
+ // 4.2 bob is still the owner:
+ expect(await approvedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ expect(await notApprovedNft.getOwner()).to.deep.eq({Substrate: bob.address});
+ // 4.3 Alice can transfer approved nft:
+ await approvedNft.transferFrom(alice, {Substrate: bob.address}, {Substrate: alice.address});
+ expect(await approvedNft.getOwner()).to.deep.eq({Substrate: alice.address});
+ });
});