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

difftreelog

misk: Documentation, test fixes, refactor

Trubnikov Sergey2022-10-27parent: #6afd9fe.patch.diff
in: master

12 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1096,26 +1096,6 @@
 checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3"
 
 [[package]]
-name = "const_format"
-version = "0.2.30"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7309d9b4d3d2c0641e018d449232f2e28f1b22933c137f157d3dbc14228b8c0e"
-dependencies = [
- "const_format_proc_macros",
-]
-
-[[package]]
-name = "const_format_proc_macros"
-version = "0.2.29"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d897f47bf7270cf70d370f8f98c1abb6d2d4cf60a6845d30e05bfb90c6568650"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-xid",
-]
-
-[[package]]
 name = "constant_time_eq"
 version = "0.1.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2373,7 +2353,6 @@
 version = "0.1.3"
 dependencies = [
  "concat-idents",
- "const_format",
  "ethereum",
  "evm-coder-procedural",
  "evm-core 0.35.0 (git+https://github.com/uniquenetwork/evm?branch=unique-polkadot-v0.9.30)",
modifiedcrates/evm-coder/Cargo.tomldiffbeforeafterboth
--- a/crates/evm-coder/Cargo.toml
+++ b/crates/evm-coder/Cargo.toml
@@ -5,7 +5,6 @@
 edition = "2021"
 
 [dependencies]
-const_format = { version = "0.2.26", default-features = false }
 sha3-const = { version = "0.1.1", default-features = false }
 # Ethereum uses keccak (=sha3) for selectors
 # sha3 = "0.10.1"
modifiedcrates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth
--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -20,7 +20,7 @@
 // about Procedural Macros in Rust book:
 // https://doc.rust-lang.org/reference/procedural-macros.html
 
-use proc_macro2::{TokenStream, token_stream};
+use proc_macro2::TokenStream;
 use quote::{quote, ToTokens, format_ident};
 use inflector::cases;
 use std::fmt::Write;
modifiedcrates/evm-coder/src/custom_signature.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/custom_signature.rs
+++ b/crates/evm-coder/src/custom_signature.rs
@@ -1,23 +1,140 @@
+//! # A module for custom signature support.
+//!
+//! ## Overview
+//! This module allows you to create arbitrary signatures for types and functions in compile time.
+//!
+//! ### Type signatures
+//! To create the desired type signature, you need to create your own trait with the `SIGNATURE` constant.
+//! Then in the implementation, for the required type, use the macro [`make_signature`]
+//! #### Example
+//! ```
+//! use std::str::from_utf8;
+//! use evm_coder::make_signature;
+//! use evm_coder::custom_signature::{
+//! 	SignatureUnit,
+//! 	SIGNATURE_SIZE_LIMIT
+//! };
+//!
+//! // Create trait for our signature
+//! trait SoliditySignature {
+//!		const SIGNATURE: SignatureUnit;
+//!
+//!		fn name() -> &'static str {
+//!			from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+//!		}
+//!	}
+//!
+//! // Make signatures for some types
+//!	impl SoliditySignature for u8 {
+//!		make_signature!(new fixed("uint8"));
+//!	}
+//!	impl SoliditySignature for u32 {
+//!		make_signature!(new fixed("uint32"));
+//!	}
+//!	impl<T: SoliditySignature> SoliditySignature for Vec<T> {
+//!		make_signature!(new nameof(T) fixed("[]"));
+//!	}
+//!	impl<A: SoliditySignature, B: SoliditySignature> SoliditySignature for (A, B) {
+//!		make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
+//!	}
+//!	impl<A: SoliditySignature> SoliditySignature for (A,) {
+//!		make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));
+//!	}
+//!
+//! assert_eq!(u8::name(), "uint8");
+//! assert_eq!(<Vec<u8>>::name(), "uint8[]");
+//! assert_eq!(<(u32, u8)>::name(), "(uint32,uint8)");
+//! ```
+//!
+//! ### Function signatures
+//! To create a function signature, the macro [`make_signature`] is also used, which accepts
+//! settings for the function format [`SignaturePreferences`] and function parameters [`SignatureUnit`]
+//! #### Example
+//! ```
+//! use core::str::from_utf8;
+//! use evm_coder::{
+//!		make_signature,
+//!		custom_signature::{
+//!			SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,
+//!		},
+//!	};
+//! // Trait for our signature
+//! trait SoliditySignature {
+//!		const SIGNATURE: SignatureUnit;
+//!
+//!		fn name() -> &'static str {
+//!			from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")
+//!		}
+//!	}
+//!
+//! // Make signatures for some types
+//!	impl SoliditySignature for u8 {
+//!		make_signature!(new fixed("uint8"));
+//!	}
+//!	impl<T: SoliditySignature> SoliditySignature for Vec<T> {
+//!		make_signature!(new nameof(T) fixed("[]"));
+//!	}
+//!
+//! // Function signature settings
+//! const SIGNATURE_PREFERENCES: SignaturePreferences = SignaturePreferences {
+//!		open_name: Some(SignatureUnit::new("some_funk")),
+//!		open_delimiter: Some(SignatureUnit::new("(")),
+//!		param_delimiter: Some(SignatureUnit::new(",")),
+//!		close_delimiter: Some(SignatureUnit::new(")")),
+//!		close_name: None,
+//!	};
+//!
+//! // Create functions signatures
+//! fn make_func_without_args() {
+//!		const SIG: FunctionSignature = make_signature!(
+//!			new fn(SIGNATURE_PREFERENCES),
+//!		);
+//!		let name = SIG.as_str();
+//!		similar_asserts::assert_eq!(name, "some_funk()");
+//!	}
+//!
+//! fn make_func_with_3_args() {
+//!		const SIG: FunctionSignature = make_signature!(
+//!			new fn(SIGNATURE_PREFERENCES),
+//!			(<u8>::SIGNATURE),
+//!			(<u8>::SIGNATURE),
+//!			(<Vec<u8>>::SIGNATURE),
+//!		);
+//!		let name = SIG.as_str();
+//!		similar_asserts::assert_eq!(name, "some_funk(uint8,uint8,uint8[])");
+//!	}
+//! ```
 use core::str::from_utf8;
 
+/// The maximum length of the signature.
 pub const SIGNATURE_SIZE_LIMIT: usize = 256;
 
+/// Function signature formatting preferences.
 #[derive(Debug)]
 pub struct SignaturePreferences {
+	/// The name of the function before the list of parameters: `*some*(param1,param2)func`
 	pub open_name: Option<SignatureUnit>,
+	/// Opening separator: `some*(*param1,param2)func`
 	pub open_delimiter: Option<SignatureUnit>,
+	/// Parameters separator: `some(param1*,*param2)func`
 	pub param_delimiter: Option<SignatureUnit>,
+	/// Closinging separator: `some(param1,param2*)*func`
 	pub close_delimiter: Option<SignatureUnit>,
+	/// The name of the function after the list of parameters: `some(param1,param2)*func*`
 	pub close_name: Option<SignatureUnit>,
 }
 
+/// Constructs and stores the signature of the function.
 #[derive(Debug)]
 pub struct FunctionSignature {
+	/// Storage for function signature.
 	pub unit: SignatureUnit,
 	preferences: SignaturePreferences,
 }
 
 impl FunctionSignature {
+	/// Start constructing the signature. It is written to the storage
+	/// [`SignaturePreferences::open_name`] and [`SignaturePreferences::open_delimiter`].
 	pub const fn new(preferences: SignaturePreferences) -> FunctionSignature {
 		let mut dst = [0_u8; SIGNATURE_SIZE_LIMIT];
 		let mut dst_offset = 0;
@@ -36,6 +153,8 @@
 		}
 	}
 
+	/// Add a function parameter to the signature. It is written to the storage
+	/// `param` [`SignatureUnit`] and [`SignaturePreferences::param_delimiter`].
 	pub const fn add_param(
 		signature: FunctionSignature,
 		param: SignatureUnit,
@@ -55,6 +174,8 @@
 		}
 	}
 
+	/// Complete signature construction. It is written to the storage
+	/// [`SignaturePreferences::close_delimiter`] and [`SignaturePreferences::close_name`].
 	pub const fn done(signature: FunctionSignature, owerride: bool) -> FunctionSignature {
 		let mut dst = signature.unit.data;
 		let mut dst_offset = signature.unit.len - if owerride { 1 } else { 0 };
@@ -73,18 +194,23 @@
 		}
 	}
 
+	/// Represent the signature as `&str'.
 	pub fn as_str(&self) -> &str {
 		from_utf8(&self.unit.data[..self.unit.len]).expect("bad utf-8")
 	}
 }
 
+/// Storage for the signature or its elements.
 #[derive(Debug)]
 pub struct SignatureUnit {
+	/// Signature data.
 	pub data: [u8; SIGNATURE_SIZE_LIMIT],
+	/// The actual size of the data.
 	pub len: usize,
 }
 
 impl SignatureUnit {
+	/// Create a signature from `&str'.
 	pub const fn new(name: &'static str) -> SignatureUnit {
 		let mut signature = [0_u8; SIGNATURE_SIZE_LIMIT];
 		let name = name.as_bytes();
@@ -98,9 +224,23 @@
 	}
 }
 
+/// ### Macro to create signatures of types and functions.
+///
+/// Format for creating a type of signature:
+/// ```ignore
+/// make_signature!(new fixed("uint8")); // Simple type
+/// make_signature!(new fixed("(") nameof(u8) fixed(",") nameof(u8) fixed(")")); // Composite type
+/// ```
+/// Format for creating a function of the function:
+/// ```ignore
+/// const SIG: FunctionSignature = make_signature!(
+///		new fn(SIGNATURE_PREFERENCES),
+///		(u8::SIGNATURE),
+///		(<(u8,u8)>::SIGNATURE),
+///	);
+/// ```
 #[macro_export]
-#[allow(missing_docs)]
-macro_rules! make_signature { // May be "define_signature"?
+macro_rules! make_signature {
 	(new fn($func:expr)$(,)+) => {
 		{
 			let fs = FunctionSignature::new($func);
@@ -283,10 +423,13 @@
 		assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));
 	}
 
-	// This test must NOT compile!
+	// This test must NOT compile with "index out of bounds"!
 	// #[test]
 	// fn over_max_size() {
-	// 	assert_eq!(<Vec<MaxSize>>::name(), "!".repeat(SIZE_LIMIT) + "[]");
+	// 	assert_eq!(
+	// 		<Vec<MaxSize>>::name(),
+	// 		"!".repeat(SIGNATURE_SIZE_LIMIT) + "[]"
+	// 	);
 	// }
 
 	#[test]
modifiedcrates/evm-coder/src/lib.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -15,8 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 #![doc = include_str!("../README.md")]
-// #![deny(missing_docs)]
-#![warn(missing_docs)]
+#![deny(missing_docs)]
 #![macro_use]
 #![cfg_attr(not(feature = "std"), no_std)]
 #[cfg(not(feature = "std"))]
@@ -94,7 +93,6 @@
 pub use evm_coder_procedural::solidity;
 /// See [`solidity_interface`]
 pub use evm_coder_procedural::weight;
-pub use const_format;
 pub use sha3_const;
 
 /// Derives [`ToLog`] for enum
@@ -384,18 +382,6 @@
 	fn function_selector_generation() {
 		assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);
 	}
-
-	// #[test]
-	// fn function_selector_generation_1() {
-	// 	assert_eq!(
-	// 		fn_selector!(transferFromCrossAccountToCrossAccount(
-	// 			EthCrossAccount,
-	// 			EthCrossAccount,
-	// 			uint256
-	// 		)),
-	// 		2543295963
-	// 	);
-	// }
 
 	#[test]
 	fn event_topic_generation() {
modifiedcrates/evm-coder/tests/conditional_is.rsdiffbeforeafterboth
--- a/crates/evm-coder/tests/conditional_is.rs
+++ b/crates/evm-coder/tests/conditional_is.rs
@@ -1,4 +1,11 @@
 use evm_coder::{types::*, solidity_interface, execution::Result};
+use evm_coder::{
+	make_signature,
+	custom_signature::{
+		SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,
+	},
+	types::Signature,
+};
 
 pub struct Contract(bool);
 
modifiedcrates/evm-coder/tests/generics.rsdiffbeforeafterboth
--- a/crates/evm-coder/tests/generics.rs
+++ b/crates/evm-coder/tests/generics.rs
@@ -16,6 +16,12 @@
 
 use std::marker::PhantomData;
 use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
+use evm_coder::{
+	make_signature,
+	custom_signature::{
+		SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,
+	},
+};
 
 pub struct Generic<T>(PhantomData<T>);
 
modifiedcrates/evm-coder/tests/random.rsdiffbeforeafterboth
--- a/crates/evm-coder/tests/random.rs
+++ b/crates/evm-coder/tests/random.rs
@@ -17,6 +17,13 @@
 #![allow(dead_code)] // This test only checks that macros is not panicking
 
 use evm_coder::{ToLog, execution::Result, solidity_interface, types::*, solidity, weight};
+use evm_coder::{
+	make_signature,
+	custom_signature::{
+		SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,
+	},
+	types::Signature,
+};
 
 pub struct Impls;
 
modifiedcrates/evm-coder/tests/solidity_generation.rsdiffbeforeafterboth
--- a/crates/evm-coder/tests/solidity_generation.rs
+++ b/crates/evm-coder/tests/solidity_generation.rs
@@ -15,6 +15,13 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
+use evm_coder::{
+	make_signature,
+	custom_signature::{
+		SIGNATURE_SIZE_LIMIT, SignatureUnit, SignaturePreferences, FunctionSignature,
+	},
+	types::Signature,
+};
 
 pub struct ERC20;
 
modifiedtests/src/eth/base.test.tsdiffbeforeafterboth
--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -116,8 +116,8 @@
     await checkInterface(helper, '0x780e9d63', true, true);
   });
 
-  itEth('ERC721UniqueExtensions - 0x244543ee - support', async ({helper}) => {
-    await checkInterface(helper, '0x244543ee', true, true);
+  itEth('ERC721UniqueExtensions support', async ({helper}) => {
+    expect(await contract(helper).methods.supportsInterface('0xb76006ac').call()).to.be.true;
   });
 
   itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
before · tests/src/eth/nonFungible.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 {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util';18import {IKeyringPair} from '@polkadot/types/types';19import {Contract} from 'web3-eth-contract';202122describe('NFT: Information getting', () => {23  let donor: IKeyringPair;24  let alice: IKeyringPair;2526  before(async function() {27    await usingEthPlaygrounds(async (helper, privateKey) => {28      donor = await privateKey({filename: __filename});29      [alice] = await helper.arrange.createAccounts([10n], donor);30    });31  });3233  itEth('totalSupply', async ({helper}) => {34    const collection = await helper.nft.mintCollection(alice, {});35    await collection.mintToken(alice);3637    const caller = await helper.eth.createAccountWithBalance(donor);3839    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);40    const totalSupply = await contract.methods.totalSupply().call();4142    expect(totalSupply).to.equal('1');43  });4445  itEth('balanceOf', async ({helper}) => {46    const collection = await helper.nft.mintCollection(alice, {});47    const caller = await helper.eth.createAccountWithBalance(donor);4849    await collection.mintToken(alice, {Ethereum: caller});50    await collection.mintToken(alice, {Ethereum: caller});51    await collection.mintToken(alice, {Ethereum: caller});5253    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);54    const balance = await contract.methods.balanceOf(caller).call();5556    expect(balance).to.equal('3');57  });5859  itEth('ownerOf', async ({helper}) => {60    const collection = await helper.nft.mintCollection(alice, {});61    const caller = await helper.eth.createAccountWithBalance(donor);6263    const token = await collection.mintToken(alice, {Ethereum: caller});6465    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);6667    const owner = await contract.methods.ownerOf(token.tokenId).call();6869    expect(owner).to.equal(caller);70  });7172  itEth('name/symbol is available regardless of ERC721Metadata support', async ({helper}) => {73    const collection = await helper.nft.mintCollection(alice, {name: 'test', tokenPrefix: 'TEST'});74    const caller = helper.eth.createAccount();7576    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);7778    expect(await contract.methods.name().call()).to.equal('test');79    expect(await contract.methods.symbol().call()).to.equal('TEST');80  });81});8283describe('Check ERC721 token URI for NFT', () => {84  let donor: IKeyringPair;8586  before(async function() {87    await usingEthPlaygrounds(async (_helper, privateKey) => {88      donor = await privateKey({filename: __filename});89    });90  });9192  async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {93    const owner = await helper.eth.createAccountWithBalance(donor);94    const receiver = helper.eth.createAccount();9596    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);97    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);9899    const result = await contract.methods.mint(receiver).send();100    const tokenId = result.events.Transfer.returnValues.tokenId;101    expect(tokenId).to.be.equal('1');102103    if (propertyKey && propertyValue) {104      // Set URL or suffix105      await contract.methods.setProperty(tokenId, propertyKey, Buffer.from(propertyValue)).send();106    }107108    const event = result.events.Transfer;109    expect(event.address).to.be.equal(collectionAddress);110    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');111    expect(event.returnValues.to).to.be.equal(receiver);112    expect(event.returnValues.tokenId).to.be.equal(tokenId);113114    return {contract, nextTokenId: tokenId};115  }116117  itEth('Empty tokenURI', async ({helper}) => {118    const {contract, nextTokenId} = await setup(helper, '');119    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('');120  });121122  itEth('TokenURI from url', async ({helper}) => {123    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');124    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');125  });126127  itEth('TokenURI from baseURI', async ({helper}) => {128    const {contract, nextTokenId} = await setup(helper, 'BaseURI_');129    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_');130  });131132  itEth('TokenURI from baseURI + suffix', async ({helper}) => {133    const suffix = '/some/suffix';134    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);135    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);136  });137});138139describe('NFT: Plain calls', () => {140  let donor: IKeyringPair;141  let alice: IKeyringPair;142143  before(async function() {144    await usingEthPlaygrounds(async (helper, privateKey) => {145      donor = await privateKey({filename: __filename});146      [alice] = await helper.arrange.createAccounts([10n], donor);147    });148  });149150  itEth('Can perform mint()', async ({helper}) => {151    const owner = await helper.eth.createAccountWithBalance(donor);152    const receiver = helper.eth.createAccount();153154    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', '6', '6', '');155    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);156157    const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();158    const tokenId = result.events.Transfer.returnValues.tokenId;159    expect(tokenId).to.be.equal('1');160161    const event = result.events.Transfer;162    expect(event.address).to.be.equal(collectionAddress);163    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');164    expect(event.returnValues.to).to.be.equal(receiver);165166    expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');167168    // TODO: this wont work right now, need release 919000 first169    // await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();170    // const tokenUri = await contract.methods.tokenURI(nextTokenId).call();171    // expect(tokenUri).to.be.equal(`https://offchain-service.local/token-info/${nextTokenId}`);172  });173174  //TODO: CORE-302 add eth methods175  itEth.skip('Can perform mintBulk()', async ({helper}) => {176    const caller = await helper.eth.createAccountWithBalance(donor);177    const receiver = helper.eth.createAccount();178179    const collection = await helper.nft.mintCollection(alice);180    await collection.addAdmin(alice, {Ethereum: caller});181182    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);183    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', caller);184    {185      const bulkSize = 3;186      const nextTokenId = await contract.methods.nextTokenId().call();187      expect(nextTokenId).to.be.equal('1');188      const result = await contract.methods.mintBulkWithTokenURI(189        receiver,190        Array.from({length: bulkSize}, (_, i) => (191          [+nextTokenId + i, `Test URI ${i}`]192        )),193      ).send({from: caller});194195      const events = result.events.Transfer.sort((a: any, b: any) => +a.returnValues.tokenId - b.returnValues.tokenId);196      for (let i = 0; i < bulkSize; i++) {197        const event = events[i];198        expect(event.address).to.equal(collectionAddress);199        expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');200        expect(event.returnValues.to).to.equal(receiver);201        expect(event.returnValues.tokenId).to.equal(`${+nextTokenId + i}`);202203        expect(await contract.methods.tokenURI(+nextTokenId + i).call()).to.be.equal(`Test URI ${i}`);204      }205    }206  });207208  itEth('Can perform burn()', async ({helper}) => {209    const caller = await helper.eth.createAccountWithBalance(donor);210211    const collection = await helper.nft.mintCollection(alice, {});212    const {tokenId} = await collection.mintToken(alice, {Ethereum: caller});213214    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);215    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', caller);216217    {218      const result = await contract.methods.burn(tokenId).send({from: caller});219220      const event = result.events.Transfer;221      expect(event.address).to.be.equal(collectionAddress);222      expect(event.returnValues.from).to.be.equal(caller);223      expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');224      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);225    }226  });227228  itEth('Can perform approve()', async ({helper}) => {229    const owner = await helper.eth.createAccountWithBalance(donor);230    const spender = helper.eth.createAccount();231232    const collection = await helper.nft.mintCollection(alice, {});233    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});234235    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);236    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);237238    {239      const result = await contract.methods.approve(spender, tokenId).send({from: owner});240241      const event = result.events.Approval;242      expect(event.address).to.be.equal(collectionAddress);243      expect(event.returnValues.owner).to.be.equal(owner);244      expect(event.returnValues.approved).to.be.equal(spender);245      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);246    }247  });248249  itEth('Can perform burnFromCross()', async ({helper, privateKey}) => {250    const alice = privateKey('//Alice');251    const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});252253    const owner = privateKey('//Bob');254    const spender = await helper.eth.createAccountWithBalance(alice, 100n);255256    const token = await collection.mintToken(alice, {Substrate: owner.address});257258    const address = helper.ethAddress.fromCollectionId(collection.collectionId);259    const contract = helper.ethNativeContract.collection(address, 'nft');260261    {262      await token.approve(owner, {Ethereum: spender});263      const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);264      const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender});265      const events = result.events.Transfer;266267      expect(events).to.be.like({268        address,269        event: 'Transfer',270        returnValues: {271          from: helper.address.substrateToEth(owner.address),272          to: '0x0000000000000000000000000000000000000000',273          tokenId: token.tokenId.toString(),274        },275      });276    }277  });278279  itEth('Can perform approveCross()', async ({helper, privateKey}) => {280    const alice = privateKey('//Alice');281    const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});282283    const owner = await helper.eth.createAccountWithBalance(alice, 100n);284    const receiver = privateKey('//Charlie');285286    const token = await collection.mintToken(alice, {Ethereum: owner});287288    const address = helper.ethAddress.fromCollectionId(collection.collectionId);289    const contract = helper.ethNativeContract.collection(address, 'nft');290291    {292      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);293      const result = await contract.methods.approveCross(recieverCross, token.tokenId).send({from: owner});294      const event = result.events.Approval;295      expect(event).to.be.like({296        address: helper.ethAddress.fromCollectionId(collection.collectionId),297        event: 'Approval',298        returnValues: {299          owner,300          approved: helper.address.substrateToEth(receiver.address),301          tokenId: token.tokenId.toString(),302        },303      });304    }305  });306307  itEth('Can perform transferFrom()', async ({helper}) => {308    const owner = await helper.eth.createAccountWithBalance(donor);309    const spender = await helper.eth.createAccountWithBalance(donor);310    const receiver = helper.eth.createAccount();311312    const collection = await helper.nft.mintCollection(alice, {});313    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});314315    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);316    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);317318    await contract.methods.approve(spender, tokenId).send({from: owner});319320    {321      const result = await contract.methods.transferFrom(owner, receiver, tokenId).send({from: spender});322323      const event = result.events.Transfer;324      expect(event.address).to.be.equal(collectionAddress);325      expect(event.returnValues.from).to.be.equal(owner);326      expect(event.returnValues.to).to.be.equal(receiver);327      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);328    }329330    {331      const balance = await contract.methods.balanceOf(receiver).call();332      expect(+balance).to.equal(1);333    }334335    {336      const balance = await contract.methods.balanceOf(owner).call();337      expect(+balance).to.equal(0);338    }339  });340341  itEth('Can perform transfer()', async ({helper}) => {342    const collection = await helper.nft.mintCollection(alice, {});343    const owner = await helper.eth.createAccountWithBalance(donor);344    const receiver = helper.eth.createAccount();345346    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});347348    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);349    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);350351    {352      const result = await contract.methods.transfer(receiver, tokenId).send({from: owner});353354      const event = result.events.Transfer;355      expect(event.address).to.be.equal(collectionAddress);356      expect(event.returnValues.from).to.be.equal(owner);357      expect(event.returnValues.to).to.be.equal(receiver);358      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);359    }360361    {362      const balance = await contract.methods.balanceOf(owner).call();363      expect(+balance).to.equal(0);364    }365366    {367      const balance = await contract.methods.balanceOf(receiver).call();368      expect(+balance).to.equal(1);369    }370  });371});372373describe('NFT: Fees', () => {374  let donor: IKeyringPair;375  let alice: IKeyringPair;376377  before(async function() {378    await usingEthPlaygrounds(async (helper, privateKey) => {379      donor = await privateKey({filename: __filename});380      [alice] = await helper.arrange.createAccounts([10n], donor);381    });382  });383384  itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {385    const owner = await helper.eth.createAccountWithBalance(donor);386    const spender = helper.eth.createAccount();387388    const collection = await helper.nft.mintCollection(alice, {});389    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});390391    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);392393    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, tokenId).send({from: owner}));394    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));395  });396397  itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {398    const owner = await helper.eth.createAccountWithBalance(donor);399    const spender = await helper.eth.createAccountWithBalance(donor);400401    const collection = await helper.nft.mintCollection(alice, {});402    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});403404    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);405406    await contract.methods.approve(spender, tokenId).send({from: owner});407408    const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, tokenId).send({from: spender}));409    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));410  });411412  itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {413    const alice = privateKey('//Alice');414    const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});415416    const owner = privateKey('//Bob');417    const spender = await helper.eth.createAccountWithBalance(alice, 100n);418    const receiver = privateKey('//Charlie');419420    const token = await collection.mintToken(alice, {Substrate: owner.address});421422    const address = helper.ethAddress.fromCollectionId(collection.collectionId);423    const contract = helper.ethNativeContract.collection(address, 'nft');424425    await token.approve(owner, {Ethereum: spender});426427    {428      const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);429      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);430      const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender});431      const event = result.events.Transfer;432      expect(event).to.be.like({433        address: helper.ethAddress.fromCollectionId(collection.collectionId),434        event: 'Transfer',435        returnValues: {436          from: helper.address.substrateToEth(owner.address),437          to: helper.address.substrateToEth(receiver.address),438          tokenId: token.tokenId.toString(),439        },440      });441    }442443    expect(await token.getOwner()).to.be.like({Substrate: receiver.address});444  });445446  itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {447    const owner = await helper.eth.createAccountWithBalance(donor);448    const receiver = helper.eth.createAccount();449450    const collection = await helper.nft.mintCollection(alice, {});451    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});452453    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);454455    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, tokenId).send({from: owner}));456    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));457  });458});459460describe('NFT: Substrate calls', () => {461  let donor: IKeyringPair;462  let alice: IKeyringPair;463464  before(async function() {465    await usingEthPlaygrounds(async (helper, privateKey) => {466      donor = await privateKey({filename: __filename});467      [alice] = await helper.arrange.createAccounts([20n], donor);468    });469  });470471  itEth('Events emitted for mint()', async ({helper}) => {472    const collection = await helper.nft.mintCollection(alice, {});473    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);474    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');475476    const events: any = [];477    contract.events.allEvents((_: any, event: any) => {478      events.push(event);479    });480481    const {tokenId} = await collection.mintToken(alice);482    if (events.length == 0) await helper.wait.newBlocks(1);483    const event = events[0];484485    expect(event.event).to.be.equal('Transfer');486    expect(event.address).to.be.equal(collectionAddress);487    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');488    expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(alice.address));489    expect(event.returnValues.tokenId).to.be.equal(tokenId.toString());490  });491492  itEth('Events emitted for burn()', async ({helper}) => {493    const collection = await helper.nft.mintCollection(alice, {});494    const token = await collection.mintToken(alice);495496    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);497    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');498499    const events: any = [];500    contract.events.allEvents((_: any, event: any) => {501      events.push(event);502    });503504    await token.burn(alice);505    if (events.length == 0) await helper.wait.newBlocks(1);506    const event = events[0];507508    expect(event.event).to.be.equal('Transfer');509    expect(event.address).to.be.equal(collectionAddress);510    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));511    expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');512    expect(event.returnValues.tokenId).to.be.equal(token.tokenId.toString());513  });514515  itEth('Events emitted for approve()', async ({helper}) => {516    const receiver = helper.eth.createAccount();517518    const collection = await helper.nft.mintCollection(alice, {});519    const token = await collection.mintToken(alice);520521    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);522    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');523524    const events: any = [];525    contract.events.allEvents((_: any, event: any) => {526      events.push(event);527    });528529    await token.approve(alice, {Ethereum: receiver});530    if (events.length == 0) await helper.wait.newBlocks(1);531    const event = events[0];532533    expect(event.event).to.be.equal('Approval');534    expect(event.address).to.be.equal(collectionAddress);535    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));536    expect(event.returnValues.approved).to.be.equal(receiver);537    expect(event.returnValues.tokenId).to.be.equal(token.tokenId.toString());538  });539540  itEth('Events emitted for transferFrom()', async ({helper}) => {541    const [bob] = await helper.arrange.createAccounts([10n], donor);542    const receiver = helper.eth.createAccount();543544    const collection = await helper.nft.mintCollection(alice, {});545    const token = await collection.mintToken(alice);546    await token.approve(alice, {Substrate: bob.address});547548    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);549    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');550551    const events: any = [];552    contract.events.allEvents((_: any, event: any) => {553      events.push(event);554    });555556    await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver});557558    if (events.length == 0) await helper.wait.newBlocks(1);559    const event = events[0];560561    expect(event.address).to.be.equal(collectionAddress);562    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));563    expect(event.returnValues.to).to.be.equal(receiver);564    expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);565  });566567  itEth('Events emitted for transfer()', async ({helper}) => {568    const receiver = helper.eth.createAccount();569570    const collection = await helper.nft.mintCollection(alice, {});571    const token = await collection.mintToken(alice);572573    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);574    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');575576    const events: any = [];577    contract.events.allEvents((_: any, event: any) => {578      events.push(event);579    });580581    await token.transfer(alice, {Ethereum: receiver});582583    if (events.length == 0) await helper.wait.newBlocks(1);584    const event = events[0];585586    expect(event.address).to.be.equal(collectionAddress);587    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));588    expect(event.returnValues.to).to.be.equal(receiver);589    expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);590  });591});592593describe('Common metadata', () => {594  let donor: IKeyringPair;595  let alice: IKeyringPair;596597  before(async function() {598    await usingEthPlaygrounds(async (helper, privateKey) => {599      donor = await privateKey({filename: __filename});600      [alice] = await helper.arrange.createAccounts([20n], donor);601    });602  });603604  itEth('Returns collection name', async ({helper}) => {605    const caller = await helper.eth.createAccountWithBalance(donor);606    const tokenPropertyPermissions = [{607      key: 'URI',608      permission: {609        mutable: true,610        collectionAdmin: true,611        tokenOwner: false,612      },613    }];614    const collection = await helper.nft.mintCollection(615      alice,616      {617        name: 'oh River',618        tokenPrefix: 'CHANGE',619        properties: [{key: 'ERC721Metadata', value: '1'}],620        tokenPropertyPermissions,621      },622    );623624    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);625    const name = await contract.methods.name().call();626    expect(name).to.equal('oh River');627  });628629  itEth('Returns symbol name', async ({helper}) => {630    const caller = await helper.eth.createAccountWithBalance(donor);631    const tokenPropertyPermissions = [{632      key: 'URI',633      permission: {634        mutable: true,635        collectionAdmin: true,636        tokenOwner: false,637      },638    }];639    const collection = await helper.nft.mintCollection(640      alice,641      {642        name: 'oh River',643        tokenPrefix: 'CHANGE',644        properties: [{key: 'ERC721Metadata', value: '1'}],645        tokenPropertyPermissions,646      },647    );648649    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);650    const symbol = await contract.methods.symbol().call();651    expect(symbol).to.equal('CHANGE');652  });653});
after · tests/src/eth/nonFungible.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 {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util';18import {IKeyringPair} from '@polkadot/types/types';19import {Contract} from 'web3-eth-contract';202122describe('NFT: Information getting', () => {23  let donor: IKeyringPair;24  let alice: IKeyringPair;2526  before(async function() {27    await usingEthPlaygrounds(async (helper, privateKey) => {28      donor = await privateKey({filename: __filename});29      [alice] = await helper.arrange.createAccounts([10n], donor);30    });31  });3233  itEth('totalSupply', async ({helper}) => {34    const collection = await helper.nft.mintCollection(alice, {});35    await collection.mintToken(alice);3637    const caller = await helper.eth.createAccountWithBalance(donor);3839    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);40    const totalSupply = await contract.methods.totalSupply().call();4142    expect(totalSupply).to.equal('1');43  });4445  itEth('balanceOf', async ({helper}) => {46    const collection = await helper.nft.mintCollection(alice, {});47    const caller = await helper.eth.createAccountWithBalance(donor);4849    await collection.mintToken(alice, {Ethereum: caller});50    await collection.mintToken(alice, {Ethereum: caller});51    await collection.mintToken(alice, {Ethereum: caller});5253    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);54    const balance = await contract.methods.balanceOf(caller).call();5556    expect(balance).to.equal('3');57  });5859  itEth('ownerOf', async ({helper}) => {60    const collection = await helper.nft.mintCollection(alice, {});61    const caller = await helper.eth.createAccountWithBalance(donor);6263    const token = await collection.mintToken(alice, {Ethereum: caller});6465    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);6667    const owner = await contract.methods.ownerOf(token.tokenId).call();6869    expect(owner).to.equal(caller);70  });7172  itEth('name/symbol is available regardless of ERC721Metadata support', async ({helper}) => {73    const collection = await helper.nft.mintCollection(alice, {name: 'test', tokenPrefix: 'TEST'});74    const caller = helper.eth.createAccount();7576    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);7778    expect(await contract.methods.name().call()).to.equal('test');79    expect(await contract.methods.symbol().call()).to.equal('TEST');80  });81});8283describe('Check ERC721 token URI for NFT', () => {84  let donor: IKeyringPair;8586  before(async function() {87    await usingEthPlaygrounds(async (_helper, privateKey) => {88      donor = await privateKey({filename: __filename});89    });90  });9192  async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {93    const owner = await helper.eth.createAccountWithBalance(donor);94    const receiver = helper.eth.createAccount();9596    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);97    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);9899    const result = await contract.methods.mint(receiver).send();100    const tokenId = result.events.Transfer.returnValues.tokenId;101    expect(tokenId).to.be.equal('1');102103    if (propertyKey && propertyValue) {104      // Set URL or suffix105      await contract.methods.setProperty(tokenId, propertyKey, Buffer.from(propertyValue)).send();106    }107108    const event = result.events.Transfer;109    expect(event.address).to.be.equal(collectionAddress);110    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');111    expect(event.returnValues.to).to.be.equal(receiver);112    expect(event.returnValues.tokenId).to.be.equal(tokenId);113114    return {contract, nextTokenId: tokenId};115  }116117  itEth('Empty tokenURI', async ({helper}) => {118    const {contract, nextTokenId} = await setup(helper, '');119    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('');120  });121122  itEth('TokenURI from url', async ({helper}) => {123    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');124    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');125  });126127  itEth('TokenURI from baseURI', async ({helper}) => {128    const {contract, nextTokenId} = await setup(helper, 'BaseURI_');129    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_');130  });131132  itEth('TokenURI from baseURI + suffix', async ({helper}) => {133    const suffix = '/some/suffix';134    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);135    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);136  });137});138139describe('NFT: Plain calls', () => {140  let donor: IKeyringPair;141  let alice: IKeyringPair;142143  before(async function() {144    await usingEthPlaygrounds(async (helper, privateKey) => {145      donor = await privateKey({filename: __filename});146      [alice] = await helper.arrange.createAccounts([10n], donor);147    });148  });149150  itEth('Can perform mint()', async ({helper}) => {151    const owner = await helper.eth.createAccountWithBalance(donor);152    const receiver = helper.eth.createAccount();153154    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', '6', '6', '');155    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);156157    const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();158    const tokenId = result.events.Transfer.returnValues.tokenId;159    expect(tokenId).to.be.equal('1');160161    const event = result.events.Transfer;162    expect(event.address).to.be.equal(collectionAddress);163    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');164    expect(event.returnValues.to).to.be.equal(receiver);165166    expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');167168    // TODO: this wont work right now, need release 919000 first169    // await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();170    // const tokenUri = await contract.methods.tokenURI(nextTokenId).call();171    // expect(tokenUri).to.be.equal(`https://offchain-service.local/token-info/${nextTokenId}`);172  });173174  //TODO: CORE-302 add eth methods175  itEth.skip('Can perform mintBulk()', async ({helper}) => {176    const caller = await helper.eth.createAccountWithBalance(donor);177    const receiver = helper.eth.createAccount();178179    const collection = await helper.nft.mintCollection(alice);180    await collection.addAdmin(alice, {Ethereum: caller});181182    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);183    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', caller);184    {185      const bulkSize = 3;186      const nextTokenId = await contract.methods.nextTokenId().call();187      expect(nextTokenId).to.be.equal('1');188      const result = await contract.methods.mintBulkWithTokenURI(189        receiver,190        Array.from({length: bulkSize}, (_, i) => (191          [+nextTokenId + i, `Test URI ${i}`]192        )),193      ).send({from: caller});194195      const events = result.events.Transfer.sort((a: any, b: any) => +a.returnValues.tokenId - b.returnValues.tokenId);196      for (let i = 0; i < bulkSize; i++) {197        const event = events[i];198        expect(event.address).to.equal(collectionAddress);199        expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');200        expect(event.returnValues.to).to.equal(receiver);201        expect(event.returnValues.tokenId).to.equal(`${+nextTokenId + i}`);202203        expect(await contract.methods.tokenURI(+nextTokenId + i).call()).to.be.equal(`Test URI ${i}`);204      }205    }206  });207208  itEth('Can perform burn()', async ({helper}) => {209    const caller = await helper.eth.createAccountWithBalance(donor);210211    const collection = await helper.nft.mintCollection(alice, {});212    const {tokenId} = await collection.mintToken(alice, {Ethereum: caller});213214    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);215    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', caller);216217    {218      const result = await contract.methods.burn(tokenId).send({from: caller});219220      const event = result.events.Transfer;221      expect(event.address).to.be.equal(collectionAddress);222      expect(event.returnValues.from).to.be.equal(caller);223      expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');224      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);225    }226  });227228  itEth('Can perform approve()', async ({helper}) => {229    const owner = await helper.eth.createAccountWithBalance(donor);230    const spender = helper.eth.createAccount();231232    const collection = await helper.nft.mintCollection(alice, {});233    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});234235    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);236    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);237238    {239      const result = await contract.methods.approve(spender, tokenId).send({from: owner});240241      const event = result.events.Approval;242      expect(event.address).to.be.equal(collectionAddress);243      expect(event.returnValues.owner).to.be.equal(owner);244      expect(event.returnValues.approved).to.be.equal(spender);245      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);246    }247  });248249  itEth('Can perform burnFromCross()', async ({helper, privateKey}) => {250    const alice = privateKey('//Alice');251    const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});252253    const owner = privateKey('//Bob');254    const spender = await helper.eth.createAccountWithBalance(alice, 100n);255256    const token = await collection.mintToken(alice, {Substrate: owner.address});257258    const address = helper.ethAddress.fromCollectionId(collection.collectionId);259    const contract = helper.ethNativeContract.collection(address, 'nft');260261    {262      await token.approve(owner, {Ethereum: spender});263      const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);264      const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender});265      const events = result.events.Transfer;266267      expect(events).to.be.like({268        address,269        event: 'Transfer',270        returnValues: {271          from: helper.address.substrateToEth(owner.address),272          to: '0x0000000000000000000000000000000000000000',273          tokenId: token.tokenId.toString(),274        },275      });276    }277  });278279  itEth('Can perform approveCross()', async ({helper, privateKey}) => {280    const alice = privateKey('//Alice');281    const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});282283    const owner = await helper.eth.createAccountWithBalance(alice, 100n);284    const receiver = privateKey('//Charlie');285286    const token = await collection.mintToken(alice, {Ethereum: owner});287288    const address = helper.ethAddress.fromCollectionId(collection.collectionId);289    const contract = helper.ethNativeContract.collection(address, 'nft');290291    {292      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);293      const result = await contract.methods.approveCross(recieverCross, token.tokenId).send({from: owner});294      const event = result.events.Approval;295      expect(event).to.be.like({296        address: helper.ethAddress.fromCollectionId(collection.collectionId),297        event: 'Approval',298        returnValues: {299          owner,300          approved: helper.address.substrateToEth(receiver.address),301          tokenId: token.tokenId.toString(),302        },303      });304    }305  });306307  itEth('Can perform transferFrom()', async ({helper}) => {308    const owner = await helper.eth.createAccountWithBalance(donor);309    const spender = await helper.eth.createAccountWithBalance(donor);310    const receiver = helper.eth.createAccount();311312    const collection = await helper.nft.mintCollection(alice, {});313    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});314315    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);316    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);317318    await contract.methods.approve(spender, tokenId).send({from: owner});319320    {321      const result = await contract.methods.transferFrom(owner, receiver, tokenId).send({from: spender});322323      const event = result.events.Transfer;324      expect(event.address).to.be.equal(collectionAddress);325      expect(event.returnValues.from).to.be.equal(owner);326      expect(event.returnValues.to).to.be.equal(receiver);327      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);328    }329330    {331      const balance = await contract.methods.balanceOf(receiver).call();332      expect(+balance).to.equal(1);333    }334335    {336      const balance = await contract.methods.balanceOf(owner).call();337      expect(+balance).to.equal(0);338    }339  });340341  itEth('Can perform transfer()', async ({helper}) => {342    const collection = await helper.nft.mintCollection(alice, {});343    const owner = await helper.eth.createAccountWithBalance(donor);344    const receiver = helper.eth.createAccount();345346    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});347348    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);349    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);350351    {352      const result = await contract.methods.transfer(receiver, tokenId).send({from: owner});353354      const event = result.events.Transfer;355      expect(event.address).to.be.equal(collectionAddress);356      expect(event.returnValues.from).to.be.equal(owner);357      expect(event.returnValues.to).to.be.equal(receiver);358      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);359    }360361    {362      const balance = await contract.methods.balanceOf(owner).call();363      expect(+balance).to.equal(0);364    }365366    {367      const balance = await contract.methods.balanceOf(receiver).call();368      expect(+balance).to.equal(1);369    }370  });371});372373describe('NFT: Fees', () => {374  let donor: IKeyringPair;375  let alice: IKeyringPair;376377  before(async function() {378    await usingEthPlaygrounds(async (helper, privateKey) => {379      donor = await privateKey({filename: __filename});380      [alice] = await helper.arrange.createAccounts([10n], donor);381    });382  });383384  itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {385    const owner = await helper.eth.createAccountWithBalance(donor);386    const spender = helper.eth.createAccount();387388    const collection = await helper.nft.mintCollection(alice, {});389    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});390391    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);392393    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, tokenId).send({from: owner}));394    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));395  });396397  itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {398    const owner = await helper.eth.createAccountWithBalance(donor);399    const spender = await helper.eth.createAccountWithBalance(donor);400401    const collection = await helper.nft.mintCollection(alice, {});402    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});403404    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);405406    await contract.methods.approve(spender, tokenId).send({from: owner});407408    const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, tokenId).send({from: spender}));409    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));410  });411412  itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {413    const collection = await helper.nft.mintCollection(donor, {name: 'A', description: 'B', tokenPrefix: 'C'});414415    const owner = privateKey('//Bob');416    const spender = await helper.eth.createAccountWithBalance(donor, 100n);417    const receiver = privateKey('//Charlie');418419    const token = await collection.mintToken(donor, {Substrate: owner.address});420421    const address = helper.ethAddress.fromCollectionId(collection.collectionId);422    const contract = helper.ethNativeContract.collection(address, 'nft');423424    await token.approve(owner, {Ethereum: spender});425426    {427      const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);428      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);429      const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender});430      const event = result.events.Transfer;431      expect(event).to.be.like({432        address: helper.ethAddress.fromCollectionId(collection.collectionId),433        event: 'Transfer',434        returnValues: {435          from: helper.address.substrateToEth(owner.address),436          to: helper.address.substrateToEth(receiver.address),437          tokenId: token.tokenId.toString(),438        },439      });440    }441442    expect(await token.getOwner()).to.be.like({Substrate: receiver.address});443  });444445  itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {446    const owner = await helper.eth.createAccountWithBalance(donor);447    const receiver = helper.eth.createAccount();448449    const collection = await helper.nft.mintCollection(alice, {});450    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});451452    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);453454    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, tokenId).send({from: owner}));455    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));456  });457});458459describe('NFT: Substrate calls', () => {460  let donor: IKeyringPair;461  let alice: IKeyringPair;462463  before(async function() {464    await usingEthPlaygrounds(async (helper, privateKey) => {465      donor = await privateKey({filename: __filename});466      [alice] = await helper.arrange.createAccounts([20n], donor);467    });468  });469470  itEth('Events emitted for mint()', async ({helper}) => {471    const collection = await helper.nft.mintCollection(alice, {});472    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);473    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');474475    const events: any = [];476    contract.events.allEvents((_: any, event: any) => {477      events.push(event);478    });479480    const {tokenId} = await collection.mintToken(alice);481    if (events.length == 0) await helper.wait.newBlocks(1);482    const event = events[0];483484    expect(event.event).to.be.equal('Transfer');485    expect(event.address).to.be.equal(collectionAddress);486    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');487    expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(alice.address));488    expect(event.returnValues.tokenId).to.be.equal(tokenId.toString());489  });490491  itEth('Events emitted for burn()', async ({helper}) => {492    const collection = await helper.nft.mintCollection(alice, {});493    const token = await collection.mintToken(alice);494495    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);496    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');497498    const events: any = [];499    contract.events.allEvents((_: any, event: any) => {500      events.push(event);501    });502503    await token.burn(alice);504    if (events.length == 0) await helper.wait.newBlocks(1);505    const event = events[0];506507    expect(event.event).to.be.equal('Transfer');508    expect(event.address).to.be.equal(collectionAddress);509    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));510    expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');511    expect(event.returnValues.tokenId).to.be.equal(token.tokenId.toString());512  });513514  itEth('Events emitted for approve()', async ({helper}) => {515    const receiver = helper.eth.createAccount();516517    const collection = await helper.nft.mintCollection(alice, {});518    const token = await collection.mintToken(alice);519520    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);521    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');522523    const events: any = [];524    contract.events.allEvents((_: any, event: any) => {525      events.push(event);526    });527528    await token.approve(alice, {Ethereum: receiver});529    if (events.length == 0) await helper.wait.newBlocks(1);530    const event = events[0];531532    expect(event.event).to.be.equal('Approval');533    expect(event.address).to.be.equal(collectionAddress);534    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));535    expect(event.returnValues.approved).to.be.equal(receiver);536    expect(event.returnValues.tokenId).to.be.equal(token.tokenId.toString());537  });538539  itEth('Events emitted for transferFrom()', async ({helper}) => {540    const [bob] = await helper.arrange.createAccounts([10n], donor);541    const receiver = helper.eth.createAccount();542543    const collection = await helper.nft.mintCollection(alice, {});544    const token = await collection.mintToken(alice);545    await token.approve(alice, {Substrate: bob.address});546547    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);548    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');549550    const events: any = [];551    contract.events.allEvents((_: any, event: any) => {552      events.push(event);553    });554555    await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver});556557    if (events.length == 0) await helper.wait.newBlocks(1);558    const event = events[0];559560    expect(event.address).to.be.equal(collectionAddress);561    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));562    expect(event.returnValues.to).to.be.equal(receiver);563    expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);564  });565566  itEth('Events emitted for transfer()', async ({helper}) => {567    const receiver = helper.eth.createAccount();568569    const collection = await helper.nft.mintCollection(alice, {});570    const token = await collection.mintToken(alice);571572    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);573    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');574575    const events: any = [];576    contract.events.allEvents((_: any, event: any) => {577      events.push(event);578    });579580    await token.transfer(alice, {Ethereum: receiver});581582    if (events.length == 0) await helper.wait.newBlocks(1);583    const event = events[0];584585    expect(event.address).to.be.equal(collectionAddress);586    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));587    expect(event.returnValues.to).to.be.equal(receiver);588    expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);589  });590});591592describe('Common metadata', () => {593  let donor: IKeyringPair;594  let alice: IKeyringPair;595596  before(async function() {597    await usingEthPlaygrounds(async (helper, privateKey) => {598      donor = await privateKey({filename: __filename});599      [alice] = await helper.arrange.createAccounts([20n], donor);600    });601  });602603  itEth('Returns collection name', async ({helper}) => {604    const caller = await helper.eth.createAccountWithBalance(donor);605    const tokenPropertyPermissions = [{606      key: 'URI',607      permission: {608        mutable: true,609        collectionAdmin: true,610        tokenOwner: false,611      },612    }];613    const collection = await helper.nft.mintCollection(614      alice,615      {616        name: 'oh River',617        tokenPrefix: 'CHANGE',618        properties: [{key: 'ERC721Metadata', value: '1'}],619        tokenPropertyPermissions,620      },621    );622623    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);624    const name = await contract.methods.name().call();625    expect(name).to.equal('oh River');626  });627628  itEth('Returns symbol name', async ({helper}) => {629    const caller = await helper.eth.createAccountWithBalance(donor);630    const tokenPropertyPermissions = [{631      key: 'URI',632      permission: {633        mutable: true,634        collectionAdmin: true,635        tokenOwner: false,636      },637    }];638    const collection = await helper.nft.mintCollection(639      alice,640      {641        name: 'oh River',642        tokenPrefix: 'CHANGE',643        properties: [{key: 'ERC721Metadata', value: '1'}],644        tokenPropertyPermissions,645      },646    );647648    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);649    const symbol = await contract.methods.symbol().call();650    expect(symbol).to.equal('CHANGE');651  });652});
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -295,14 +295,13 @@
   });
 
   itEth('Can perform transferFromCross()', async ({helper, privateKey}) => {
-    const alice = privateKey('//Alice');
-    const collection = await helper.rft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+    const collection = await helper.rft.mintCollection(donor, {name: 'A', description: 'B', tokenPrefix: 'C'});
 
     const owner = privateKey('//Bob');
-    const spender = await helper.eth.createAccountWithBalance(alice, 100n);
+    const spender = await helper.eth.createAccountWithBalance(donor, 100n);
     const receiver = privateKey('//Charlie');
 
-    const token = await collection.mintToken(alice, 100n, {Substrate: owner.address});
+    const token = await collection.mintToken(donor, 100n, {Substrate: owner.address});
 
     const address = helper.ethAddress.fromCollectionId(collection.collectionId);
     const contract = helper.ethNativeContract.collection(address, 'rft');