git.delta.rocks / unique-network / refs/commits / d82d09e3c952

difftreelog

fix(refungible-pallet) fixed wrong amount in ItemCreated event

Grigoriy Simonov2022-08-04parent: #3203150.patch.diff
in: master

4 files changed

modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
before · pallets/fungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//!	- [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::{ensure};84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86	AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,87	budget::Budget,88};89use pallet_common::{90	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91	eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115	use up_data_structs::CollectionId;116	use super::weights::WeightInfo;117118	#[pallet::error]119	pub enum Error<T> {120		/// Not Fungible item data used to mint in Fungible collection.121		NotFungibleDataUsedToMintFungibleCollectionToken,122		/// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.123		FungibleItemsHaveNoId,124		/// Tried to set data for fungible item.125		FungibleItemsDontHaveData,126		/// Fungible token does not support nesting.127		FungibleDisallowsNesting,128		/// Setting item properties is not allowed.129		SettingPropertiesNotAllowed,130	}131132	#[pallet::config]133	pub trait Config:134		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config135	{136		type WeightInfo: WeightInfo;137	}138139	#[pallet::pallet]140	#[pallet::generate_store(pub(super) trait Store)]141	pub struct Pallet<T>(_);142143	/// Total amount of fungible tokens inside a collection.144	#[pallet::storage]145	pub type TotalSupply<T: Config> =146		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;147148	/// Amount of tokens owned by an account inside a collection.149	#[pallet::storage]150	pub type Balance<T: Config> = StorageNMap<151		Key = (152			Key<Twox64Concat, CollectionId>,153			Key<Blake2_128Concat, T::CrossAccountId>,154		),155		Value = u128,156		QueryKind = ValueQuery,157	>;158159	/// Storage for assets delegated to a limited extent to other users.160	#[pallet::storage]161	pub type Allowance<T: Config> = StorageNMap<162		Key = (163			Key<Twox64Concat, CollectionId>,164			Key<Blake2_128, T::CrossAccountId>,165			Key<Blake2_128Concat, T::CrossAccountId>,166		),167		Value = u128,168		QueryKind = ValueQuery,169	>;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		data: CreateCollectionData<T::AccountId>,214	) -> Result<CollectionId, DispatchError> {215		<PalletCommon<T>>::init_collection(owner, data, false)216	}217218	/// Destroys a collection.219	pub fn destroy_collection(220		collection: FungibleHandle<T>,221		sender: &T::CrossAccountId,222	) -> DispatchResult {223		let id = collection.id;224225		if Self::collection_has_tokens(id) {226			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());227		}228229		// =========230231		PalletCommon::destroy_collection(collection.0, sender)?;232233		<TotalSupply<T>>::remove(id);234		<Balance<T>>::remove_prefix((id,), None);235		<Allowance<T>>::remove_prefix((id,), None);236		Ok(())237	}238239	///Checks if collection has tokens. Return `true` if it has.240	fn collection_has_tokens(collection_id: CollectionId) -> bool {241		<TotalSupply<T>>::get(collection_id) != 0242	}243244	/// Burns the specified amount of the token. If the token balance245	/// or total supply is less than the given value,246	/// it will return [DispatchError].247	pub fn burn(248		collection: &FungibleHandle<T>,249		owner: &T::CrossAccountId,250		amount: u128,251	) -> DispatchResult {252		let total_supply = <TotalSupply<T>>::get(collection.id)253			.checked_sub(amount)254			.ok_or(<CommonError<T>>::TokenValueTooLow)?;255256		let balance = <Balance<T>>::get((collection.id, owner))257			.checked_sub(amount)258			.ok_or(<CommonError<T>>::TokenValueTooLow)?;259260		if collection.permissions.access() == AccessMode::AllowList {261			collection.check_allowlist(owner)?;262		}263264		// =========265266		if balance == 0 {267			<Balance<T>>::remove((collection.id, owner));268			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());269		} else {270			<Balance<T>>::insert((collection.id, owner), balance);271		}272		<TotalSupply<T>>::insert(collection.id, total_supply);273274		<PalletEvm<T>>::deposit_log(275			ERC20Events::Transfer {276				from: *owner.as_eth(),277				to: H160::default(),278				value: amount.into(),279			}280			.to_log(collection_id_to_address(collection.id)),281		);282		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(283			collection.id,284			TokenId::default(),285			owner.clone(),286			amount,287		));288		Ok(())289	}290291	/// Transfers the specified amount of tokens. Will check that292	/// the transfer is allowed for the token.293	///294	/// - `from`: Owner of tokens to transfer.295	/// - `to`: Recepient of transfered tokens.296	/// - `amount`: Amount of tokens to transfer.297	/// - `collection`: Collection that contains the token298	pub fn transfer(299		collection: &FungibleHandle<T>,300		from: &T::CrossAccountId,301		to: &T::CrossAccountId,302		amount: u128,303		nesting_budget: &dyn Budget,304	) -> DispatchResult {305		ensure!(306			collection.limits.transfers_enabled(),307			<CommonError<T>>::TransferNotAllowed,308		);309310		if collection.permissions.access() == AccessMode::AllowList {311			collection.check_allowlist(from)?;312			collection.check_allowlist(to)?;313		}314		<PalletCommon<T>>::ensure_correct_receiver(to)?;315316		let balance_from = <Balance<T>>::get((collection.id, from))317			.checked_sub(amount)318			.ok_or(<CommonError<T>>::TokenValueTooLow)?;319		let balance_to = if from != to {320			Some(321				<Balance<T>>::get((collection.id, to))322					.checked_add(amount)323					.ok_or(ArithmeticError::Overflow)?,324			)325		} else {326			None327		};328329		// =========330331		<PalletStructure<T>>::nest_if_sent_to_token(332			from.clone(),333			to,334			collection.id,335			TokenId::default(),336			nesting_budget,337		)?;338339		if let Some(balance_to) = balance_to {340			// from != to341			if balance_from == 0 {342				<Balance<T>>::remove((collection.id, from));343				<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());344			} else {345				<Balance<T>>::insert((collection.id, from), balance_from);346			}347			<Balance<T>>::insert((collection.id, to), balance_to);348		}349350		<PalletEvm<T>>::deposit_log(351			ERC20Events::Transfer {352				from: *from.as_eth(),353				to: *to.as_eth(),354				value: amount.into(),355			}356			.to_log(collection_id_to_address(collection.id)),357		);358		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(359			collection.id,360			TokenId::default(),361			from.clone(),362			to.clone(),363			amount,364		));365		Ok(())366	}367368	/// Minting tokens for multiple IDs.369	/// See [`create_item`][`Pallet::create_item`] for more details.370	pub fn create_multiple_items(371		collection: &FungibleHandle<T>,372		sender: &T::CrossAccountId,373		data: BTreeMap<T::CrossAccountId, u128>,374		nesting_budget: &dyn Budget,375	) -> DispatchResult {376		if !collection.is_owner_or_admin(sender) {377			ensure!(378				collection.permissions.mint_mode(),379				<CommonError<T>>::PublicMintingNotAllowed380			);381			collection.check_allowlist(sender)?;382383			for (owner, _) in data.iter() {384				collection.check_allowlist(owner)?;385			}386		}387388		let total_supply = data389			.iter()390			.map(|(_, v)| *v)391			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {392				acc.checked_add(v)393			})394			.ok_or(ArithmeticError::Overflow)?;395396		let mut balances = data;397		for (k, v) in balances.iter_mut() {398			*v = <Balance<T>>::get((collection.id, &k))399				.checked_add(*v)400				.ok_or(ArithmeticError::Overflow)?;401		}402403		for (to, _) in balances.iter() {404			<PalletStructure<T>>::check_nesting(405				sender.clone(),406				to,407				collection.id,408				TokenId::default(),409				nesting_budget,410			)?;411		}412413		// =========414415		<TotalSupply<T>>::insert(collection.id, total_supply);416		for (user, amount) in balances {417			<Balance<T>>::insert((collection.id, &user), amount);418			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(419				&user,420				collection.id,421				TokenId::default(),422			);423			<PalletEvm<T>>::deposit_log(424				ERC20Events::Transfer {425					from: H160::default(),426					to: *user.as_eth(),427					value: amount.into(),428				}429				.to_log(collection_id_to_address(collection.id)),430			);431			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(432				collection.id,433				TokenId::default(),434				user.clone(),435				amount,436			));437		}438439		Ok(())440	}441442	fn set_allowance_unchecked(443		collection: &FungibleHandle<T>,444		owner: &T::CrossAccountId,445		spender: &T::CrossAccountId,446		amount: u128,447	) {448		if amount == 0 {449			<Allowance<T>>::remove((collection.id, owner, spender));450		} else {451			<Allowance<T>>::insert((collection.id, owner, spender), amount);452		}453454		<PalletEvm<T>>::deposit_log(455			ERC20Events::Approval {456				owner: *owner.as_eth(),457				spender: *spender.as_eth(),458				value: amount.into(),459			}460			.to_log(collection_id_to_address(collection.id)),461		);462		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(463			collection.id,464			TokenId(0),465			owner.clone(),466			spender.clone(),467			amount,468		));469	}470471	/// Set allowance for the spender to `transfer` or `burn` owner's tokens.472	///473	/// - `collection`: Collection that contains the token474	/// - `owner`: Owner of tokens that sets the allowance.475	/// - `spender`: Recipient of the allowance rights.476	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.477	pub fn set_allowance(478		collection: &FungibleHandle<T>,479		owner: &T::CrossAccountId,480		spender: &T::CrossAccountId,481		amount: u128,482	) -> DispatchResult {483		if collection.permissions.access() == AccessMode::AllowList {484			collection.check_allowlist(owner)?;485			collection.check_allowlist(spender)?;486		}487488		if <Balance<T>>::get((collection.id, owner)) < amount {489			ensure!(490				collection.ignores_owned_amount(owner),491				<CommonError<T>>::CantApproveMoreThanOwned492			);493		}494495		// =========496497		Self::set_allowance_unchecked(collection, owner, spender, amount);498		Ok(())499	}500501	/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.502	/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.503	///504	/// - `collection`: Collection that contains the token.505	/// - `spender`: CrossAccountId who has the allowance rights.506	/// - `from`: The owner of the tokens who sets the allowance.507	/// - `amount`: Amount of tokens by which the allowance sholud be reduced.508	fn check_allowed(509		collection: &FungibleHandle<T>,510		spender: &T::CrossAccountId,511		from: &T::CrossAccountId,512		amount: u128,513		nesting_budget: &dyn Budget,514	) -> Result<Option<u128>, DispatchError> {515		if spender.conv_eq(from) {516			return Ok(None);517		}518		if collection.permissions.access() == AccessMode::AllowList {519			// `from`, `to` checked in [`transfer`]520			collection.check_allowlist(spender)?;521		}522		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {523			// TODO: should collection owner be allowed to perform this transfer?524			ensure!(525				<PalletStructure<T>>::check_indirectly_owned(526					spender.clone(),527					source.0,528					source.1,529					None,530					nesting_budget531				)?,532				<CommonError<T>>::ApprovedValueTooLow,533			);534			return Ok(None);535		}536		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);537		if allowance.is_none() {538			ensure!(539				collection.ignores_allowance(spender),540				<CommonError<T>>::ApprovedValueTooLow541			);542		}543544		Ok(allowance)545	}546547	/// Transfer fungible tokens from one account to another.548	/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.549	/// The owner should set allowance for the spender to transfer pieces.550	///	See [`set_allowance`][`Pallet::set_allowance`] for more details.551552	pub fn transfer_from(553		collection: &FungibleHandle<T>,554		spender: &T::CrossAccountId,555		from: &T::CrossAccountId,556		to: &T::CrossAccountId,557		amount: u128,558		nesting_budget: &dyn Budget,559	) -> DispatchResult {560		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;561562		// =========563564		Self::transfer(collection, from, to, amount, nesting_budget)?;565		if let Some(allowance) = allowance {566			Self::set_allowance_unchecked(collection, from, spender, allowance);567		}568		Ok(())569	}570571	/// Burn fungible tokens from the account.572	///573	/// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should574	/// set allowance for the spender to burn tokens.575	/// See [`set_allowance`][`Pallet::set_allowance`] for more details.576	pub fn burn_from(577		collection: &FungibleHandle<T>,578		spender: &T::CrossAccountId,579		from: &T::CrossAccountId,580		amount: u128,581		nesting_budget: &dyn Budget,582	) -> DispatchResult {583		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;584585		// =========586587		Self::burn(collection, from, amount)?;588		if let Some(allowance) = allowance {589			Self::set_allowance_unchecked(collection, from, spender, allowance);590		}591		Ok(())592	}593594	///	Creates fungible token.595	///596	/// The sender should be the owner/admin of the collection or collection should be configured597	/// to allow public minting.598	///599	/// - `data`: Contains user who will become the owners of the tokens and amount600	///   of tokens he will receive.601	pub fn create_item(602		collection: &FungibleHandle<T>,603		sender: &T::CrossAccountId,604		data: CreateItemData<T>,605		nesting_budget: &dyn Budget,606	) -> DispatchResult {607		Self::create_multiple_items(608			collection,609			sender,610			[(data.0, data.1)].into_iter().collect(),611			nesting_budget,612		)613	}614615	/// Returns 10 tokens owners in no particular order616	///617	/// There is no direct way to get token holders in ascending order,618	/// since `iter_prefix` returns values in no particular order.619	/// Therefore, getting the 10 largest holders with a large value of holders620	/// can lead to impact memory allocation + sorting with  `n * log (n)`.621	pub fn token_owners(622		collection: CollectionId,623		_token: TokenId,624	) -> Option<Vec<T::CrossAccountId>> {625		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))626			.map(|(owner, _amount)| owner)627			.take(10)628			.collect();629630		if res.is_empty() {631			None632		} else {633			Some(res)634		}635	}636}
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -560,10 +560,7 @@
 		<Pallet<T>>::create_item(
 			self,
 			&caller,
-			CreateItemData::<T> {
-				users,
-				properties,
-			},
+			CreateItemData::<T> { users, properties },
 			&budget,
 		)
 		.map_err(dispatch_to_evm::<T>)?;
modifiedtests/src/createItem.test.tsdiffbeforeafterboth
--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -14,7 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import {default as usingApi} from './substrate/substrate-api';
+import {default as usingApi, executeTransaction} from './substrate/substrate-api';
 import chai from 'chai';
 import {IKeyringPair} from '@polkadot/types/types';
 import {
@@ -26,6 +26,9 @@
   createItemWithPropsExpectFailure,
   createCollection,
   transferExpectSuccess,
+  itApi,
+  normalizeAccountId,
+  getCreateItemResult,
 } from './util/helpers';
 
 const expect = chai.expect;
@@ -50,6 +53,32 @@
     const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});
     await createItemExpectSuccess(alice, newCollectionID, createMode);
   });
+  itApi('Check events on create new item in Fungible collection', async ({api}) => {
+    const createMode = 'Fungible';
+    
+    const newCollectionID = (await createCollection(api, alice, {mode: {type: createMode, decimalPoints: 0}})).collectionId;
+    
+    const to = normalizeAccountId(alice);
+    {
+      const createData = {fungible: {value: 100}};
+      const tx = api.tx.unique.createItem(newCollectionID, to, createData as any);
+      const events = await executeTransaction(api, alice, tx);
+      const result = getCreateItemResult(events);
+      expect(result.amount).to.be.equal(100);
+      expect(result.collectionId).to.be.equal(newCollectionID);
+      expect(result.recipient).to.be.deep.equal(to);
+    }
+    {
+      const createData = {fungible: {value: 50}};
+      const tx = api.tx.unique.createItem(newCollectionID, to, createData as any);
+      const events = await executeTransaction(api, alice, tx);
+      const result = getCreateItemResult(events);
+      expect(result.amount).to.be.equal(50);
+      expect(result.collectionId).to.be.equal(newCollectionID);
+      expect(result.recipient).to.be.deep.equal(to);
+    }
+
+  });
   it('Create new item in ReFungible collection', async () => {
     const createMode = 'ReFungible';
     const newCollectionID = await createCollectionExpectSuccess({mode: {type: createMode}});
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -248,22 +248,23 @@
 }
 
 export function getCreateItemResult(events: EventRecord[]): CreateItemResult {
-  const genericResult = getGenericResult<[number, number, CrossAccountId?]>(events, 'common', 'ItemCreated', (data) => [
-    parseInt(data[0].toString(), 10),
-    parseInt(data[1].toString(), 10),
-    normalizeAccountId(data[2].toJSON() as any),
-  ]);
-
-  if (genericResult.data == null) genericResult.data = [0, 0];
-
-  const result: CreateItemResult = {
-    success: genericResult.success,
-    collectionId: genericResult.data[0],
-    itemId: genericResult.data[1],
-    recipient: genericResult.data![2],
-  };
+  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));
   
-  return result;
+  if (genericResult.data == null) 
+    return {
+      success: genericResult.success,
+      collectionId: 0,
+      itemId: 0,
+      amount: 0,
+    };
+  else 
+    return {
+      success: genericResult.success,
+      collectionId: genericResult.data[0] as number,
+      itemId: genericResult.data[1] as number,
+      recipient: normalizeAccountId(genericResult.data![2] as any),
+      amount: genericResult.data[3] as number,
+    };
 }
 
 export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {
@@ -1699,3 +1700,14 @@
 
   return result.success;
 }
+
+export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
+  let i: any = it;
+  if (opts.only) i = i.only;
+  else if (opts.skip) i = i.skip;
+  i(name, async () => {
+    await usingApi(async (api, privateKeyWrapper) => {
+      await cb({api, privateKeyWrapper});
+    });
+  });
+}