git.delta.rocks / unique-network / refs/commits / 36fc5abfd9d0

difftreelog

feat add delete properties

Trubnikov Sergey2022-10-24parent: #ec90529.patch.diff
in: master

17 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -117,8 +117,6 @@
 	/// @param key Property key.
 	#[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]
 	fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {
-		self.consume_store_reads_and_writes(1, 1)?;
-
 		let caller = T::CrossAccountId::from_eth(caller);
 		let key = <Vec<u8>>::from(key)
 			.try_into()
@@ -127,6 +125,24 @@
 		<Pallet<T>>::delete_collection_property(self, &caller, key).map_err(dispatch_to_evm::<T>)
 	}
 
+	/// Delete collection properties.
+	///
+	/// @param keys Properties keys.
+	#[weight(<SelfWeightOf<T>>::delete_collection_properties(keys.len() as u32))]
+	fn delete_collection_properties(&mut self, caller: caller, keys: Vec<string>) -> Result<()> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let keys = keys
+			.into_iter()
+			.map(|key| {
+				<Vec<u8>>::from(key)
+					.try_into()
+					.map_err(|_| Error::Revert("key too large".into()))
+			})
+			.collect::<Result<Vec<_>>>()?;
+
+		<Pallet<T>>::delete_collection_properties(self, &caller, keys).map_err(dispatch_to_evm::<T>)
+	}
+
 	/// Get collection property.
 	///
 	/// @dev Throws error if key not found.
@@ -146,28 +162,34 @@
 
 	/// Get collection properties.
 	///
-	/// @param keys Properties keys.
+	/// @param keys Properties keys. Empty keys for all propertyes.
 	/// @return Vector of properties key/value pairs.
 	fn collection_properties(&self, keys: Vec<string>) -> Result<Vec<(string, bytes)>> {
-		let mut keys_ = Vec::<PropertyKey>::with_capacity(keys.len());
-		for key in keys {
-			keys_.push(
+		let keys = keys
+			.into_iter()
+			.map(|key| {
 				<Vec<u8>>::from(key)
 					.try_into()
-					.map_err(|_| Error::Revert("key too large".into()))?,
-			)
-		}
-		let properties = Pallet::<T>::filter_collection_properties(self.id, Some(keys_))
-			.map_err(dispatch_to_evm::<T>)?;
+					.map_err(|_| Error::Revert("key too large".into()))
+			})
+			.collect::<Result<Vec<_>>>()?;
 
-		let mut properties_ = Vec::<(string, bytes)>::with_capacity(properties.len());
-		for p in properties {
-			let key =
-				string::from_utf8(p.key.into()).map_err(|e| Error::Revert(format!("{}", e)))?;
-			let value = bytes(p.value.to_vec());
-			properties_.push((key, value));
-		}
-		Ok(properties_)
+		let properties = Pallet::<T>::filter_collection_properties(
+			self.id,
+			if keys.is_empty() { None } else { Some(keys) },
+		)
+		.map_err(dispatch_to_evm::<T>)?;
+
+		let properties = properties
+			.into_iter()
+			.map(|p| {
+				let key =
+					string::from_utf8(p.key.into()).map_err(|e| Error::Revert(format!("{}", e)))?;
+				let value = bytes(p.value.to_vec());
+				Ok((key, value))
+			})
+			.collect::<Result<Vec<_>>>()?;
+		Ok(properties)
 	}
 
 	/// Set the sponsor of the collection.
modifiedpallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth
--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -18,7 +18,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x5d354410
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
 contract Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -55,6 +55,17 @@
 		dummy = 0;
 	}
 
+	/// Delete collection properties.
+	///
+	/// @param keys Properties keys.
+	/// @dev EVM selector for this function is: 0xee206ee3,
+	///  or in textual repr: deleteCollectionProperties(string[])
+	function deleteCollectionProperties(string[] memory keys) public {
+		require(false, stub_error);
+		keys;
+		dummy = 0;
+	}
+
 	/// Get collection property.
 	///
 	/// @dev Throws error if key not found.
@@ -72,7 +83,7 @@
 
 	/// Get collection properties.
 	///
-	/// @param keys Properties keys.
+	/// @param keys Properties keys. Empty keys for all propertyes.
 	/// @return Vector of properties key/value pairs.
 	/// @dev EVM selector for this function is: 0x285fb8e6,
 	///  or in textual repr: collectionProperties(string[])
modifiedpallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth
--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -91,7 +91,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x5d354410
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
 contract Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -128,6 +128,17 @@
 		dummy = 0;
 	}
 
+	/// Delete collection properties.
+	///
+	/// @param keys Properties keys.
+	/// @dev EVM selector for this function is: 0xee206ee3,
+	///  or in textual repr: deleteCollectionProperties(string[])
+	function deleteCollectionProperties(string[] memory keys) public {
+		require(false, stub_error);
+		keys;
+		dummy = 0;
+	}
+
 	/// Get collection property.
 	///
 	/// @dev Throws error if key not found.
@@ -145,7 +156,7 @@
 
 	/// Get collection properties.
 	///
-	/// @param keys Properties keys.
+	/// @param keys Properties keys. Empty keys for all propertyes.
 	/// @return Vector of properties key/value pairs.
 	/// @dev EVM selector for this function is: 0x285fb8e6,
 	///  or in textual repr: collectionProperties(string[])
modifiedpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth
--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -91,7 +91,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x5d354410
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
 contract Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -128,6 +128,17 @@
 		dummy = 0;
 	}
 
+	/// Delete collection properties.
+	///
+	/// @param keys Properties keys.
+	/// @dev EVM selector for this function is: 0xee206ee3,
+	///  or in textual repr: deleteCollectionProperties(string[])
+	function deleteCollectionProperties(string[] memory keys) public {
+		require(false, stub_error);
+		keys;
+		dummy = 0;
+	}
+
 	/// Get collection property.
 	///
 	/// @dev Throws error if key not found.
@@ -145,7 +156,7 @@
 
 	/// Get collection properties.
 	///
-	/// @param keys Properties keys.
+	/// @param keys Properties keys. Empty keys for all propertyes.
 	/// @return Vector of properties key/value pairs.
 	/// @dev EVM selector for this function is: 0x285fb8e6,
 	///  or in textual repr: collectionProperties(string[])
modifiedtests/src/eth/api/UniqueFungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x5d354410
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
 interface Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -37,6 +37,13 @@
 	///  or in textual repr: deleteCollectionProperty(string)
 	function deleteCollectionProperty(string memory key) external;
 
+	/// Delete collection properties.
+	///
+	/// @param keys Properties keys.
+	/// @dev EVM selector for this function is: 0xee206ee3,
+	///  or in textual repr: deleteCollectionProperties(string[])
+	function deleteCollectionProperties(string[] memory keys) external;
+
 	/// Get collection property.
 	///
 	/// @dev Throws error if key not found.
@@ -49,7 +56,7 @@
 
 	/// Get collection properties.
 	///
-	/// @param keys Properties keys.
+	/// @param keys Properties keys. Empty keys for all propertyes.
 	/// @return Vector of properties key/value pairs.
 	/// @dev EVM selector for this function is: 0x285fb8e6,
 	///  or in textual repr: collectionProperties(string[])
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -62,7 +62,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x5d354410
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
 interface Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -86,6 +86,13 @@
 	///  or in textual repr: deleteCollectionProperty(string)
 	function deleteCollectionProperty(string memory key) external;
 
+	/// Delete collection properties.
+	///
+	/// @param keys Properties keys.
+	/// @dev EVM selector for this function is: 0xee206ee3,
+	///  or in textual repr: deleteCollectionProperties(string[])
+	function deleteCollectionProperties(string[] memory keys) external;
+
 	/// Get collection property.
 	///
 	/// @dev Throws error if key not found.
@@ -98,7 +105,7 @@
 
 	/// Get collection properties.
 	///
-	/// @param keys Properties keys.
+	/// @param keys Properties keys. Empty keys for all propertyes.
 	/// @return Vector of properties key/value pairs.
 	/// @dev EVM selector for this function is: 0x285fb8e6,
 	///  or in textual repr: collectionProperties(string[])
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -62,7 +62,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x5d354410
+/// @dev the ERC-165 identifier for this interface is 0xb3152af3
 interface Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -86,6 +86,13 @@
 	///  or in textual repr: deleteCollectionProperty(string)
 	function deleteCollectionProperty(string memory key) external;
 
+	/// Delete collection properties.
+	///
+	/// @param keys Properties keys.
+	/// @dev EVM selector for this function is: 0xee206ee3,
+	///  or in textual repr: deleteCollectionProperties(string[])
+	function deleteCollectionProperties(string[] memory keys) external;
+
 	/// Get collection property.
 	///
 	/// @dev Throws error if key not found.
@@ -98,7 +105,7 @@
 
 	/// Get collection properties.
 	///
-	/// @param keys Properties keys.
+	/// @param keys Properties keys. Empty keys for all propertyes.
 	/// @return Vector of properties key/value pairs.
 	/// @dev EVM selector for this function is: 0x285fb8e6,
 	///  or in textual repr: collectionProperties(string[])
modifiedtests/src/eth/collectionProperties.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -16,7 +16,7 @@
 
 import {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util';
 import {Pallets} from '../util';
-import {IProperty, ITokenPropertyPermission} from '../util/playgrounds/types';
+import {IProperty, ITokenPropertyPermission, TCollectionMode} from '../util/playgrounds/types';
 import {IKeyringPair} from '@polkadot/types/types';
 
 describe('EVM collection properties', () => {
@@ -163,29 +163,89 @@
 });
 
 describe('EVM collection property', () => {
-  itEth('Set/read properties', async ({helper, privateKey}) => {
-    const alice = await privateKey('//Alice');
-    const collection = await helper.nft.mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+  let alice: IKeyringPair;
+
+  before(() => {
+    usingEthPlaygrounds(async (_helper, privateKey) => {
+      alice = await privateKey('//Alice');
+    });
+  });
+
+  async function testSetReadProperties(helper: EthUniqueHelper, mode: TCollectionMode) {
+    const collection = await helper[mode].mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
 
     const sender = await helper.eth.createAccountWithBalance(alice, 100n);
     await collection.addAdmin(alice, {Ethereum: sender});
 
     const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
-    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', sender);
+    const contract = helper.ethNativeContract.collection(collectionAddress, mode, sender);
 
-    const key1 = 'key1';
-    const value1 = Buffer.from('value1');
-    
-    const key2 = 'key2';
-    const value2 = Buffer.from('value2');
+    const keys = ['key0', 'key1'];
 
     const writeProperties = [
-      [key1, '0x'+value1.toString('hex')],
-      [key2, '0x'+value2.toString('hex')],
+      helper.ethProperty.property(keys[0], 'value0'),
+      helper.ethProperty.property(keys[1], 'value1'),
     ];
 
     await contract.methods.setCollectionProperties(writeProperties).send();
-    const readProperties = await contract.methods.collectionProperties([key1, key2]).call();
+    const readProperties = await contract.methods.collectionProperties([keys[0], keys[1]]).call();
     expect(readProperties).to.be.like(writeProperties);
+  }
+
+  itEth('Set/read properties ft', async ({helper}) => {
+    await testSetReadProperties(helper, 'ft');
+  });
+  itEth('Set/read properties rft', async ({helper}) => {
+    await testSetReadProperties(helper, 'rft');
+  });
+  itEth('Set/read properties nft', async ({helper}) => {
+    await testSetReadProperties(helper, 'nft');
+  });
+
+  async function testDeleteProperties(helper: EthUniqueHelper, mode: TCollectionMode) {
+    const collection = await helper[mode].mintCollection(alice, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const sender = await helper.eth.createAccountWithBalance(alice, 100n);
+    await collection.addAdmin(alice, {Ethereum: sender});
+
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, mode, sender);
+
+    const keys = ['key0', 'key1', 'key2', 'key3'];
+
+    {
+      const writeProperties = [
+        helper.ethProperty.property(keys[0], 'value0'),
+        helper.ethProperty.property(keys[1], 'value1'),
+        helper.ethProperty.property(keys[2], 'value2'),
+        helper.ethProperty.property(keys[3], 'value3'),
+      ];
+
+      await contract.methods.setCollectionProperties(writeProperties).send();
+      const readProperties = await contract.methods.collectionProperties([keys[0], keys[1], keys[2], keys[3]]).call();
+      expect(readProperties).to.be.like(writeProperties);
+    }
+
+    {
+      const expectProperties = [
+        helper.ethProperty.property(keys[0], 'value0'),
+        helper.ethProperty.property(keys[1], 'value1'),
+      ];
+
+      await contract.methods.deleteCollectionProperties([keys[2], keys[3]]).send();
+      const readProperties = await contract.methods.collectionProperties([]).call();
+      expect(readProperties).to.be.like(expectProperties);
+    }
+  }
+  
+  itEth('Delete properties ft', async ({helper}) => {
+    await testDeleteProperties(helper, 'ft');
+  });
+  itEth('Delete properties rft', async ({helper}) => {
+    await testDeleteProperties(helper, 'rft');
   });
+  itEth('Delete properties nft', async ({helper}) => {
+    await testDeleteProperties(helper, 'nft');
+  });
+    
 });
modifiedtests/src/eth/fungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -293,6 +293,15 @@
     "type": "function"
   },
   {
+    "inputs": [
+      { "internalType": "string[]", "name": "keys", "type": "string[]" }
+    ],
+    "name": "deleteCollectionProperties",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
     "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
     "name": "deleteCollectionProperty",
     "outputs": [],
modifiedtests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -316,6 +316,15 @@
     "type": "function"
   },
   {
+    "inputs": [
+      { "internalType": "string[]", "name": "keys", "type": "string[]" }
+    ],
+    "name": "deleteCollectionProperties",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
     "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
     "name": "deleteCollectionProperty",
     "outputs": [],
modifiedtests/src/eth/reFungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -298,6 +298,15 @@
     "type": "function"
   },
   {
+    "inputs": [
+      { "internalType": "string[]", "name": "keys", "type": "string[]" }
+    ],
+    "name": "deleteCollectionProperties",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
     "inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
     "name": "deleteCollectionProperty",
     "outputs": [],
modifiedtests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -19,3 +19,6 @@
   readonly field_0: string,
   readonly field_1: string | Uint8Array,
 }
+
+export type EthProperty = string[];
+
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/eth/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, TEthCrossAccount, NormalizedEvent} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../collectionHelpersAbi.json';25import fungibleAbi from '../../fungibleAbi.json';26import nonFungibleAbi from '../../nonFungibleAbi.json';27import refungibleAbi from '../../reFungibleAbi.json';28import refungibleTokenAbi from '../../reFungibleTokenAbi.json';29import contractHelpersAbi from './../contractHelpersAbi.json';30import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';3132class EthGroupBase {33  helper: EthUniqueHelper;3435  constructor(helper: EthUniqueHelper) {36    this.helper = helper;37  }38}394041class ContractGroup extends EthGroupBase {42  async findImports(imports?: ContractImports[]){43    if(!imports) return function(path: string) {44      return {error: `File not found: ${path}`};45    };4647    const knownImports = {} as {[key: string]: string};48    for(const imp of imports) {49      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();50    }5152    return function(path: string) {53      if(path in knownImports) return {contents: knownImports[path]};54      return {error: `File not found: ${path}`};55    };56  }5758  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {59    const out = JSON.parse(solc.compile(JSON.stringify({60      language: 'Solidity',61      sources: {62        [`${name}.sol`]: {63          content: src,64        },65      },66      settings: {67        outputSelection: {68          '*': {69            '*': ['*'],70          },71        },72      },73    }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];7475    return {76      abi: out.abi,77      object: '0x' + out.evm.bytecode.object,78    };79  }8081  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {82    const compiledContract = await this.compile(name, src, imports);83    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);84  }8586  async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {87    const web3 = this.helper.getWeb3();88    const contract = new web3.eth.Contract(abi, undefined, {89      data: object,90      from: signer,91      gas: this.helper.eth.DEFAULT_GAS,92    });93    return await contract.deploy({data: object}).send({from: signer});94  }9596}9798class NativeContractGroup extends EthGroupBase {99100  contractHelpers(caller: string): Contract {101    const web3 = this.helper.getWeb3();102    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});103  }104105  collectionHelpers(caller: string) {106    const web3 = this.helper.getWeb3();107    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});108  }109110  collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {111    const abi = {112      'nft': nonFungibleAbi,113      'rft': refungibleAbi,114      'ft': fungibleAbi,115    }[mode];116    const web3 = this.helper.getWeb3();117    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});118  }119120  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {121    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);122  }123124  rftToken(address: string, caller?: string): Contract {125    const web3 = this.helper.getWeb3();126    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});127  }128129  rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {130    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);131  }132}133134135class EthGroup extends EthGroupBase {136  DEFAULT_GAS = 2_500_000;137138  createAccount() {139    const web3 = this.helper.getWeb3();140    const account = web3.eth.accounts.create();141    web3.eth.accounts.wallet.add(account.privateKey);142    return account.address;143  }144145  async createAccountWithBalance(donor: IKeyringPair, amount=100n) {146    const account = this.createAccount();147    await this.transferBalanceFromSubstrate(donor, account, amount);148149    return account;150  }151152  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=100n, inTokens=true) {153    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));154  }155156  async getCollectionCreationFee(signer: string) {157    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);158    return await collectionHelper.methods.collectionCreationFee().call();159  }160161  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {162    if(!gasLimit) gasLimit = this.DEFAULT_GAS;163    const web3 = this.helper.getWeb3();164    const gasPrice = await web3.eth.getGasPrice();165    // TODO: check execution status166    await this.helper.executeExtrinsic(167      signer,168      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],169      true,170    );171  }172173  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {174    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);175  }176  177  async createCollecion(functionName: string, signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {178    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();179    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);180        181    const result = await collectionHelper.methods[functionName](name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});182183    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);184    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);185    const events = this.helper.eth.normalizeEvents(result.events);186    187    return {collectionId, collectionAddress, events};188  }189  190  async createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {191    return this.createCollecion('createNFTCollection', signer, name, description, tokenPrefix);192  }193194  async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {195    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);196197    const {collectionId, collectionAddress, events} = await this.createCollecion('createNFTCollection', signer, name, description, tokenPrefix);198199    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();200201    return {collectionId, collectionAddress, events};202  }203204  async createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {205    return this.createCollecion('createRFTCollection', signer, name, description, tokenPrefix);206  }207208  async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {209    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);210211    const {collectionId, collectionAddress, events} = await this.createCollecion('createRFTCollection', signer, name, description, tokenPrefix);212213    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();214215    return {collectionId, collectionAddress, events};216  }217218  async deployCollectorContract(signer: string): Promise<Contract> {219    return await this.helper.ethContract.deployByCode(signer, 'Collector', `220    // SPDX-License-Identifier: UNLICENSED221    pragma solidity ^0.8.6;222223    contract Collector {224      uint256 collected;225      fallback() external payable {226        giveMoney();227      }228      function giveMoney() public payable {229        collected += msg.value;230      }231      function getCollected() public view returns (uint256) {232        return collected;233      }234      function getUnaccounted() public view returns (uint256) {235        return address(this).balance - collected;236      }237238      function withdraw(address payable target) public {239        target.transfer(collected);240        collected = 0;241      }242    }243  `);244  }245246  async deployFlipper(signer: string): Promise<Contract> {247    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `248    // SPDX-License-Identifier: UNLICENSED249    pragma solidity ^0.8.6;250251    contract Flipper {252      bool value = false;253      function flip() public {254        value = !value;255      }256      function getValue() public view returns (bool) {257        return value;258      }259    }260  `);261  }262263  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {264    const before = await this.helper.balance.getEthereum(user);265    await call();266    // In dev mode, the transaction might not finish processing in time267    await this.helper.wait.newBlocks(1);268    const after = await this.helper.balance.getEthereum(user);269270    return before - after;271  }272273  normalizeEvents(events: any): NormalizedEvent[] {274    const output = [];275    for (const key of Object.keys(events)) {276      if (key.match(/^[0-9]+$/)) {277        output.push(events[key]);278      } else if (Array.isArray(events[key])) {279        output.push(...events[key]);280      } else {281        output.push(events[key]);282      }283    }284    output.sort((a, b) => a.logIndex - b.logIndex);285    return output.map(({address, event, returnValues}) => {286      const args: { [key: string]: string } = {};287      for (const key of Object.keys(returnValues)) {288        if (!key.match(/^[0-9]+$/)) {289          args[key] = returnValues[key];290        }291      }292      return {293        address,294        event,295        args,296      };297    });298  }299300  async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {301    const wrappedCode = async () => {302      await code();303      // In dev mode, the transaction might not finish processing in time304      await this.helper.wait.newBlocks(1);305    };306    return await this.helper.arrange.calculcateFee(address, wrappedCode);307  }308}309310class EthAddressGroup extends EthGroupBase {311  extractCollectionId(address: string): number {312    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');313    return parseInt(address.substr(address.length - 8), 16);314  }315316  fromCollectionId(collectionId: number): string {317    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');318    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);319  }320321  extractTokenId(address: string): {collectionId: number, tokenId: number} {322    if (!address.startsWith('0x'))323      throw 'address not starts with "0x"';324    if (address.length > 42)325      throw 'address length is more than 20 bytes';326    return {327      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),328      tokenId: Number('0x' + address.substring(address.length - 8)),329    };330  }331332  fromTokenId(collectionId: number, tokenId: number): string  {333    return this.helper.util.getTokenAddress({collectionId, tokenId});334  }335336  normalizeAddress(address: string): string {337    return '0x' + address.substring(address.length - 40);338  }339}340341export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;342343export class EthCrossAccountGroup extends EthGroupBase {344  fromAddress(address: TEthereumAccount): TEthCrossAccount {345    return {346      0: address,347      1: '0',348      field_0: address,349      field_1: '0',350    };351  }352353  fromKeyringPair(keyring: IKeyringPair): TEthCrossAccount {354    return {355      0: '0x0000000000000000000000000000000000000000',356      1: keyring.addressRaw,357      field_0: '0x0000000000000000000000000000000000000000',358      field_1: keyring.addressRaw,359    };360  }361}362363export class EthUniqueHelper extends DevUniqueHelper {364  web3: Web3 | null = null;365  web3Provider: WebsocketProvider | null = null;366367  eth: EthGroup;368  ethAddress: EthAddressGroup;369  ethNativeContract: NativeContractGroup;370  ethContract: ContractGroup;371  ethCrossAccount: EthCrossAccountGroup;372373  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {374    options.helperBase = options.helperBase ?? EthUniqueHelper;375376    super(logger, options);377    this.eth = new EthGroup(this);378    this.ethAddress = new EthAddressGroup(this);379    this.ethCrossAccount = new EthCrossAccountGroup(this);380    this.ethNativeContract = new NativeContractGroup(this);381    this.ethContract = new ContractGroup(this);382  }383384  getWeb3(): Web3 {385    if(this.web3 === null) throw Error('Web3 not connected');386    return this.web3;387  }388389  async connectWeb3(wsEndpoint: string) {390    if(this.web3 !== null) return;391    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);392    this.web3 = new Web3(this.web3Provider);393  }394395  async disconnect() {396    if(this.web3 === null) return;397    this.web3Provider?.connection.close();398399    await super.disconnect();400  }401402  clearApi() {403    super.clearApi();404    this.web3 = null;405  }406407  clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {408    const newHelper = super.clone(helperCls, options) as EthUniqueHelper;409    newHelper.web3 = this.web3;410    newHelper.web3Provider = this.web3Provider;411412    return newHelper;413  }414}
after · tests/src/eth/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, TEthCrossAccount, NormalizedEvent, EthProperty} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../collectionHelpersAbi.json';25import fungibleAbi from '../../fungibleAbi.json';26import nonFungibleAbi from '../../nonFungibleAbi.json';27import refungibleAbi from '../../reFungibleAbi.json';28import refungibleTokenAbi from '../../reFungibleTokenAbi.json';29import contractHelpersAbi from './../contractHelpersAbi.json';30import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';31import {TCollectionMode} from '../../../util/playgrounds/types';3233class EthGroupBase {34  helper: EthUniqueHelper;3536  constructor(helper: EthUniqueHelper) {37    this.helper = helper;38  }39}404142class ContractGroup extends EthGroupBase {43  async findImports(imports?: ContractImports[]){44    if(!imports) return function(path: string) {45      return {error: `File not found: ${path}`};46    };4748    const knownImports = {} as {[key: string]: string};49    for(const imp of imports) {50      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();51    }5253    return function(path: string) {54      if(path in knownImports) return {contents: knownImports[path]};55      return {error: `File not found: ${path}`};56    };57  }5859  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {60    const out = JSON.parse(solc.compile(JSON.stringify({61      language: 'Solidity',62      sources: {63        [`${name}.sol`]: {64          content: src,65        },66      },67      settings: {68        outputSelection: {69          '*': {70            '*': ['*'],71          },72        },73      },74    }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];7576    return {77      abi: out.abi,78      object: '0x' + out.evm.bytecode.object,79    };80  }8182  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {83    const compiledContract = await this.compile(name, src, imports);84    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);85  }8687  async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {88    const web3 = this.helper.getWeb3();89    const contract = new web3.eth.Contract(abi, undefined, {90      data: object,91      from: signer,92      gas: this.helper.eth.DEFAULT_GAS,93    });94    return await contract.deploy({data: object}).send({from: signer});95  }9697}9899class NativeContractGroup extends EthGroupBase {100101  contractHelpers(caller: string): Contract {102    const web3 = this.helper.getWeb3();103    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});104  }105106  collectionHelpers(caller: string) {107    const web3 = this.helper.getWeb3();108    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});109  }110111  collection(address: string, mode: TCollectionMode, caller?: string): Contract {112    const abi = {113      'nft': nonFungibleAbi,114      'rft': refungibleAbi,115      'ft': fungibleAbi,116    }[mode];117    const web3 = this.helper.getWeb3();118    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});119  }120121  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {122    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);123  }124125  rftToken(address: string, caller?: string): Contract {126    const web3 = this.helper.getWeb3();127    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});128  }129130  rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {131    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);132  }133}134135136class EthGroup extends EthGroupBase {137  DEFAULT_GAS = 2_500_000;138139  createAccount() {140    const web3 = this.helper.getWeb3();141    const account = web3.eth.accounts.create();142    web3.eth.accounts.wallet.add(account.privateKey);143    return account.address;144  }145146  async createAccountWithBalance(donor: IKeyringPair, amount=100n) {147    const account = this.createAccount();148    await this.transferBalanceFromSubstrate(donor, account, amount);149150    return account;151  }152153  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=100n, inTokens=true) {154    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));155  }156157  async getCollectionCreationFee(signer: string) {158    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);159    return await collectionHelper.methods.collectionCreationFee().call();160  }161162  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {163    if(!gasLimit) gasLimit = this.DEFAULT_GAS;164    const web3 = this.helper.getWeb3();165    const gasPrice = await web3.eth.getGasPrice();166    // TODO: check execution status167    await this.helper.executeExtrinsic(168      signer,169      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],170      true,171    );172  }173174  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {175    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);176  }177  178  async createCollecion(functionName: string, signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {179    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();180    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);181        182    const result = await collectionHelper.methods[functionName](name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});183184    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);185    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);186    const events = this.helper.eth.normalizeEvents(result.events);187    188    return {collectionId, collectionAddress, events};189  }190  191  async createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {192    return this.createCollecion('createNFTCollection', signer, name, description, tokenPrefix);193  }194195  async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {196    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);197198    const {collectionId, collectionAddress, events} = await this.createCollecion('createNFTCollection', signer, name, description, tokenPrefix);199200    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();201202    return {collectionId, collectionAddress, events};203  }204205  async createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {206    return this.createCollecion('createRFTCollection', signer, name, description, tokenPrefix);207  }208209  async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {210    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);211212    const {collectionId, collectionAddress, events} = await this.createCollecion('createRFTCollection', signer, name, description, tokenPrefix);213214    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();215216    return {collectionId, collectionAddress, events};217  }218219  async deployCollectorContract(signer: string): Promise<Contract> {220    return await this.helper.ethContract.deployByCode(signer, 'Collector', `221    // SPDX-License-Identifier: UNLICENSED222    pragma solidity ^0.8.6;223224    contract Collector {225      uint256 collected;226      fallback() external payable {227        giveMoney();228      }229      function giveMoney() public payable {230        collected += msg.value;231      }232      function getCollected() public view returns (uint256) {233        return collected;234      }235      function getUnaccounted() public view returns (uint256) {236        return address(this).balance - collected;237      }238239      function withdraw(address payable target) public {240        target.transfer(collected);241        collected = 0;242      }243    }244  `);245  }246247  async deployFlipper(signer: string): Promise<Contract> {248    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `249    // SPDX-License-Identifier: UNLICENSED250    pragma solidity ^0.8.6;251252    contract Flipper {253      bool value = false;254      function flip() public {255        value = !value;256      }257      function getValue() public view returns (bool) {258        return value;259      }260    }261  `);262  }263264  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {265    const before = await this.helper.balance.getEthereum(user);266    await call();267    // In dev mode, the transaction might not finish processing in time268    await this.helper.wait.newBlocks(1);269    const after = await this.helper.balance.getEthereum(user);270271    return before - after;272  }273274  normalizeEvents(events: any): NormalizedEvent[] {275    const output = [];276    for (const key of Object.keys(events)) {277      if (key.match(/^[0-9]+$/)) {278        output.push(events[key]);279      } else if (Array.isArray(events[key])) {280        output.push(...events[key]);281      } else {282        output.push(events[key]);283      }284    }285    output.sort((a, b) => a.logIndex - b.logIndex);286    return output.map(({address, event, returnValues}) => {287      const args: { [key: string]: string } = {};288      for (const key of Object.keys(returnValues)) {289        if (!key.match(/^[0-9]+$/)) {290          args[key] = returnValues[key];291        }292      }293      return {294        address,295        event,296        args,297      };298    });299  }300301  async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {302    const wrappedCode = async () => {303      await code();304      // In dev mode, the transaction might not finish processing in time305      await this.helper.wait.newBlocks(1);306    };307    return await this.helper.arrange.calculcateFee(address, wrappedCode);308  }309}310311class EthAddressGroup extends EthGroupBase {312  extractCollectionId(address: string): number {313    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');314    return parseInt(address.substr(address.length - 8), 16);315  }316317  fromCollectionId(collectionId: number): string {318    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');319    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);320  }321322  extractTokenId(address: string): {collectionId: number, tokenId: number} {323    if (!address.startsWith('0x'))324      throw 'address not starts with "0x"';325    if (address.length > 42)326      throw 'address length is more than 20 bytes';327    return {328      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),329      tokenId: Number('0x' + address.substring(address.length - 8)),330    };331  }332333  fromTokenId(collectionId: number, tokenId: number): string  {334    return this.helper.util.getTokenAddress({collectionId, tokenId});335  }336337  normalizeAddress(address: string): string {338    return '0x' + address.substring(address.length - 40);339  }340}  341342export class EthPropertyGroup extends EthGroupBase {343  property(key: string, value: string): EthProperty {344    return [345      key, 346      '0x'+Buffer.from(value).toString('hex'),347    ];348  }349}350export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;351352export class EthCrossAccountGroup extends EthGroupBase {353  fromAddress(address: TEthereumAccount): TEthCrossAccount {354    return {355      0: address,356      1: '0',357      field_0: address,358      field_1: '0',359    };360  }361362  fromKeyringPair(keyring: IKeyringPair): TEthCrossAccount {363    return {364      0: '0x0000000000000000000000000000000000000000',365      1: keyring.addressRaw,366      field_0: '0x0000000000000000000000000000000000000000',367      field_1: keyring.addressRaw,368    };369  }370}371372export class EthUniqueHelper extends DevUniqueHelper {373  web3: Web3 | null = null;374  web3Provider: WebsocketProvider | null = null;375376  eth: EthGroup;377  ethAddress: EthAddressGroup;378  ethNativeContract: NativeContractGroup;379  ethContract: ContractGroup;380  ethCrossAccount: EthCrossAccountGroup;381  ethProperty: EthPropertyGroup;382383  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {384    options.helperBase = options.helperBase ?? EthUniqueHelper;385386    super(logger, options);387    this.eth = new EthGroup(this);388    this.ethAddress = new EthAddressGroup(this);389    this.ethCrossAccount = new EthCrossAccountGroup(this);390    this.ethNativeContract = new NativeContractGroup(this);391    this.ethContract = new ContractGroup(this);392    this.ethProperty = new EthPropertyGroup(this);393  }394395  getWeb3(): Web3 {396    if(this.web3 === null) throw Error('Web3 not connected');397    return this.web3;398  }399400  async connectWeb3(wsEndpoint: string) {401    if(this.web3 !== null) return;402    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);403    this.web3 = new Web3(this.web3Provider);404  }405406  async disconnect() {407    if(this.web3 === null) return;408    this.web3Provider?.connection.close();409410    await super.disconnect();411  }412413  clearApi() {414    super.clearApi();415    this.web3 = null;416  }417418  clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {419    const newHelper = super.clone(helperCls, options) as EthUniqueHelper;420    newHelper.web3 = this.web3;421    newHelper.web3Provider = this.web3Provider;422423    return newHelper;424  }425}
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -224,3 +224,4 @@
 export type TRelayNetworks = 'rococo' | 'westend';
 export type TNetworks = TUniqueNetworks | TSiblingNetworkds | TRelayNetworks;
 export type TSigner = IKeyringPair; // | 'string'
+export type TCollectionMode = 'nft' | 'rft' | 'ft';