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

difftreelog

test(eth) fix linting errors and warnings

Fahrrader2022-09-05parent: #e6b5df4.patch.diff
in: master

8 files changed

modifiedtests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -15,7 +15,7 @@
 
 import {expect} from 'chai';
 import privateKey from '../substrate/privateKey';
-import { UNIQUE } from '../util/helpers';
+import {UNIQUE} from '../util/helpers';
 import {
   createEthAccount,
   createEthAccountWithBalance, 
@@ -24,7 +24,6 @@
   getCollectionAddressFromResult, 
   itWeb3,
   recordEthFee,
-  subToEth,
 } from './util/helpers';
 
 describe('Add collection admins', () => {
@@ -37,7 +36,7 @@
       .send();
     const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
 
-    const newAdmin = await createEthAccount(web3);
+    const newAdmin = createEthAccount(web3);
     const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
     await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
     const adminList = await api.rpc.unique.adminlist(collectionId);
@@ -92,7 +91,7 @@
     const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
     await collectionEvm.methods.addCollectionAdmin(admin).send();
     
-    const user = await createEthAccount(web3);
+    const user = createEthAccount(web3);
     await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: admin}))
       .to.be.rejectedWith('NoPermission');
 
@@ -114,7 +113,7 @@
     const notAdmin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
     const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
     
-    const user = await createEthAccount(web3);
+    const user = createEthAccount(web3);
     await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: notAdmin}))
       .to.be.rejectedWith('NoPermission');
 
@@ -175,7 +174,7 @@
       .send();
     const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
 
-    const newAdmin = await createEthAccount(web3);
+    const newAdmin = createEthAccount(web3);
     const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
     await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
     {
@@ -226,7 +225,7 @@
 
     const admin0 = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
     await collectionEvm.methods.addCollectionAdmin(admin0).send();
-    const admin1 = await createEthAccount(web3);
+    const admin1 = createEthAccount(web3);
     await collectionEvm.methods.addCollectionAdmin(admin1).send();
 
     await expect(collectionEvm.methods.removeCollectionAdmin(admin1).call({from: admin0}))
@@ -253,7 +252,7 @@
 
     const admin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
     await collectionEvm.methods.addCollectionAdmin(admin).send();
-    const notAdmin = await createEthAccount(web3);
+    const notAdmin = createEthAccount(web3);
 
     await expect(collectionEvm.methods.removeCollectionAdmin(admin).call({from: notAdmin}))
       .to.be.rejectedWith('NoPermission');
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -1,5 +1,5 @@
 import {addToAllowListExpectSuccess, bigIntToSub, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess} from '../util/helpers';
-import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub, subToEth} from './util/helpers';
+import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub} from './util/helpers';
 import nonFungibleAbi from './nonFungibleAbi.json';
 import {expect} from 'chai';
 import {evmToAddress} from '@polkadot/util-crypto';
modifiedtests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -181,7 +181,7 @@
   });
   
   itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
-    const owner = await createEthAccount(web3);
+    const owner = createEthAccount(web3);
     const helper = evmCollectionHelpers(web3, owner);
     const collectionName = 'A';
     const description = 'A';
@@ -194,7 +194,7 @@
 
   itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const notOwner = await createEthAccount(web3);
+    const notOwner = createEthAccount(web3);
     const collectionHelpers = evmCollectionHelpers(web3, owner);
     const result = await collectionHelpers.methods.createNonfungibleCollection('A', 'A', 'A').send();
     const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
modifiedtests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -189,7 +189,7 @@
   });
   
   itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
-    const owner = await createEthAccount(web3);
+    const owner = createEthAccount(web3);
     const helper = evmCollectionHelpers(web3, owner);
     const collectionName = 'A';
     const description = 'A';
@@ -202,7 +202,7 @@
 
   itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const notOwner = await createEthAccount(web3);
+    const notOwner = createEthAccount(web3);
     const collectionHelpers = evmCollectionHelpers(web3, owner);
     const result = await collectionHelpers.methods.createRefungibleCollection('A', 'A', 'A').send();
     const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
modifiedtests/src/eth/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -1,7 +1,7 @@
 import {IKeyringPair} from '@polkadot/types/types';
 import {Contract} from 'web3-eth-contract';
 
-import {itEth, EthUniqueHelper, usingEthPlaygrounds, expect} from '../util/playgrounds'
+import {itEth, EthUniqueHelper, usingEthPlaygrounds, expect} from '../util/playgrounds';
 
 const createNestingCollection = async (
   helper: EthUniqueHelper,
modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE, requirePallets, Pallets} from '../util/helpers';
-import {collectionIdFromAddress, collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
+import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createRefungibleCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
 
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
modifiedtests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/index.ts
+++ b/tests/src/eth/util/playgrounds/index.ts
@@ -33,7 +33,7 @@
     await helper.disconnectWeb3();
     silentConsole.disable();
   }
-}
+};
   
 export async function itEth(name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
   let i: any = it;
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 */56import {readFile} from 'fs/promises';78import Web3 from 'web3';9import {WebsocketProvider} from 'web3-core';10import {Contract} from 'web3-eth-contract';1112import * as solc from 'solc';1314import {evmToAddress} from '@polkadot/util-crypto';15import {IKeyringPair} from '@polkadot/types/types';1617import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';1819import {ContractImports, CompiledContract} from './types';2021// Native contracts ABI22import collectionHelpersAbi from '../../collectionHelpersAbi.json';23import fungibleAbi from '../../fungibleAbi.json';24import nonFungibleAbi from '../../nonFungibleAbi.json';25import refungibleAbi from '../../reFungibleAbi.json';26import refungibleTokenAbi from '../../reFungibleTokenAbi.json';27import contractHelpersAbi from './../contractHelpersAbi.json';2829class EthGroupBase {30  helper: EthUniqueHelper;3132  constructor(helper: EthUniqueHelper) {33    this.helper = helper;34  }35}363738class ContractGroup extends EthGroupBase {39  async findImports(imports?: ContractImports[]){40    if(!imports) return function(path: string) {41      return {error: 'File not found'};42    };43  44    const knownImports = {} as any;45    for(let imp of imports) {46      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();47    }48  49    return function(path: string) {50      if(knownImports.hasOwnProperty(path)) return {contents: knownImports[path]};51      return {error: 'File not found'};52    }53  }5455  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {56    const out = JSON.parse(solc.compile(JSON.stringify({57      language: 'Solidity',58      sources: {59        [`${name}.sol`]: {60          content: src,61        },62      },63      settings: {64        outputSelection: {65          '*': {66            '*': ['*'],67          },68        },69      },70    }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];71  72    return {73      abi: out.abi,74      object: '0x' + out.evm.bytecode.object,75    };76  }7778  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {79    const compiledContract = await this.compile(name, src, imports);80    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);81  }8283  async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {84    const web3 = this.helper.getWeb3();85    const contract = new web3.eth.Contract(abi, undefined, {86      data: object,87      from: signer,88      gas: this.helper.eth.DEFAULT_GAS89    });90    return await contract.deploy({data: object}).send({from: signer});91  }9293}94  95class NativeContractGroup extends EthGroupBase {9697  contractHelpers(caller: string): Contract {98    const web3 = this.helper.getWeb3();99    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});100  }101102  collectionHelpers(caller: string) {103    const web3 = this.helper.getWeb3();104    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});105  }106107  collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {108    const abi = {109      'nft': nonFungibleAbi,110      'rft': refungibleAbi,111      'ft': fungibleAbi112    }[mode];113    const web3 = this.helper.getWeb3();114    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});115  }116117  rftTokenByAddress(address: string, caller?: string): Contract {118    const web3 = this.helper.getWeb3();119    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});120  }121122  rftToken(collectionId: number, tokenId: number, caller?: string): Contract {123    return this.rftTokenByAddress(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);124  }125}126127  128class EthGroup extends EthGroupBase {129  DEFAULT_GAS = 2_500_000;130131  createAccount() {132    const web3 = this.helper.getWeb3();133    const account = web3.eth.accounts.create();134    web3.eth.accounts.wallet.add(account.privateKey);135    return account.address;136  }137138  async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {139    const account = this.createAccount();140    await this.transferBalanceFromSubstrate(donor, account, amount);141  142    return account;143  }144145  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {146    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));147  }148149  async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {150    if(!gasLimit) gasLimit = this.DEFAULT_GAS;151    const web3 = this.helper.getWeb3();152    const gasPrice = await web3.eth.getGasPrice();153    // TODO: check execution status154    await this.helper.executeExtrinsic(155      signer,156      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],157      true, `Unable to perform evm.call`158    );159  }160161  async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {162    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);163        164    const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send();165166    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);167    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);168169    return {collectionId, collectionAddress};170  }171172  async deployCollectorContract(signer: string): Promise<Contract> {173    return await this.helper.ethContract.deployByCode(signer, 'Collector', `174    // SPDX-License-Identifier: UNLICENSED175    pragma solidity ^0.8.6;176177    contract Collector {178      uint256 collected;179      fallback() external payable {180        giveMoney();181      }182      function giveMoney() public payable {183        collected += msg.value;184      }185      function getCollected() public view returns (uint256) {186        return collected;187      }188      function getUnaccounted() public view returns (uint256) {189        return address(this).balance - collected;190      }191192      function withdraw(address payable target) public {193        target.transfer(collected);194        collected = 0;195      }196    }197  `);198  }199}200  201  202class EthAddressGroup extends EthGroupBase {203  extractCollectionId(address: string): number {204    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');205    return parseInt(address.substr(address.length - 8), 16);206  }207208  fromCollectionId(collectionId: number): string {209    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');210    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);211  }212213  extractTokenId(address: string): {collectionId: number, tokenId: number} {214    if (!address.startsWith('0x'))215      throw 'address not starts with "0x"';216    if (address.length > 42)217      throw 'address length is more than 20 bytes';218    return {219      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),220      tokenId: Number('0x' + address.substring(address.length - 8)),221    };222  }223224  fromTokenId(collectionId: number, tokenId: number): string  {225    return this.helper.util.getNestingTokenAddress(collectionId, tokenId);226  }227228  normalizeAddress(address: string): string {229    return '0x' + address.substring(address.length - 40);230  }231}  232 233234export class EthUniqueHelper extends DevUniqueHelper {235  web3: Web3 | null = null;236  web3Provider: WebsocketProvider | null = null;237238  eth: EthGroup;239  ethAddress: EthAddressGroup;240  ethNativeContract: NativeContractGroup;241  ethContract: ContractGroup;242243  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {244    super(logger);245    this.eth = new EthGroup(this);246    this.ethAddress = new EthAddressGroup(this);247    this.ethNativeContract = new NativeContractGroup(this);248    this.ethContract = new ContractGroup(this);249  }250251  getWeb3(): Web3 {252    if(this.web3 === null) throw Error('Web3 not connected');253    return this.web3;254  }255256  async connectWeb3(wsEndpoint: string) {257    if(this.web3 !== null) return;258    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);259    this.web3 = new Web3(this.web3Provider);260  }261262  async disconnectWeb3() {263    if(this.web3 === null) return;264    this.web3Provider?.connection.close();265    this.web3 = null;266  }267}268  
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 */56import {readFile} from 'fs/promises';78import Web3 from 'web3';9import {WebsocketProvider} from 'web3-core';10import {Contract} from 'web3-eth-contract';1112import * as solc from 'solc';1314import {evmToAddress} from '@polkadot/util-crypto';15import {IKeyringPair} from '@polkadot/types/types';1617import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';1819import {ContractImports, CompiledContract} from './types';2021// Native contracts ABI22import collectionHelpersAbi from '../../collectionHelpersAbi.json';23import fungibleAbi from '../../fungibleAbi.json';24import nonFungibleAbi from '../../nonFungibleAbi.json';25import refungibleAbi from '../../reFungibleAbi.json';26import refungibleTokenAbi from '../../reFungibleTokenAbi.json';27import contractHelpersAbi from './../contractHelpersAbi.json';2829class EthGroupBase {30  helper: EthUniqueHelper;3132  constructor(helper: EthUniqueHelper) {33    this.helper = helper;34  }35}363738class ContractGroup extends EthGroupBase {39  async findImports(imports?: ContractImports[]){40    if(!imports) return function(path: string) {41      return {error: `File not found: ${path}`};42    };43  44    const knownImports = {} as any;45    for(const imp of imports) {46      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();47    }48  49    return function(path: string) {50      if(knownImports.hasOwnPropertyDescriptor(path)) return {contents: knownImports[path]};51      return {error: `File not found: ${path}`};52    };53  }5455  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {56    const out = JSON.parse(solc.compile(JSON.stringify({57      language: 'Solidity',58      sources: {59        [`${name}.sol`]: {60          content: src,61        },62      },63      settings: {64        outputSelection: {65          '*': {66            '*': ['*'],67          },68        },69      },70    }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];71  72    return {73      abi: out.abi,74      object: '0x' + out.evm.bytecode.object,75    };76  }7778  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {79    const compiledContract = await this.compile(name, src, imports);80    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);81  }8283  async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {84    const web3 = this.helper.getWeb3();85    const contract = new web3.eth.Contract(abi, undefined, {86      data: object,87      from: signer,88      gas: this.helper.eth.DEFAULT_GAS,89    });90    return await contract.deploy({data: object}).send({from: signer});91  }9293}94  95class NativeContractGroup extends EthGroupBase {9697  contractHelpers(caller: string): Contract {98    const web3 = this.helper.getWeb3();99    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});100  }101102  collectionHelpers(caller: string) {103    const web3 = this.helper.getWeb3();104    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});105  }106107  collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {108    const abi = {109      'nft': nonFungibleAbi,110      'rft': refungibleAbi,111      'ft': fungibleAbi,112    }[mode];113    const web3 = this.helper.getWeb3();114    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});115  }116117  rftTokenByAddress(address: string, caller?: string): Contract {118    const web3 = this.helper.getWeb3();119    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});120  }121122  rftToken(collectionId: number, tokenId: number, caller?: string): Contract {123    return this.rftTokenByAddress(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);124  }125}126127  128class EthGroup extends EthGroupBase {129  DEFAULT_GAS = 2_500_000;130131  createAccount() {132    const web3 = this.helper.getWeb3();133    const account = web3.eth.accounts.create();134    web3.eth.accounts.wallet.add(account.privateKey);135    return account.address;136  }137138  async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {139    const account = this.createAccount();140    await this.transferBalanceFromSubstrate(donor, account, amount);141  142    return account;143  }144145  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {146    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));147  }148149  async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {150    if(!gasLimit) gasLimit = this.DEFAULT_GAS;151    const web3 = this.helper.getWeb3();152    const gasPrice = await web3.eth.getGasPrice();153    // TODO: check execution status154    await this.helper.executeExtrinsic(155      signer,156      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],157      true, 'Unable to perform evm.call',158    );159  }160161  async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {162    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);163        164    const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send();165166    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);167    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);168169    return {collectionId, collectionAddress};170  }171172  async deployCollectorContract(signer: string): Promise<Contract> {173    return await this.helper.ethContract.deployByCode(signer, 'Collector', `174    // SPDX-License-Identifier: UNLICENSED175    pragma solidity ^0.8.6;176177    contract Collector {178      uint256 collected;179      fallback() external payable {180        giveMoney();181      }182      function giveMoney() public payable {183        collected += msg.value;184      }185      function getCollected() public view returns (uint256) {186        return collected;187      }188      function getUnaccounted() public view returns (uint256) {189        return address(this).balance - collected;190      }191192      function withdraw(address payable target) public {193        target.transfer(collected);194        collected = 0;195      }196    }197  `);198  }199}200  201  202class EthAddressGroup extends EthGroupBase {203  extractCollectionId(address: string): number {204    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');205    return parseInt(address.substr(address.length - 8), 16);206  }207208  fromCollectionId(collectionId: number): string {209    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');210    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);211  }212213  extractTokenId(address: string): {collectionId: number, tokenId: number} {214    if (!address.startsWith('0x'))215      throw 'address not starts with "0x"';216    if (address.length > 42)217      throw 'address length is more than 20 bytes';218    return {219      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),220      tokenId: Number('0x' + address.substring(address.length - 8)),221    };222  }223224  fromTokenId(collectionId: number, tokenId: number): string  {225    return this.helper.util.getNestingTokenAddress(collectionId, tokenId);226  }227228  normalizeAddress(address: string): string {229    return '0x' + address.substring(address.length - 40);230  }231}  232 233234export class EthUniqueHelper extends DevUniqueHelper {235  web3: Web3 | null = null;236  web3Provider: WebsocketProvider | null = null;237238  eth: EthGroup;239  ethAddress: EthAddressGroup;240  ethNativeContract: NativeContractGroup;241  ethContract: ContractGroup;242243  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {244    super(logger);245    this.eth = new EthGroup(this);246    this.ethAddress = new EthAddressGroup(this);247    this.ethNativeContract = new NativeContractGroup(this);248    this.ethContract = new ContractGroup(this);249  }250251  getWeb3(): Web3 {252    if(this.web3 === null) throw Error('Web3 not connected');253    return this.web3;254  }255256  async connectWeb3(wsEndpoint: string) {257    if(this.web3 !== null) return;258    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);259    this.web3 = new Web3(this.web3Provider);260  }261262  async disconnectWeb3() {263    if(this.web3 === null) return;264    this.web3Provider?.connection.close();265    this.web3 = null;266  }267}268