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

difftreelog

refac: incapsulate CollectionHandler into CollectionDispatch

Trubnikov Sergey2023-04-24parent: #361b516.patch.diff
in: master

13 files changed

modifiedpallets/balances-adapter/src/lib.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/lib.rs
+++ b/pallets/balances-adapter/src/lib.rs
@@ -3,6 +3,7 @@
 #![warn(missing_docs)]
 
 extern crate alloc;
+use frame_support::sp_runtime::DispatchResult;
 pub use pallet::*;
 use pallet_common::CollectionHandle;
 use pallet_evm_coder_substrate::{WithRecorder, SubstrateRecorder};
@@ -10,24 +11,23 @@
 pub mod common;
 pub mod erc;
 
-pub struct NativeFungibleHandle<T: Config>(CollectionHandle<T>);
+pub struct NativeFungibleHandle<T: Config>(SubstrateRecorder<T>);
 impl<T: Config> NativeFungibleHandle<T> {
-	pub fn cast(inner: CollectionHandle<T>) -> Self {
-		Self(inner)
+	pub fn new() -> NativeFungibleHandle<T> {
+		Self(SubstrateRecorder::new(u64::MAX))
 	}
 
-	/// Casts [`NativeFungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].
-	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
-		self.0
+	pub fn check_is_internal(&self) -> DispatchResult {
+		Ok(())
 	}
 }
 
 impl<T: Config> WithRecorder<T> for NativeFungibleHandle<T> {
 	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
-		&self.0.recorder
+		&self.0
 	}
 	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {
-		self.0.recorder
+		self.0
 	}
 }
 #[frame_support::pallet]
modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -34,16 +34,11 @@
 	collection: CollectionId,
 	call: C,
 ) -> DispatchResultWithPostInfo {
-	let handle =
-		CollectionHandle::try_get(collection).map_err(|error| DispatchErrorWithPostInfo {
-			post_info: PostDispatchInfo {
-				actual_weight: Some(dispatch_weight::<T>()),
-				pays_fee: Pays::Yes,
-			},
-			error,
-		})?;
-	handle
-		.check_is_internal()
+	let dispatched = T::CollectionDispatch::dispatch(collection)
+		.and_then(|dispatched| {
+			dispatched.check_is_internal()?;
+			Ok(dispatched)
+		})
 		.map_err(|error| DispatchErrorWithPostInfo {
 			post_info: PostDispatchInfo {
 				actual_weight: Some(dispatch_weight::<T>()),
@@ -51,7 +46,6 @@
 			},
 			error,
 		})?;
-	let dispatched = T::CollectionDispatch::dispatch(handle);
 	let mut result = call(dispatched.as_dyn());
 	match &mut result {
 		Ok(PostDispatchInfo {
@@ -72,6 +66,8 @@
 
 /// Interface for working with different collections through the dispatcher.
 pub trait CollectionDispatch<T: Config> {
+	fn check_is_internal(&self) -> DispatchResult;
+
 	/// Create a collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
 	///
 	/// * `sender` - The user who will become the owner of the collection.
@@ -92,7 +88,9 @@
 	/// Get a specialized collection from the handle.
 	///
 	/// * `handle` - Collection handle.
-	fn dispatch(handle: CollectionHandle<T>) -> Self;
+	fn dispatch(collection_id: CollectionId) -> Result<Self, DispatchError>
+	where
+		Self: Sized;
 
 	/// Get the implementation of [`CommonCollectionOperations`].
 	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T>;
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -77,6 +77,14 @@
 	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult>;
 }
 
+impl CommonEvmHandler for () {
+	const CODE: &'static [u8] = &[];
+
+	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
+		None
+	}
+}
+
 /// @title A contract that allows you to work with collections.
 #[solidity_interface(name = Collection, enum(derive(PreDispatch)), enum_attr(weight))]
 impl<T: Config> CollectionHandle<T>
modifiedpallets/structure/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -42,7 +42,7 @@
 			},
 			CollectionFlags::default(),
 		)?;
-		let dispatch = T::CollectionDispatch::dispatch(CollectionHandle::try_get(CollectionId(1))?);
+		let dispatch = T::CollectionDispatch::dispatch(CollectionId(1))?;
 		let dispatch = dispatch.as_dyn();
 
 		dispatch.create_item(caller_cross.clone(), caller_cross.clone(), CreateItemData::NFT(CreateNftData::default()), &Unlimited)?;
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -155,11 +155,10 @@
 		token: TokenId,
 	) -> Result<Parent<T::CrossAccountId>, DispatchError> {
 		// TODO: Reduce cost by not reading collection config
-		let handle = match CollectionHandle::try_get(collection) {
+		let handle = match T::CollectionDispatch::dispatch(collection) {
 			Ok(v) => v,
 			Err(_) => return Ok(Parent::TokenNotFound),
 		};
-		let handle = T::CollectionDispatch::dispatch(handle);
 		let handle = handle.as_dyn();
 
 		Ok(match handle.token_owner(token) {
@@ -279,8 +278,7 @@
 		self_budget: &dyn Budget,
 		breadth_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
-		let handle = <CollectionHandle<T>>::try_get(collection)?;
-		let dispatch = T::CollectionDispatch::dispatch(handle);
+		let dispatch = T::CollectionDispatch::dispatch(collection)?;
 		let dispatch = dispatch.as_dyn();
 		dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)
 	}
@@ -404,10 +402,8 @@
 		let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {
 			return Ok(())
 		};
-
-		let handle = <CollectionHandle<T>>::try_get(collection)?;
 
-		let dispatch = T::CollectionDispatch::dispatch(handle);
+		let dispatch = T::CollectionDispatch::dispatch(collection)?;
 		let dispatch = dispatch.as_dyn();
 
 		action(dispatch, token)
modifiedruntime/common/dispatch.rsdiffbeforeafterboth
--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -50,6 +50,7 @@
 	Refungible(RefungibleHandle<T>),
 	NativeFungible(NativeFungibleHandle<T>),
 }
+
 impl<T> CollectionDispatch<T> for CollectionDispatchT<T>
 where
 	T: pallet_common::Config
@@ -59,6 +60,15 @@
 		+ pallet_refungible::Config
 		+ pallet_balances_adapter::Config,
 {
+	fn check_is_internal(&self) -> DispatchResult {
+		match self {
+			Self::Fungible(h) => h.check_is_internal(),
+			Self::Nonfungible(h) => h.check_is_internal(),
+			Self::Refungible(h) => h.check_is_internal(),
+			Self::NativeFungible(h) => h.check_is_internal(),
+		}
+	}
+
 	fn create(
 		sender: T::CrossAccountId,
 		payer: T::CrossAccountId,
@@ -104,18 +114,17 @@
 		Ok(())
 	}
 
-	fn dispatch(handle: CollectionHandle<T>) -> Self {
-		match handle.mode {
-			CollectionMode::Fungible(_) => {
-				if handle.id != up_data_structs::CollectionId(0) {
-					Self::Fungible(FungibleHandle::cast(handle))
-				} else {
-					Self::NativeFungible(NativeFungibleHandle::cast(handle))
-				}
-			}
+	fn dispatch(collection_id: CollectionId) -> Result<Self, DispatchError> {
+		if collection_id == CollectionId(0) {
+			return Ok(Self::NativeFungible(NativeFungibleHandle::new()));
+		}
+
+		let handle = <CollectionHandle<T>>::try_get(collection_id)?;
+		Ok(match handle.mode {
+			CollectionMode::Fungible(_) => Self::Fungible(FungibleHandle::cast(handle)),
 			CollectionMode::NFT => Self::Nonfungible(NonfungibleHandle::cast(handle)),
 			CollectionMode::ReFungible => Self::Refungible(RefungibleHandle::cast(handle)),
-		}
+		})
 	}
 
 	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T> {
@@ -172,15 +181,19 @@
 	}
 	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
 		if let Some(collection_id) = map_eth_to_id(&handle.code_address()) {
-			let collection =
-				<CollectionHandle<T>>::new_with_gas_limit(collection_id, handle.remaining_gas())?;
-			let dispatched = Self::dispatch(collection);
+			if collection_id == CollectionId(0) {
+				<NativeFungibleHandle<T>>::new().call(handle)
+			} else {
+				let collection = <CollectionHandle<T>>::new_with_gas_limit(
+					collection_id,
+					handle.remaining_gas(),
+				)?;
 
-			match dispatched {
-				Self::Fungible(h) => h.call(handle),
-				Self::Nonfungible(h) => h.call(handle),
-				Self::Refungible(h) => h.call(handle),
-				Self::NativeFungible(h) => h.call(handle),
+				match collection.mode {
+					CollectionMode::Fungible(_) => FungibleHandle::cast(collection).call(handle),
+					CollectionMode::NFT => NonfungibleHandle::cast(collection).call(handle),
+					CollectionMode::ReFungible => RefungibleHandle::cast(collection).call(handle),
+				}
 			}
 		} else if let Some((collection_id, token_id)) =
 			<T as pallet_common::Config>::EvmTokenAddressMapping::address_to_token(
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -17,7 +17,7 @@
 #[macro_export]
 macro_rules! dispatch_unique_runtime {
 	($collection:ident.$method:ident($($name:ident),*) $($rest:tt)*) => {{
-		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
+		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch($collection)?;
 		let dispatch = collection.as_dyn();
 
 		Ok::<_, DispatchError>(dispatch.$method($($name),*) $($rest)*)
modifiedtests/src/eth/fungible.test.tsdiffbeforeafterboth
before · tests/src/eth/fungible.test.ts
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/>.1617import {expect, itEth, usingEthPlaygrounds} from './util';18import {IKeyringPair} from '@polkadot/types/types';1920describe('Fungible: Plain calls', () => {21  let donor: IKeyringPair;22  let alice: IKeyringPair;23  let owner: IKeyringPair;2425  before(async function() {26    await usingEthPlaygrounds(async (helper, privateKey) => {27      donor = await privateKey({url: import.meta.url});28      [alice, owner] = await helper.arrange.createAccounts([30n, 20n], donor);29    });30  });3132  [33    'substrate' as const,34    'ethereum' as const,35  ].map(testCase => {36    itEth.only(`Can perform mintCross() for ${testCase} address`, async ({helper}) => {37      // 1. Create receiver depending on the test case:38      const receiverEth = helper.eth.createAccount();39      const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);40      const receiverSub = owner;41      const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(owner);4243      const ethOwner = await helper.eth.createAccountWithBalance(donor);44      const collection = await helper.ft.mintCollection(alice);45      await collection.addAdmin(alice, {Ethereum: ethOwner});4647      const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);48      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', ethOwner);4950      // 2. Mint tokens:51      const result = await collectionEvm.methods.mintCross(testCase === 'ethereum' ? receiverCrossEth : receiverCrossSub, 100).send();5253      const event = result.events.Transfer;54      expect(event.address).to.equal(collectionAddress);55      expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');56      expect(event.returnValues.to).to.equal(testCase === 'ethereum' ? receiverEth : helper.address.substrateToEth(receiverSub.address));57      expect(event.returnValues.value).to.equal('100');5859      // 3. Get balance depending on the test case:60      let balance;61      if (testCase === 'ethereum') balance = await collection.getBalance({Ethereum: receiverEth});62      else if (testCase === 'substrate') balance = await collection.getBalance({Substrate: receiverSub.address});63      // 3.1 Check balance:64      expect(balance).to.eq(100n);65    });66  });6768  itEth('Can perform mintBulk()', async ({helper}) => {69    const owner = await helper.eth.createAccountWithBalance(donor);70    const bulkSize = 3;71    const receivers = [...new Array(bulkSize)].map(() => helper.eth.createAccount());72    const collection = await helper.ft.mintCollection(alice);73    await collection.addAdmin(alice, {Ethereum: owner});7475    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);76    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);7778    const result = await contract.methods.mintBulk(Array.from({length: bulkSize}, (_, i) => (79      [receivers[i], (i + 1) * 10]80    ))).send();81    const events = result.events.Transfer.sort((a: any, b: any) => +a.returnValues.value - b.returnValues.value);82    for (let i = 0; i < bulkSize; i++) {83      const event = events[i];84      expect(event.address).to.equal(collectionAddress);85      expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');86      expect(event.returnValues.to).to.equal(receivers[i]);87      expect(event.returnValues.value).to.equal(String(10 * (i + 1)));88    }89  });9091  // Soft-deprecated92  itEth('Can perform burn()', async ({helper}) => {93    const owner = await helper.eth.createAccountWithBalance(donor);94    const receiver = await helper.eth.createAccountWithBalance(donor);95    const collection = await helper.ft.mintCollection(alice);96    await collection.addAdmin(alice, {Ethereum: owner});9798    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);99    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner, true);100    await contract.methods.mint(receiver, 100).send();101102    const result = await contract.methods.burnFrom(receiver, 49).send({from: receiver});103104    const event = result.events.Transfer;105    expect(event.address).to.equal(collectionAddress);106    expect(event.returnValues.from).to.equal(receiver);107    expect(event.returnValues.to).to.equal('0x0000000000000000000000000000000000000000');108    expect(event.returnValues.value).to.equal('49');109110    const balance = await contract.methods.balanceOf(receiver).call();111    expect(balance).to.equal('51');112  });113114  itEth('Can perform approve()', async ({helper}) => {115    const owner = await helper.eth.createAccountWithBalance(donor);116    const spender = helper.eth.createAccount();117    const collection = await helper.ft.mintCollection(alice);118    await collection.mint(alice, 200n, {Ethereum: owner});119120    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);121    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);122123    {124      const result = await contract.methods.approve(spender, 100).send({from: owner});125126      const event = result.events.Approval;127      expect(event.address).to.be.equal(collectionAddress);128      expect(event.returnValues.owner).to.be.equal(owner);129      expect(event.returnValues.spender).to.be.equal(spender);130      expect(event.returnValues.value).to.be.equal('100');131    }132133    {134      const allowance = await contract.methods.allowance(owner, spender).call();135      expect(+allowance).to.equal(100);136    }137    {138      const ownerCross = helper.ethCrossAccount.fromAddress(owner);139      const spenderCross = helper.ethCrossAccount.fromAddress(spender);140      const allowance = await contract.methods.allowanceCross(ownerCross, spenderCross).call();141      expect(+allowance).to.equal(100);142    }143  });144145  itEth('Can perform approveCross()', async ({helper}) => {146    const owner = await helper.eth.createAccountWithBalance(donor);147    const spender = helper.eth.createAccount();148    const spenderSub = (await helper.arrange.createAccounts([1n], donor))[0];149    const spenderCrossEth = helper.ethCrossAccount.fromAddress(spender);150    const spenderCrossSub = helper.ethCrossAccount.fromKeyringPair(spenderSub);151152153    const collection = await helper.ft.mintCollection(alice);154    await collection.mint(alice, 200n, {Ethereum: owner});155156    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);157    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);158159    {160      const result = await contract.methods.approveCross(spenderCrossEth, 100).send({from: owner});161      const event = result.events.Approval;162      expect(event.address).to.be.equal(collectionAddress);163      expect(event.returnValues.owner).to.be.equal(owner);164      expect(event.returnValues.spender).to.be.equal(spender);165      expect(event.returnValues.value).to.be.equal('100');166    }167168    {169      const allowance = await contract.methods.allowance(owner, spender).call();170      expect(+allowance).to.equal(100);171    }172173174    {175      const result = await contract.methods.approveCross(spenderCrossSub, 100).send({from: owner});176      const event = result.events.Approval;177      expect(event.address).to.be.equal(collectionAddress);178      expect(event.returnValues.owner).to.be.equal(owner);179      expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(spenderSub.address));180      expect(event.returnValues.value).to.be.equal('100');181    }182183    {184      const allowance = await collection.getApprovedTokens({Ethereum: owner}, {Substrate: spenderSub.address});185      expect(allowance).to.equal(100n);186    }187188    {189      //TO-DO expect with future allowanceCross(owner, spenderCrossEth).call()190    }191  });192193  itEth('Non-owner and non admin cannot approveCross', async ({helper}) => {194    const nonOwner = await helper.eth.createAccountWithBalance(donor);195    const nonOwnerCross = helper.ethCrossAccount.fromAddress(nonOwner);196    const owner = await helper.eth.createAccountWithBalance(donor);197    const collection = await helper.ft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});198    await collection.mint(alice, 100n, {Ethereum: owner});199200    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);201    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);202203    await expect(collectionEvm.methods.approveCross(nonOwnerCross, 20).call({from: nonOwner})).to.be.rejectedWith('CantApproveMoreThanOwned');204  });205206207  itEth('Can perform burnFromCross()', async ({helper}) => {208    const sender = await helper.eth.createAccountWithBalance(donor);209210    const collection = await helper.ft.mintCollection(owner, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);211212    await collection.mint(owner, 200n, {Substrate: owner.address});213    await collection.approveTokens(owner, {Ethereum: sender}, 100n);214215    const address = helper.ethAddress.fromCollectionId(collection.collectionId);216    const contract = await helper.ethNativeContract.collection(address, 'ft');217218    const fromBalanceBefore = await collection.getBalance({Substrate: owner.address});219220    const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);221    const result = await contract.methods.burnFromCross(ownerCross, 49).send({from: sender});222    const events = result.events;223224    expect(events).to.be.like({225      Transfer: {226        address: helper.ethAddress.fromCollectionId(collection.collectionId),227        event: 'Transfer',228        returnValues: {229          from: helper.address.substrateToEth(owner.address),230          to: '0x0000000000000000000000000000000000000000',231          value: '49',232        },233      },234      Approval: {235        address: helper.ethAddress.fromCollectionId(collection.collectionId),236        returnValues: {237          owner: helper.address.substrateToEth(owner.address),238          spender: sender,239          value: '51',240        },241        event: 'Approval',242      },243    });244245    const fromBalanceAfter = await collection.getBalance({Substrate: owner.address});246    expect(fromBalanceBefore - fromBalanceAfter).to.be.eq(49n);247  });248249  itEth('Can perform transferFrom()', async ({helper}) => {250    const owner = await helper.eth.createAccountWithBalance(donor);251    const spender = await helper.eth.createAccountWithBalance(donor);252    const receiver = helper.eth.createAccount();253    const collection = await helper.ft.mintCollection(alice);254    await collection.mint(alice, 200n, {Ethereum: owner});255256    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);257    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);258259    await contract.methods.approve(spender, 100).send();260261    {262      const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: spender});263264      let event = result.events.Transfer;265      expect(event.address).to.be.equal(collectionAddress);266      expect(event.returnValues.from).to.be.equal(owner);267      expect(event.returnValues.to).to.be.equal(receiver);268      expect(event.returnValues.value).to.be.equal('49');269270      event = result.events.Approval;271      expect(event.address).to.be.equal(collectionAddress);272      expect(event.returnValues.owner).to.be.equal(owner);273      expect(event.returnValues.spender).to.be.equal(spender);274      expect(event.returnValues.value).to.be.equal('51');275    }276277    {278      const balance = await contract.methods.balanceOf(receiver).call();279      expect(+balance).to.equal(49);280    }281282    {283      const balance = await contract.methods.balanceOf(owner).call();284      expect(+balance).to.equal(151);285    }286  });287288  itEth('Can perform transferCross()', async ({helper}) => {289    const sender = await helper.eth.createAccountWithBalance(donor);290    const receiverEth = await helper.eth.createAccountWithBalance(donor);291    const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);292    const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(donor);293    const collection = await helper.ft.mintCollection(alice);294    await collection.mint(alice, 200n, {Ethereum: sender});295296    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);297    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', sender);298299    {300      // Can transferCross to ethereum address:301      const result = await collectionEvm.methods.transferCross(receiverCrossEth, 50).send({from: sender});302      // Check events:303      const event = result.events.Transfer;304      expect(event.address).to.be.equal(collectionAddress);305      expect(event.returnValues.from).to.be.equal(sender);306      expect(event.returnValues.to).to.be.equal(receiverEth);307      expect(event.returnValues.value).to.be.equal('50');308      // Sender's balance decreased:309      const ownerBalance = await collectionEvm.methods.balanceOf(sender).call();310      expect(+ownerBalance).to.equal(150);311      // Receiver's balance increased:312      const receiverBalance = await collectionEvm.methods.balanceOf(receiverEth).call();313      expect(+receiverBalance).to.equal(50);314    }315316    {317      // Can transferCross to substrate address:318      const result = await collectionEvm.methods.transferCross(receiverCrossSub, 50).send({from: sender});319      // Check events:320      const event = result.events.Transfer;321      expect(event.address).to.be.equal(collectionAddress);322      expect(event.returnValues.from).to.be.equal(sender);323      expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(donor.address));324      expect(event.returnValues.value).to.be.equal('50');325      // Sender's balance decreased:326      const senderBalance = await collection.getBalance({Ethereum: sender});327      expect(senderBalance).to.equal(100n);328      // Receiver's balance increased:329      const balance = await collection.getBalance({Substrate: donor.address});330      expect(balance).to.equal(50n);331    }332  });333334  ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} incorrect amount`, async ({helper}) => {335    const sender = await helper.eth.createAccountWithBalance(donor);336    const receiverEth = await helper.eth.createAccountWithBalance(donor);337    const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);338    const BALANCE = 200n;339    const BALANCE_TO_TRANSFER = BALANCE + 100n;340341    const collection = await helper.ft.mintCollection(alice);342    await collection.mint(alice, BALANCE, {Ethereum: sender});343    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);344    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', sender);345346    // 1. Cannot transfer more than have347    const receiver = testCase === 'transfer' ? receiverEth : receiverCrossEth;348    await expect(collectionEvm.methods[testCase](receiver, BALANCE_TO_TRANSFER).send({from: sender})).to.be.rejected;349    // 2. Zero transfer allowed (EIP-20):350    await collectionEvm.methods[testCase](receiver, 0n).send({from: sender});351  }));352353354  itEth('Can perform transfer()', async ({helper}) => {355    const owner = await helper.eth.createAccountWithBalance(donor);356    const receiver = await helper.eth.createAccountWithBalance(donor);357    const collection = await helper.ft.mintCollection(alice);358    await collection.mint(alice, 200n, {Ethereum: owner});359360    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);361    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);362363    {364      const result = await contract.methods.transfer(receiver, 50).send({from: owner});365366      const event = result.events.Transfer;367      expect(event.address).to.be.equal(collectionAddress);368      expect(event.returnValues.from).to.be.equal(owner);369      expect(event.returnValues.to).to.be.equal(receiver);370      expect(event.returnValues.value).to.be.equal('50');371    }372373    {374      const balance = await contract.methods.balanceOf(owner).call();375      expect(+balance).to.equal(150);376    }377378    {379      const balance = await contract.methods.balanceOf(receiver).call();380      expect(+balance).to.equal(50);381    }382  });383384  itEth('Can perform transferFromCross()', async ({helper}) => {385    const sender = await helper.eth.createAccountWithBalance(donor);386387    const collection = await helper.ft.mintCollection(owner, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);388389    const receiver = helper.eth.createAccount();390391    await collection.mint(owner, 200n, {Substrate: owner.address});392    await collection.approveTokens(owner, {Ethereum: sender}, 100n);393394    const address = helper.ethAddress.fromCollectionId(collection.collectionId);395    const contract = await helper.ethNativeContract.collection(address, 'ft');396397    const from = helper.ethCrossAccount.fromKeyringPair(owner);398    const to = helper.ethCrossAccount.fromAddress(receiver);399400    const fromBalanceBefore = await collection.getBalance({Substrate: owner.address});401    const toBalanceBefore = await collection.getBalance({Ethereum: receiver});402403    const result = await contract.methods.transferFromCross(from, to, 51).send({from: sender});404405    expect(result.events).to.be.like({406      Transfer: {407        address,408        event: 'Transfer',409        returnValues: {410          from: helper.address.substrateToEth(owner.address),411          to: receiver,412          value: '51',413        },414      },415      Approval: {416        address,417        event: 'Approval',418        returnValues: {419          owner: helper.address.substrateToEth(owner.address),420          spender: sender,421          value: '49',422        },423      }});424425    const fromBalanceAfter = await collection.getBalance({Substrate: owner.address});426    expect(fromBalanceBefore - fromBalanceAfter).to.be.eq(51n);427    const toBalanceAfter = await collection.getBalance({Ethereum: receiver});428    expect(toBalanceAfter - toBalanceBefore).to.be.eq(51n);429  });430431  itEth('Check balanceOfCross()', async ({helper}) => {432    const collection = await helper.ft.mintCollection(alice, {});433    const owner = await helper.ethCrossAccount.createAccountWithBalance(donor);434    const other = await helper.ethCrossAccount.createAccountWithBalance(donor);435    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);436    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner.eth);437438    expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('0');439    expect(await collectionEvm.methods.balanceOfCross(other).call({from: owner.eth})).to.be.eq('0');440441    await collection.mint(alice, 100n, {Ethereum: owner.eth});442    expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('100');443    expect(await collectionEvm.methods.balanceOfCross(other).call({from: owner.eth})).to.be.eq('0');444445    await collectionEvm.methods.transferCross(other, 50n).send({from: owner.eth});446    expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('50');447    expect(await collectionEvm.methods.balanceOfCross(other).call({from: owner.eth})).to.be.eq('50');448449    await collectionEvm.methods.transferCross(other, 50n).send({from: owner.eth});450    expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('0');451    expect(await collectionEvm.methods.balanceOfCross(other).call({from: owner.eth})).to.be.eq('100');452453    await collectionEvm.methods.transferCross(owner, 100n).send({from: other.eth});454    expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('100');455    expect(await collectionEvm.methods.balanceOfCross(other).call({from: owner.eth})).to.be.eq('0');456  });457});458459describe('Fungible: Fees', () => {460  let donor: IKeyringPair;461  let alice: IKeyringPair;462463  before(async function() {464    await usingEthPlaygrounds(async (helper, privateKey) => {465      donor = await privateKey({url: import.meta.url});466      [alice] = await helper.arrange.createAccounts([20n], donor);467    });468  });469470  itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {471    const owner = await helper.eth.createAccountWithBalance(donor);472    const spender = helper.eth.createAccount();473    const collection = await helper.ft.mintCollection(alice);474    await collection.mint(alice, 200n, {Ethereum: owner});475476    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);477    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);478479    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, 100).send({from: owner}));480    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));481  });482483  itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {484    const owner = await helper.eth.createAccountWithBalance(donor);485    const spender = await helper.eth.createAccountWithBalance(donor);486    const collection = await helper.ft.mintCollection(alice);487    await collection.mint(alice, 200n, {Ethereum: owner});488489    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);490    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);491492    await contract.methods.approve(spender, 100).send({from: owner});493494    const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));495    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));496  });497498  itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {499    const owner = await helper.eth.createAccountWithBalance(donor);500    const receiver = helper.eth.createAccount();501    const collection = await helper.ft.mintCollection(alice);502    await collection.mint(alice, 200n, {Ethereum: owner});503504    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);505    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);506507    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));508    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));509  });510});511512describe('Fungible: Substrate calls', () => {513  let donor: IKeyringPair;514  let alice: IKeyringPair;515  let owner: IKeyringPair;516517  before(async function() {518    await usingEthPlaygrounds(async (helper, privateKey) => {519      donor = await privateKey({url: import.meta.url});520      [alice, owner] = await helper.arrange.createAccounts([20n, 20n], donor);521    });522  });523524  itEth('Events emitted for approve()', async ({helper}) => {525    const receiver = helper.eth.createAccount();526    const collection = await helper.ft.mintCollection(alice);527    await collection.mint(alice, 200n);528529    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);530    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft');531532    const events: any = [];533    contract.events.allEvents((_: any, event: any) => {534      events.push(event);535    });536537    await collection.approveTokens(alice, {Ethereum: receiver}, 100n);538    if (events.length == 0) await helper.wait.newBlocks(1);539    const event = events[0];540541    expect(event.event).to.be.equal('Approval');542    expect(event.address).to.be.equal(collectionAddress);543    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));544    expect(event.returnValues.spender).to.be.equal(receiver);545    expect(event.returnValues.value).to.be.equal('100');546  });547548  itEth('Events emitted for transferFrom()', async ({helper}) => {549    const [bob] = await helper.arrange.createAccounts([10n], donor);550    const receiver = helper.eth.createAccount();551    const collection = await helper.ft.mintCollection(alice);552    await collection.mint(alice, 200n);553    await collection.approveTokens(alice, {Substrate: bob.address}, 100n);554555    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);556    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft');557558    const events: any = [];559    contract.events.allEvents((_: any, event: any) => {560      events.push(event);561    });562563    await collection.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver}, 51n);564    if (events.length == 0) await helper.wait.newBlocks(1);565    let event = events[0];566567    expect(event.event).to.be.equal('Transfer');568    expect(event.address).to.be.equal(collectionAddress);569    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));570    expect(event.returnValues.to).to.be.equal(receiver);571    expect(event.returnValues.value).to.be.equal('51');572573    event = events[1];574    expect(event.event).to.be.equal('Approval');575    expect(event.address).to.be.equal(collectionAddress);576    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));577    expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(bob.address));578    expect(event.returnValues.value).to.be.equal('49');579  });580581  itEth('Events emitted for transfer()', async ({helper}) => {582    const receiver = helper.eth.createAccount();583    const collection = await helper.ft.mintCollection(alice);584    await collection.mint(alice, 200n);585586    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);587    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft');588589    const events: any = [];590    contract.events.allEvents((_: any, event: any) => {591      events.push(event);592    });593594    await collection.transfer(alice, {Ethereum:receiver}, 51n);595    if (events.length == 0) await helper.wait.newBlocks(1);596    const event = events[0];597598    expect(event.event).to.be.equal('Transfer');599    expect(event.address).to.be.equal(collectionAddress);600    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));601    expect(event.returnValues.to).to.be.equal(receiver);602    expect(event.returnValues.value).to.be.equal('51');603  });604605  itEth('Events emitted for transferFromCross()', async ({helper}) => {606    const sender = await helper.eth.createAccountWithBalance(donor);607608    const collection = await helper.ft.mintCollection(owner, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);609610    const receiver = helper.eth.createAccount();611612    await collection.mint(owner, 200n, {Substrate: owner.address});613    await collection.approveTokens(owner, {Ethereum: sender}, 100n);614615    const address = helper.ethAddress.fromCollectionId(collection.collectionId);616    const contract = await helper.ethNativeContract.collection(address, 'ft');617618    const from = helper.ethCrossAccount.fromKeyringPair(owner);619    const to = helper.ethCrossAccount.fromAddress(receiver);620621    const result = await contract.methods.transferFromCross(from, to, 51).send({from: sender});622623    expect(result.events).to.be.like({624      Transfer: {625        address,626        event: 'Transfer',627        returnValues: {628          from: helper.address.substrateToEth(owner.address),629          to: receiver,630          value: '51',631        },632      },633      Approval: {634        address,635        event: 'Approval',636        returnValues: {637          owner: helper.address.substrateToEth(owner.address),638          spender: sender,639          value: '49',640        },641      }});642  });643});
after · tests/src/eth/fungible.test.ts
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/>.1617import {expect, itEth, usingEthPlaygrounds} from './util';18import {IKeyringPair} from '@polkadot/types/types';1920describe('Fungible: Plain calls', () => {21  let donor: IKeyringPair;22  let alice: IKeyringPair;23  let owner: IKeyringPair;2425  before(async function() {26    await usingEthPlaygrounds(async (helper, privateKey) => {27      donor = await privateKey({url: import.meta.url});28      [alice, owner] = await helper.arrange.createAccounts([30n, 20n], donor);29    });30  });3132  [33    'substrate' as const,34    'ethereum' as const,35  ].map(testCase => {36    itEth(`Can perform mintCross() for ${testCase} address`, async ({helper}) => {37      // 1. Create receiver depending on the test case:38      const receiverEth = helper.eth.createAccount();39      const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);40      const receiverSub = owner;41      const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(owner);4243      const ethOwner = await helper.eth.createAccountWithBalance(donor);44      const collection = await helper.ft.mintCollection(alice);45      await collection.addAdmin(alice, {Ethereum: ethOwner});4647      const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);48      const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', ethOwner);4950      // 2. Mint tokens:51      const result = await collectionEvm.methods.mintCross(testCase === 'ethereum' ? receiverCrossEth : receiverCrossSub, 100).send();5253      const event = result.events.Transfer;54      expect(event.address).to.equal(collectionAddress);55      expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');56      expect(event.returnValues.to).to.equal(testCase === 'ethereum' ? receiverEth : helper.address.substrateToEth(receiverSub.address));57      expect(event.returnValues.value).to.equal('100');5859      // 3. Get balance depending on the test case:60      let balance;61      if (testCase === 'ethereum') balance = await collection.getBalance({Ethereum: receiverEth});62      else if (testCase === 'substrate') balance = await collection.getBalance({Substrate: receiverSub.address});63      // 3.1 Check balance:64      expect(balance).to.eq(100n);65    });66  });6768  itEth('Can perform mintBulk()', async ({helper}) => {69    const owner = await helper.eth.createAccountWithBalance(donor);70    const bulkSize = 3;71    const receivers = [...new Array(bulkSize)].map(() => helper.eth.createAccount());72    const collection = await helper.ft.mintCollection(alice);73    await collection.addAdmin(alice, {Ethereum: owner});7475    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);76    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);7778    const result = await contract.methods.mintBulk(Array.from({length: bulkSize}, (_, i) => (79      [receivers[i], (i + 1) * 10]80    ))).send();81    const events = result.events.Transfer.sort((a: any, b: any) => +a.returnValues.value - b.returnValues.value);82    for (let i = 0; i < bulkSize; i++) {83      const event = events[i];84      expect(event.address).to.equal(collectionAddress);85      expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');86      expect(event.returnValues.to).to.equal(receivers[i]);87      expect(event.returnValues.value).to.equal(String(10 * (i + 1)));88    }89  });9091  // Soft-deprecated92  itEth('Can perform burn()', async ({helper}) => {93    const owner = await helper.eth.createAccountWithBalance(donor);94    const receiver = await helper.eth.createAccountWithBalance(donor);95    const collection = await helper.ft.mintCollection(alice);96    await collection.addAdmin(alice, {Ethereum: owner});9798    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);99    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner, true);100    await contract.methods.mint(receiver, 100).send();101102    const result = await contract.methods.burnFrom(receiver, 49).send({from: receiver});103104    const event = result.events.Transfer;105    expect(event.address).to.equal(collectionAddress);106    expect(event.returnValues.from).to.equal(receiver);107    expect(event.returnValues.to).to.equal('0x0000000000000000000000000000000000000000');108    expect(event.returnValues.value).to.equal('49');109110    const balance = await contract.methods.balanceOf(receiver).call();111    expect(balance).to.equal('51');112  });113114  itEth('Can perform approve()', async ({helper}) => {115    const owner = await helper.eth.createAccountWithBalance(donor);116    const spender = helper.eth.createAccount();117    const collection = await helper.ft.mintCollection(alice);118    await collection.mint(alice, 200n, {Ethereum: owner});119120    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);121    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);122123    {124      const result = await contract.methods.approve(spender, 100).send({from: owner});125126      const event = result.events.Approval;127      expect(event.address).to.be.equal(collectionAddress);128      expect(event.returnValues.owner).to.be.equal(owner);129      expect(event.returnValues.spender).to.be.equal(spender);130      expect(event.returnValues.value).to.be.equal('100');131    }132133    {134      const allowance = await contract.methods.allowance(owner, spender).call();135      expect(+allowance).to.equal(100);136    }137    {138      const ownerCross = helper.ethCrossAccount.fromAddress(owner);139      const spenderCross = helper.ethCrossAccount.fromAddress(spender);140      const allowance = await contract.methods.allowanceCross(ownerCross, spenderCross).call();141      expect(+allowance).to.equal(100);142    }143  });144145  itEth('Can perform approveCross()', async ({helper}) => {146    const owner = await helper.eth.createAccountWithBalance(donor);147    const spender = helper.eth.createAccount();148    const spenderSub = (await helper.arrange.createAccounts([1n], donor))[0];149    const spenderCrossEth = helper.ethCrossAccount.fromAddress(spender);150    const spenderCrossSub = helper.ethCrossAccount.fromKeyringPair(spenderSub);151152153    const collection = await helper.ft.mintCollection(alice);154    await collection.mint(alice, 200n, {Ethereum: owner});155156    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);157    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);158159    {160      const result = await contract.methods.approveCross(spenderCrossEth, 100).send({from: owner});161      const event = result.events.Approval;162      expect(event.address).to.be.equal(collectionAddress);163      expect(event.returnValues.owner).to.be.equal(owner);164      expect(event.returnValues.spender).to.be.equal(spender);165      expect(event.returnValues.value).to.be.equal('100');166    }167168    {169      const allowance = await contract.methods.allowance(owner, spender).call();170      expect(+allowance).to.equal(100);171    }172173174    {175      const result = await contract.methods.approveCross(spenderCrossSub, 100).send({from: owner});176      const event = result.events.Approval;177      expect(event.address).to.be.equal(collectionAddress);178      expect(event.returnValues.owner).to.be.equal(owner);179      expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(spenderSub.address));180      expect(event.returnValues.value).to.be.equal('100');181    }182183    {184      const allowance = await collection.getApprovedTokens({Ethereum: owner}, {Substrate: spenderSub.address});185      expect(allowance).to.equal(100n);186    }187188    {189      //TO-DO expect with future allowanceCross(owner, spenderCrossEth).call()190    }191  });192193  itEth('Non-owner and non admin cannot approveCross', async ({helper}) => {194    const nonOwner = await helper.eth.createAccountWithBalance(donor);195    const nonOwnerCross = helper.ethCrossAccount.fromAddress(nonOwner);196    const owner = await helper.eth.createAccountWithBalance(donor);197    const collection = await helper.ft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});198    await collection.mint(alice, 100n, {Ethereum: owner});199200    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);201    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);202203    await expect(collectionEvm.methods.approveCross(nonOwnerCross, 20).call({from: nonOwner})).to.be.rejectedWith('CantApproveMoreThanOwned');204  });205206207  itEth('Can perform burnFromCross()', async ({helper}) => {208    const sender = await helper.eth.createAccountWithBalance(donor);209210    const collection = await helper.ft.mintCollection(owner, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);211212    await collection.mint(owner, 200n, {Substrate: owner.address});213    await collection.approveTokens(owner, {Ethereum: sender}, 100n);214215    const address = helper.ethAddress.fromCollectionId(collection.collectionId);216    const contract = await helper.ethNativeContract.collection(address, 'ft');217218    const fromBalanceBefore = await collection.getBalance({Substrate: owner.address});219220    const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);221    const result = await contract.methods.burnFromCross(ownerCross, 49).send({from: sender});222    const events = result.events;223224    expect(events).to.be.like({225      Transfer: {226        address: helper.ethAddress.fromCollectionId(collection.collectionId),227        event: 'Transfer',228        returnValues: {229          from: helper.address.substrateToEth(owner.address),230          to: '0x0000000000000000000000000000000000000000',231          value: '49',232        },233      },234      Approval: {235        address: helper.ethAddress.fromCollectionId(collection.collectionId),236        returnValues: {237          owner: helper.address.substrateToEth(owner.address),238          spender: sender,239          value: '51',240        },241        event: 'Approval',242      },243    });244245    const fromBalanceAfter = await collection.getBalance({Substrate: owner.address});246    expect(fromBalanceBefore - fromBalanceAfter).to.be.eq(49n);247  });248249  itEth('Can perform transferFrom()', async ({helper}) => {250    const owner = await helper.eth.createAccountWithBalance(donor);251    const spender = await helper.eth.createAccountWithBalance(donor);252    const receiver = helper.eth.createAccount();253    const collection = await helper.ft.mintCollection(alice);254    await collection.mint(alice, 200n, {Ethereum: owner});255256    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);257    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);258259    await contract.methods.approve(spender, 100).send();260261    {262      const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: spender});263264      let event = result.events.Transfer;265      expect(event.address).to.be.equal(collectionAddress);266      expect(event.returnValues.from).to.be.equal(owner);267      expect(event.returnValues.to).to.be.equal(receiver);268      expect(event.returnValues.value).to.be.equal('49');269270      event = result.events.Approval;271      expect(event.address).to.be.equal(collectionAddress);272      expect(event.returnValues.owner).to.be.equal(owner);273      expect(event.returnValues.spender).to.be.equal(spender);274      expect(event.returnValues.value).to.be.equal('51');275    }276277    {278      const balance = await contract.methods.balanceOf(receiver).call();279      expect(+balance).to.equal(49);280    }281282    {283      const balance = await contract.methods.balanceOf(owner).call();284      expect(+balance).to.equal(151);285    }286  });287288  itEth('Can perform transferCross()', async ({helper}) => {289    const sender = await helper.eth.createAccountWithBalance(donor);290    const receiverEth = await helper.eth.createAccountWithBalance(donor);291    const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);292    const receiverCrossSub = helper.ethCrossAccount.fromKeyringPair(donor);293    const collection = await helper.ft.mintCollection(alice);294    await collection.mint(alice, 200n, {Ethereum: sender});295296    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);297    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', sender);298299    {300      // Can transferCross to ethereum address:301      const result = await collectionEvm.methods.transferCross(receiverCrossEth, 50).send({from: sender});302      // Check events:303      const event = result.events.Transfer;304      expect(event.address).to.be.equal(collectionAddress);305      expect(event.returnValues.from).to.be.equal(sender);306      expect(event.returnValues.to).to.be.equal(receiverEth);307      expect(event.returnValues.value).to.be.equal('50');308      // Sender's balance decreased:309      const ownerBalance = await collectionEvm.methods.balanceOf(sender).call();310      expect(+ownerBalance).to.equal(150);311      // Receiver's balance increased:312      const receiverBalance = await collectionEvm.methods.balanceOf(receiverEth).call();313      expect(+receiverBalance).to.equal(50);314    }315316    {317      // Can transferCross to substrate address:318      const result = await collectionEvm.methods.transferCross(receiverCrossSub, 50).send({from: sender});319      // Check events:320      const event = result.events.Transfer;321      expect(event.address).to.be.equal(collectionAddress);322      expect(event.returnValues.from).to.be.equal(sender);323      expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(donor.address));324      expect(event.returnValues.value).to.be.equal('50');325      // Sender's balance decreased:326      const senderBalance = await collection.getBalance({Ethereum: sender});327      expect(senderBalance).to.equal(100n);328      // Receiver's balance increased:329      const balance = await collection.getBalance({Substrate: donor.address});330      expect(balance).to.equal(50n);331    }332  });333334  ['transfer', 'transferCross'].map(testCase => itEth(`Cannot ${testCase} incorrect amount`, async ({helper}) => {335    const sender = await helper.eth.createAccountWithBalance(donor);336    const receiverEth = await helper.eth.createAccountWithBalance(donor);337    const receiverCrossEth = helper.ethCrossAccount.fromAddress(receiverEth);338    const BALANCE = 200n;339    const BALANCE_TO_TRANSFER = BALANCE + 100n;340341    const collection = await helper.ft.mintCollection(alice);342    await collection.mint(alice, BALANCE, {Ethereum: sender});343    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);344    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', sender);345346    // 1. Cannot transfer more than have347    const receiver = testCase === 'transfer' ? receiverEth : receiverCrossEth;348    await expect(collectionEvm.methods[testCase](receiver, BALANCE_TO_TRANSFER).send({from: sender})).to.be.rejected;349    // 2. Zero transfer allowed (EIP-20):350    await collectionEvm.methods[testCase](receiver, 0n).send({from: sender});351  }));352353354  itEth('Can perform transfer()', async ({helper}) => {355    const owner = await helper.eth.createAccountWithBalance(donor);356    const receiver = await helper.eth.createAccountWithBalance(donor);357    const collection = await helper.ft.mintCollection(alice);358    await collection.mint(alice, 200n, {Ethereum: owner});359360    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);361    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);362363    {364      const result = await contract.methods.transfer(receiver, 50).send({from: owner});365366      const event = result.events.Transfer;367      expect(event.address).to.be.equal(collectionAddress);368      expect(event.returnValues.from).to.be.equal(owner);369      expect(event.returnValues.to).to.be.equal(receiver);370      expect(event.returnValues.value).to.be.equal('50');371    }372373    {374      const balance = await contract.methods.balanceOf(owner).call();375      expect(+balance).to.equal(150);376    }377378    {379      const balance = await contract.methods.balanceOf(receiver).call();380      expect(+balance).to.equal(50);381    }382  });383384  itEth('Can perform transferFromCross()', async ({helper}) => {385    const sender = await helper.eth.createAccountWithBalance(donor);386387    const collection = await helper.ft.mintCollection(owner, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);388389    const receiver = helper.eth.createAccount();390391    await collection.mint(owner, 200n, {Substrate: owner.address});392    await collection.approveTokens(owner, {Ethereum: sender}, 100n);393394    const address = helper.ethAddress.fromCollectionId(collection.collectionId);395    const contract = await helper.ethNativeContract.collection(address, 'ft');396397    const from = helper.ethCrossAccount.fromKeyringPair(owner);398    const to = helper.ethCrossAccount.fromAddress(receiver);399400    const fromBalanceBefore = await collection.getBalance({Substrate: owner.address});401    const toBalanceBefore = await collection.getBalance({Ethereum: receiver});402403    const result = await contract.methods.transferFromCross(from, to, 51).send({from: sender});404405    expect(result.events).to.be.like({406      Transfer: {407        address,408        event: 'Transfer',409        returnValues: {410          from: helper.address.substrateToEth(owner.address),411          to: receiver,412          value: '51',413        },414      },415      Approval: {416        address,417        event: 'Approval',418        returnValues: {419          owner: helper.address.substrateToEth(owner.address),420          spender: sender,421          value: '49',422        },423      }});424425    const fromBalanceAfter = await collection.getBalance({Substrate: owner.address});426    expect(fromBalanceBefore - fromBalanceAfter).to.be.eq(51n);427    const toBalanceAfter = await collection.getBalance({Ethereum: receiver});428    expect(toBalanceAfter - toBalanceBefore).to.be.eq(51n);429  });430431  itEth('Check balanceOfCross()', async ({helper}) => {432    const collection = await helper.ft.mintCollection(alice, {});433    const owner = await helper.ethCrossAccount.createAccountWithBalance(donor);434    const other = await helper.ethCrossAccount.createAccountWithBalance(donor);435    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);436    const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner.eth);437438    expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('0');439    expect(await collectionEvm.methods.balanceOfCross(other).call({from: owner.eth})).to.be.eq('0');440441    await collection.mint(alice, 100n, {Ethereum: owner.eth});442    expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('100');443    expect(await collectionEvm.methods.balanceOfCross(other).call({from: owner.eth})).to.be.eq('0');444445    await collectionEvm.methods.transferCross(other, 50n).send({from: owner.eth});446    expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('50');447    expect(await collectionEvm.methods.balanceOfCross(other).call({from: owner.eth})).to.be.eq('50');448449    await collectionEvm.methods.transferCross(other, 50n).send({from: owner.eth});450    expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('0');451    expect(await collectionEvm.methods.balanceOfCross(other).call({from: owner.eth})).to.be.eq('100');452453    await collectionEvm.methods.transferCross(owner, 100n).send({from: other.eth});454    expect(await collectionEvm.methods.balanceOfCross(owner).call({from: owner.eth})).to.be.eq('100');455    expect(await collectionEvm.methods.balanceOfCross(other).call({from: owner.eth})).to.be.eq('0');456  });457});458459describe('Fungible: Fees', () => {460  let donor: IKeyringPair;461  let alice: IKeyringPair;462463  before(async function() {464    await usingEthPlaygrounds(async (helper, privateKey) => {465      donor = await privateKey({url: import.meta.url});466      [alice] = await helper.arrange.createAccounts([20n], donor);467    });468  });469470  itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {471    const owner = await helper.eth.createAccountWithBalance(donor);472    const spender = helper.eth.createAccount();473    const collection = await helper.ft.mintCollection(alice);474    await collection.mint(alice, 200n, {Ethereum: owner});475476    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);477    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);478479    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, 100).send({from: owner}));480    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));481  });482483  itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {484    const owner = await helper.eth.createAccountWithBalance(donor);485    const spender = await helper.eth.createAccountWithBalance(donor);486    const collection = await helper.ft.mintCollection(alice);487    await collection.mint(alice, 200n, {Ethereum: owner});488489    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);490    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);491492    await contract.methods.approve(spender, 100).send({from: owner});493494    const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));495    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));496  });497498  itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {499    const owner = await helper.eth.createAccountWithBalance(donor);500    const receiver = helper.eth.createAccount();501    const collection = await helper.ft.mintCollection(alice);502    await collection.mint(alice, 200n, {Ethereum: owner});503504    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);505    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft', owner);506507    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));508    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));509  });510});511512describe('Fungible: Substrate calls', () => {513  let donor: IKeyringPair;514  let alice: IKeyringPair;515  let owner: IKeyringPair;516517  before(async function() {518    await usingEthPlaygrounds(async (helper, privateKey) => {519      donor = await privateKey({url: import.meta.url});520      [alice, owner] = await helper.arrange.createAccounts([20n, 20n], donor);521    });522  });523524  itEth('Events emitted for approve()', async ({helper}) => {525    const receiver = helper.eth.createAccount();526    const collection = await helper.ft.mintCollection(alice);527    await collection.mint(alice, 200n);528529    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);530    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft');531532    const events: any = [];533    contract.events.allEvents((_: any, event: any) => {534      events.push(event);535    });536537    await collection.approveTokens(alice, {Ethereum: receiver}, 100n);538    if (events.length == 0) await helper.wait.newBlocks(1);539    const event = events[0];540541    expect(event.event).to.be.equal('Approval');542    expect(event.address).to.be.equal(collectionAddress);543    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));544    expect(event.returnValues.spender).to.be.equal(receiver);545    expect(event.returnValues.value).to.be.equal('100');546  });547548  itEth('Events emitted for transferFrom()', async ({helper}) => {549    const [bob] = await helper.arrange.createAccounts([10n], donor);550    const receiver = helper.eth.createAccount();551    const collection = await helper.ft.mintCollection(alice);552    await collection.mint(alice, 200n);553    await collection.approveTokens(alice, {Substrate: bob.address}, 100n);554555    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);556    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft');557558    const events: any = [];559    contract.events.allEvents((_: any, event: any) => {560      events.push(event);561    });562563    await collection.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver}, 51n);564    if (events.length == 0) await helper.wait.newBlocks(1);565    let event = events[0];566567    expect(event.event).to.be.equal('Transfer');568    expect(event.address).to.be.equal(collectionAddress);569    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));570    expect(event.returnValues.to).to.be.equal(receiver);571    expect(event.returnValues.value).to.be.equal('51');572573    event = events[1];574    expect(event.event).to.be.equal('Approval');575    expect(event.address).to.be.equal(collectionAddress);576    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));577    expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(bob.address));578    expect(event.returnValues.value).to.be.equal('49');579  });580581  itEth('Events emitted for transfer()', async ({helper}) => {582    const receiver = helper.eth.createAccount();583    const collection = await helper.ft.mintCollection(alice);584    await collection.mint(alice, 200n);585586    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);587    const contract = await helper.ethNativeContract.collection(collectionAddress, 'ft');588589    const events: any = [];590    contract.events.allEvents((_: any, event: any) => {591      events.push(event);592    });593594    await collection.transfer(alice, {Ethereum:receiver}, 51n);595    if (events.length == 0) await helper.wait.newBlocks(1);596    const event = events[0];597598    expect(event.event).to.be.equal('Transfer');599    expect(event.address).to.be.equal(collectionAddress);600    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));601    expect(event.returnValues.to).to.be.equal(receiver);602    expect(event.returnValues.value).to.be.equal('51');603  });604605  itEth('Events emitted for transferFromCross()', async ({helper}) => {606    const sender = await helper.eth.createAccountWithBalance(donor);607608    const collection = await helper.ft.mintCollection(owner, {name: 'A', description: 'B', tokenPrefix: 'C'}, 0);609610    const receiver = helper.eth.createAccount();611612    await collection.mint(owner, 200n, {Substrate: owner.address});613    await collection.approveTokens(owner, {Ethereum: sender}, 100n);614615    const address = helper.ethAddress.fromCollectionId(collection.collectionId);616    const contract = await helper.ethNativeContract.collection(address, 'ft');617618    const from = helper.ethCrossAccount.fromKeyringPair(owner);619    const to = helper.ethCrossAccount.fromAddress(receiver);620621    const result = await contract.methods.transferFromCross(from, to, 51).send({from: sender});622623    expect(result.events).to.be.like({624      Transfer: {625        address,626        event: 'Transfer',627        returnValues: {628          from: helper.address.substrateToEth(owner.address),629          to: receiver,630          value: '51',631        },632      },633      Approval: {634        address,635        event: 'Approval',636        returnValues: {637          owner: helper.address.substrateToEth(owner.address),638          spender: sender,639          value: '49',640        },641      }});642  });643});
modifiedtests/src/eth/nativeFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nativeFungible.test.ts
+++ b/tests/src/eth/nativeFungible.test.ts
@@ -29,7 +29,7 @@
     });
   });
 
-  itEth.only('Can perform approve()', async ({helper}) => {
+  itEth.skip('Can perform approve()', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const spender = helper.eth.createAccount();
     const collection = await helper.ft.mintCollection(alice);
modifiedtests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -48,3 +48,5 @@
   field: CollectionLimitField,
   value: OptionUint,
 }
+
+export const NON_EXISTENT_COLLECTION_ID = 4_294_967_295;
\ No newline at end of file
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -19,6 +19,7 @@
 // Pallets that must always be present
 const requiredPallets = [
   'balances',
+  'balancesadapter',
   'common',
   'timestamp',
   'transactionpayment',
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -17,6 +17,7 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {itEth, usingEthPlaygrounds} from './eth/util';
 import {itSub, Pallets, usingPlaygrounds, expect} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './eth/util/playgrounds/types';
 
 describe('Integration Test Transfer(recipient, collection_id, item_id, value)', () => {
   let donor: IKeyringPair;
@@ -124,20 +125,17 @@
 
 
   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}))
+    await expect(helper.nft.transferToken(alice, NON_EXISTENT_COLLECTION_ID, 1, {Substrate: bob.address}))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
   });
 
   itSub('[fungible] Transfer with not existed collection_id', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
-    await expect(helper.ft.transfer(alice, collectionId, {Substrate: bob.address}))
+    await expect(helper.ft.transfer(alice, NON_EXISTENT_COLLECTION_ID, {Substrate: bob.address}))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
   });
 
   itSub.ifWithPallets('[refungible] Transfer with not existed collection_id', [Pallets.ReFungible], async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
-    await expect(helper.rft.transferToken(alice, collectionId, 1, {Substrate: bob.address}))
+    await expect(helper.rft.transferToken(alice, NON_EXISTENT_COLLECTION_ID, 1, {Substrate: bob.address}))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
   });
 
modifiedtests/src/transferFrom.test.tsdiffbeforeafterboth
--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -16,6 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {itSub, Pallets, usingPlaygrounds, expect} from './util';
+import {NON_EXISTENT_COLLECTION_ID} from './eth/util/playgrounds/types';
 
 describe('Integration Test transferFrom(from, recipient, collection_id, item_id, value):', () => {
   let alice: IKeyringPair;
@@ -97,10 +98,9 @@
   });
 
   itSub('transferFrom for a collection that does not exist', async ({helper}) => {
-    const collectionId = (1 << 32) - 1;
-    await expect(helper.collection.approveToken(alice, collectionId, 0, {Substrate: bob.address}, 1n))
+    await expect(helper.collection.approveToken(alice, NON_EXISTENT_COLLECTION_ID, 0, {Substrate: bob.address}, 1n))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
-    await expect(helper.collection.transferTokenFrom(bob, collectionId, 0, {Substrate: alice.address}, {Substrate: bob.address}, 1n))
+    await expect(helper.collection.transferTokenFrom(bob, NON_EXISTENT_COLLECTION_ID, 0, {Substrate: alice.address}, {Substrate: bob.address}, 1n))
       .to.be.rejectedWith(/common\.CollectionNotFound/);
   });