git.delta.rocks / unique-network / refs/commits / 7aba0b5d7f8d

difftreelog

basic test

Grigoriy Simonov2022-09-30parent: #239c99e.patch.diff
in: master

3 files changed

modifiedtests/src/eth/allowlist.test.tsdiffbeforeafterboth
--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -19,12 +19,8 @@
 import {isAllowlisted, normalizeAccountId} from '../util/helpers';
 import {
   contractHelpers,
-  createEthAccount,
   createEthAccountWithBalance,
   deployFlipper,
-  evmCollection,
-  evmCollectionHelpers,
-  getCollectionAddressFromResult,
   itWeb3,
 } from './util/helpers';
 import {itEth, usingEthPlaygrounds} from './util/playgrounds';
addedtests/src/eth/proxyContract.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/proxyContract.test.ts
@@ -0,0 +1,124 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+
+import {itEth, expect, usingEthPlaygrounds, EthUniqueHelper} from './util/playgrounds';
+
+describe('EVM payable contracts', () => {
+  let donor: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (_, privateKey) => {
+      donor = privateKey('//Alice');
+    });
+  });
+
+  itEth('Update proxy contract', async({helper}) => {
+    const deployer = await helper.eth.createAccountWithBalance(donor);
+    const proxyContract = await deployProxyContract(helper, deployer);
+    const realContractV1 = await deployRealContractV1(helper, deployer);
+    await proxyContract.methods.updateVersion(realContractV1.options.address).send();
+    await proxyContract.methods.flip().send();
+    await proxyContract.methods.flip().send();
+    await proxyContract.methods.flip().send();
+    const value1 = await proxyContract.methods.getValue().call();
+    const flipCount1 = await proxyContract.methods.getFlipCount().call();
+    expect(value1).to.be.equal(true);
+    expect(flipCount1).to.be.equal('3');
+    const realContractV2 = await deployRealContractV2(helper, deployer);
+    await proxyContract.methods.updateVersion(realContractV2.options.address).send();
+    await proxyContract.methods.flip().send();
+    await proxyContract.methods.flip().send();
+    const value2 = await proxyContract.methods.getValue().call();
+    const flipCount2 = await proxyContract.methods.getFlipCount().call();
+    expect(value2).to.be.equal(true);
+    expect(flipCount2).to.be.equal('1');
+  });
+
+  async function deployProxyContract(helper: EthUniqueHelper, deployer: string) {
+    return await helper.ethContract.deployByCode(deployer, 'ProxyContract', `
+      // SPDX-License-Identifier: UNLICENSED
+      pragma solidity ^0.8.6;
+      
+      contract ProxyContract {
+        address realContract;
+        event NewEvent(uint data);
+        receive() external payable {}
+        constructor() {}
+        function updateVersion(address newContractAddress) external {
+          realContract = newContractAddress;
+        }
+        function flip() external {
+          RealContract(realContract).flip();
+        }
+        function getValue() external view returns (bool) {
+          return RealContract(realContract).getValue();
+        }
+        function getFlipCount() external view returns (uint) {
+            return RealContract(realContract).getFlipCount();
+        }
+      }
+      
+      interface RealContract {
+        function flip() external;
+        function getValue() external view returns (bool);
+        function getFlipCount() external view returns (uint);
+      }`);
+  }
+
+  async function deployRealContractV1(helper: EthUniqueHelper, deployer: string) {
+    return await helper.ethContract.deployByCode(deployer, 'RealContractV1', `
+      // SPDX-License-Identifier: UNLICENSED
+      pragma solidity ^0.8.6;
+  
+      contract RealContractV1 {
+        bool value = false;
+        uint flipCount = 0;
+        function flip() external {
+          value = !value;
+          flipCount++;
+        }
+        function getValue() external view returns (bool) {
+          return value;
+        }
+        function getFlipCount() external view returns (uint) {
+          return flipCount;
+        }
+      }`);
+  }
+
+  async function deployRealContractV2(helper: EthUniqueHelper, deployer: string) {
+    return await helper.ethContract.deployByCode(deployer, 'RealContractV2', `
+      // SPDX-License-Identifier: UNLICENSED
+      pragma solidity ^0.8.6;
+  
+      contract RealContractV2 {
+        bool value = false;
+        uint flipCount = 10;
+        function flip() external {
+          value = !value;
+          flipCount--;
+        }
+        function getValue() external view returns (bool) {
+          return value;
+        }
+        function getFlipCount() external view returns (uint) {
+          return flipCount;
+        }
+      }`);
+  }
+});
\ No newline at end of file
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} 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 {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    };46  47    const knownImports = {} as {[key: string]: string};48    for(const imp of imports) {49      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();50    }51  52    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];74  75    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}97  98class 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=1000n) {146    const account = this.createAccount();147    await this.transferBalanceFromSubstrate(donor, account, amount);148  149    return account;150  }151152  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {153    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));154  }155  156  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  }176177  async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {178    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();179    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);180        181    const result = await collectionHelper.methods.createNonfungibleCollection(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);185186    return {collectionId, collectionAddress};187  }188189  async createRefungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {190    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();191    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);192        193    const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});194195    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);196    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);197198    return {collectionId, collectionAddress};199  }200201  async deployCollectorContract(signer: string): Promise<Contract> {202    return await this.helper.ethContract.deployByCode(signer, 'Collector', `203    // SPDX-License-Identifier: UNLICENSED204    pragma solidity ^0.8.6;205206    contract Collector {207      uint256 collected;208      fallback() external payable {209        giveMoney();210      }211      function giveMoney() public payable {212        collected += msg.value;213      }214      function getCollected() public view returns (uint256) {215        return collected;216      }217      function getUnaccounted() public view returns (uint256) {218        return address(this).balance - collected;219      }220221      function withdraw(address payable target) public {222        target.transfer(collected);223        collected = 0;224      }225    }226  `);227  }228229  async deployFlipper(signer: string): Promise<Contract> {230    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `231    // SPDX-License-Identifier: UNLICENSED232    pragma solidity ^0.8.6;233234    contract Flipper {235      bool value = false;236      function flip() public {237        value = !value;238      }239      function getValue() public view returns (bool) {240        return value;241      }242    }243  `);244  }245246  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {247    const before = await this.helper.balance.getEthereum(user);248    await call();249    // In dev mode, the transaction might not finish processing in time250    await this.helper.wait.newBlocks(1);251    const after = await this.helper.balance.getEthereum(user);252253    return before - after;254  }255}  256257class EthAddressGroup extends EthGroupBase {258  extractCollectionId(address: string): number {259    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');260    return parseInt(address.substr(address.length - 8), 16);261  }262263  fromCollectionId(collectionId: number): string {264    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');265    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);266  }267268  extractTokenId(address: string): {collectionId: number, tokenId: number} {269    if (!address.startsWith('0x'))270      throw 'address not starts with "0x"';271    if (address.length > 42)272      throw 'address length is more than 20 bytes';273    return {274      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),275      tokenId: Number('0x' + address.substring(address.length - 8)),276    };277  }278279  fromTokenId(collectionId: number, tokenId: number): string  {280    return this.helper.util.getTokenAddress({collectionId, tokenId});281  }282283  normalizeAddress(address: string): string {284    return '0x' + address.substring(address.length - 40);285  }286}  287 288289export class EthUniqueHelper extends DevUniqueHelper {290  web3: Web3 | null = null;291  web3Provider: WebsocketProvider | null = null;292293  eth: EthGroup;294  ethAddress: EthAddressGroup;295  ethNativeContract: NativeContractGroup;296  ethContract: ContractGroup;297298  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {299    super(logger);300    this.eth = new EthGroup(this);301    this.ethAddress = new EthAddressGroup(this);302    this.ethNativeContract = new NativeContractGroup(this);303    this.ethContract = new ContractGroup(this);304  }305306  getWeb3(): Web3 {307    if(this.web3 === null) throw Error('Web3 not connected');308    return this.web3;309  }310311  async connectWeb3(wsEndpoint: string) {312    if(this.web3 !== null) return;313    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);314    this.web3 = new Web3(this.web3Provider);315  }316317  async disconnectWeb3() {318    if(this.web3 === null) return;319    this.web3Provider?.connection.close();320    this.web3 = null;321  }322}323  
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} 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 {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    };46  47    const knownImports = {} as {[key: string]: string};48    for(const imp of imports) {49      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();50    }51  52    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];74    return {75      abi: out.abi,76      object: '0x' + out.evm.bytecode.object,77    };78  }7980  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {81    const compiledContract = await this.compile(name, src, imports);82    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);83  }8485  async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {86    const web3 = this.helper.getWeb3();87    const contract = new web3.eth.Contract(abi, undefined, {88      data: object,89      from: signer,90      gas: this.helper.eth.DEFAULT_GAS,91    });92    return await contract.deploy({data: object}).send({from: signer});93  }9495}96  97class NativeContractGroup extends EthGroupBase {9899  contractHelpers(caller: string): Contract {100    const web3 = this.helper.getWeb3();101    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});102  }103104  collectionHelpers(caller: string) {105    const web3 = this.helper.getWeb3();106    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});107  }108109  collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {110    const abi = {111      'nft': nonFungibleAbi,112      'rft': refungibleAbi,113      'ft': fungibleAbi,114    }[mode];115    const web3 = this.helper.getWeb3();116    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});117  }118119  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {120    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);121  }122123  rftToken(address: string, caller?: string): Contract {124    const web3 = this.helper.getWeb3();125    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});126  }127128  rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {129    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);130  }131}132133134class EthGroup extends EthGroupBase {135  DEFAULT_GAS = 2_500_000;136137  createAccount() {138    const web3 = this.helper.getWeb3();139    const account = web3.eth.accounts.create();140    web3.eth.accounts.wallet.add(account.privateKey);141    return account.address;142  }143144  async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {145    const account = this.createAccount();146    await this.transferBalanceFromSubstrate(donor, account, amount);147  148    return account;149  }150151  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {152    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));153  }154  155  async getCollectionCreationFee(signer: string) {156    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);157    return await collectionHelper.methods.collectionCreationFee().call();158  }159160  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {161    if(!gasLimit) gasLimit = this.DEFAULT_GAS;162    const web3 = this.helper.getWeb3();163    const gasPrice = await web3.eth.getGasPrice();164    // TODO: check execution status165    await this.helper.executeExtrinsic(166      signer,167      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],168      true,169    );170  }171172  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {173    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);174  }175176  async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {177    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();178    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);179        180    const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});181182    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);183    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);184185    return {collectionId, collectionAddress};186  }187188  async createRefungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {189    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();190    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);191        192    const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});193194    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);195    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);196197    return {collectionId, collectionAddress};198  }199200  async deployCollectorContract(signer: string): Promise<Contract> {201    return await this.helper.ethContract.deployByCode(signer, 'Collector', `202    // SPDX-License-Identifier: UNLICENSED203    pragma solidity ^0.8.6;204205    contract Collector {206      uint256 collected;207      fallback() external payable {208        giveMoney();209      }210      function giveMoney() public payable {211        collected += msg.value;212      }213      function getCollected() public view returns (uint256) {214        return collected;215      }216      function getUnaccounted() public view returns (uint256) {217        return address(this).balance - collected;218      }219220      function withdraw(address payable target) public {221        target.transfer(collected);222        collected = 0;223      }224    }225  `);226  }227228  async deployFlipper(signer: string): Promise<Contract> {229    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `230    // SPDX-License-Identifier: UNLICENSED231    pragma solidity ^0.8.6;232233    contract Flipper {234      bool value = false;235      function flip() public {236        value = !value;237      }238      function getValue() public view returns (bool) {239        return value;240      }241    }242  `);243  }244245  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {246    const before = await this.helper.balance.getEthereum(user);247    await call();248    // In dev mode, the transaction might not finish processing in time249    await this.helper.wait.newBlocks(1);250    const after = await this.helper.balance.getEthereum(user);251252    return before - after;253  }254}  255256class EthAddressGroup extends EthGroupBase {257  extractCollectionId(address: string): number {258    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');259    return parseInt(address.substr(address.length - 8), 16);260  }261262  fromCollectionId(collectionId: number): string {263    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');264    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);265  }266267  extractTokenId(address: string): {collectionId: number, tokenId: number} {268    if (!address.startsWith('0x'))269      throw 'address not starts with "0x"';270    if (address.length > 42)271      throw 'address length is more than 20 bytes';272    return {273      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),274      tokenId: Number('0x' + address.substring(address.length - 8)),275    };276  }277278  fromTokenId(collectionId: number, tokenId: number): string  {279    return this.helper.util.getTokenAddress({collectionId, tokenId});280  }281282  normalizeAddress(address: string): string {283    return '0x' + address.substring(address.length - 40);284  }285}  286 287288export class EthUniqueHelper extends DevUniqueHelper {289  web3: Web3 | null = null;290  web3Provider: WebsocketProvider | null = null;291292  eth: EthGroup;293  ethAddress: EthAddressGroup;294  ethNativeContract: NativeContractGroup;295  ethContract: ContractGroup;296297  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {298    super(logger);299    this.eth = new EthGroup(this);300    this.ethAddress = new EthAddressGroup(this);301    this.ethNativeContract = new NativeContractGroup(this);302    this.ethContract = new ContractGroup(this);303  }304305  getWeb3(): Web3 {306    if(this.web3 === null) throw Error('Web3 not connected');307    return this.web3;308  }309310  async connectWeb3(wsEndpoint: string) {311    if(this.web3 !== null) return;312    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);313    this.web3 = new Web3(this.web3Provider);314  }315316  async disconnectWeb3() {317    if(this.web3 === null) return;318    this.web3Provider?.connection.close();319    this.web3 = null;320  }321}322