git.delta.rocks / unique-network / refs/commits / 60662ccc0c31

difftreelog

fix build

Trubnikov Sergey2023-04-21parent: #d3a59ed.patch.diff
in: master

4 files changed

modifiedpallets/balances-adapter/src/erc.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/erc.rs
+++ b/pallets/balances-adapter/src/erc.rs
@@ -100,7 +100,7 @@
 			amount,
 			ExistenceRequirement::KeepAlive,
 		)
-		.map_err(dispatch_to_evm::<T>);
+		.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
 
@@ -117,7 +117,7 @@
 		let to = T::CrossAccountId::from_eth(to);
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
 
-		if (from != to) {
+		if from != to {
 			return Err("no permission".into());
 		}
 		// let budget = self
@@ -132,7 +132,7 @@
 			amount,
 			ExistenceRequirement::KeepAlive,
 		)
-		.map_err(dispatch_to_evm::<T>);
+		.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
 }
@@ -165,7 +165,7 @@
 			amount,
 			ExistenceRequirement::KeepAlive,
 		)
-		.map_err(dispatch_to_evm::<T>);
+		.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
 
@@ -182,7 +182,7 @@
 		let to = to.into_sub_cross_account::<T>()?;
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
 
-		if (from != to) {
+		if from != to {
 			return Err("no permission".into());
 		}
 
@@ -198,7 +198,7 @@
 			amount,
 			ExistenceRequirement::KeepAlive,
 		)
-		.map_err(dispatch_to_evm::<T>);
+		.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
 }
modifiedpallets/balances-adapter/src/lib.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/lib.rs
+++ b/pallets/balances-adapter/src/lib.rs
@@ -2,12 +2,14 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 #![warn(missing_docs)]
 
+extern crate alloc;
 pub use pallet::*;
 
 pub mod erc;
 
 #[frame_support::pallet]
 pub mod pallet {
+	use alloc::string::String;
 	use frame_support::traits::Get;
 	use sp_core::U256;
 
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -14,6 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
+use alloc::string::{String, ToString};
 use frame_support::parameter_types;
 use sp_runtime::traits::AccountIdConversion;
 use crate::{
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 solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {ArrangeGroup, DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, CrossAddress, NormalizedEvent, EthProperty} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../abi/collectionHelpers.json' assert {type: 'json'};25import fungibleAbi from '../../abi/fungible.json' assert {type: 'json'};26import fungibleDeprecatedAbi from '../../abi/fungibleDeprecated.json' assert {type: 'json'};27import nonFungibleAbi from '../../abi/nonFungible.json' assert {type: 'json'};28import nonFungibleDeprecatedAbi from '../../abi/nonFungibleDeprecated.json' assert {type: 'json'};29import refungibleAbi from '../../abi/reFungible.json' assert {type: 'json'};30import refungibleDeprecatedAbi from '../../abi/reFungibleDeprecated.json' assert {type: 'json'};31import refungibleTokenAbi from '../../abi/reFungibleToken.json' assert {type: 'json'};32import refungibleTokenDeprecatedAbi from '../../abi/reFungibleTokenDeprecated.json' assert {type: 'json'};33import contractHelpersAbi from '../../abi/contractHelpers.json' assert {type: 'json'};34import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';35import {TCollectionMode} from '../../../util/playgrounds/types';3637class EthGroupBase {38  helper: EthUniqueHelper;39  gasPrice?: string;4041  constructor(helper: EthUniqueHelper) {42    this.helper = helper;43  }44  async getGasPrice() {45    if (this.gasPrice)46      return this.gasPrice;47    this.gasPrice = await this.helper.getWeb3().eth.getGasPrice();48    return this.gasPrice;49  }50}515253class ContractGroup extends EthGroupBase {54  async findImports(imports?: ContractImports[]) {55    if (!imports) return function(path: string) {56      return {error: `File not found: ${path}`};57    };5859    const knownImports = {} as { [key: string]: string };60    for (const imp of imports) {61      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();62    }6364    return function(path: string) {65      if (path in knownImports) return {contents: knownImports[path]};66      return {error: `File not found: ${path}`};67    };68  }6970  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {71    const compiled = JSON.parse(solc.compile(JSON.stringify({72      language: 'Solidity',73      sources: {74        [`${name}.sol`]: {75          content: src,76        },77      },78      settings: {79        outputSelection: {80          '*': {81            '*': ['*'],82          },83        },84      },85    }), {import: await this.findImports(imports)}));8687    const hasErrors = compiled['errors']88      && compiled['errors'].length > 089      && compiled.errors.some(function(err: any) {90        return err.severity == 'error';91      });9293    if (hasErrors) {94      throw compiled.errors;95    }96    const out = compiled.contracts[`${name}.sol`][name];9798    return {99      abi: out.abi,100      object: '0x' + out.evm.bytecode.object,101    };102  }103104  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[], gas?: number): Promise<Contract> {105    const compiledContract = await this.compile(name, src, imports);106    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object, gas);107  }108109  async deployByAbi(signer: string, abi: any, object: string, gas?: number): Promise<Contract> {110    const web3 = this.helper.getWeb3();111    const contract = new web3.eth.Contract(abi, undefined, {112      data: object,113      from: signer,114      gas: gas ?? this.helper.eth.DEFAULT_GAS,115      gasPrice: await this.getGasPrice(),116    });117    return await contract.deploy({data: object}).send({from: signer});118  }119120}121122class NativeContractGroup extends EthGroupBase {123124  async contractHelpers(caller: string): Promise<Contract> {125    const web3 = this.helper.getWeb3();126    return new web3.eth.Contract(contractHelpersAbi as any, this.helper.getApi().consts.evmContractHelpers.contractAddress.toString(), {127      from: caller,128      gas: this.helper.eth.DEFAULT_GAS,129      gasPrice: await this.getGasPrice(),130    });131  }132133  async collectionHelpers(caller: string) {134    const web3 = this.helper.getWeb3();135    return new web3.eth.Contract(collectionHelpersAbi as any, this.helper.getApi().consts.common.contractAddress.toString(), {136      from: caller,137      gas: this.helper.eth.DEFAULT_GAS,138      gasPrice: await this.getGasPrice(),139    });140  }141142  async collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false) {143    let abi = {144      'nft': nonFungibleAbi,145      'rft': refungibleAbi,146      'ft': fungibleAbi,147    }[mode];148    if (mergeDeprecated) {149      const deprecated = {150        'nft': nonFungibleDeprecatedAbi,151        'rft': refungibleDeprecatedAbi,152        'ft': fungibleDeprecatedAbi,153      }[mode];154      abi = [...abi, ...deprecated];155    }156    const web3 = this.helper.getWeb3();157    return new web3.eth.Contract(abi as any, address, {158      gas: this.helper.eth.DEFAULT_GAS,159      gasPrice: await this.getGasPrice(),160      ...(caller ? {from: caller} : {}),161    });162  }163164  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string, mergeDeprecated = false) {165    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller, mergeDeprecated);166  }167168  async rftToken(address: string, caller?: string, mergeDeprecated = false) {169    const web3 = this.helper.getWeb3();170    const abi = mergeDeprecated ? [...refungibleTokenAbi, ...refungibleTokenDeprecatedAbi] : refungibleTokenAbi;171    return new web3.eth.Contract(abi as any, address, {172      gas: this.helper.eth.DEFAULT_GAS,173      gasPrice: await this.getGasPrice(),174      ...(caller ? {from: caller} : {}),175    });176  }177178  rftTokenById(collectionId: number, tokenId: number, caller?: string, mergeDeprecated = false) {179    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller, mergeDeprecated);180  }181}182183184class EthGroup extends EthGroupBase {185  DEFAULT_GAS = 2_500_000;186187  createAccount() {188    const web3 = this.helper.getWeb3();189    const account = web3.eth.accounts.create();190    web3.eth.accounts.wallet.add(account.privateKey);191    return account.address;192  }193194  async createAccountWithBalance(donor: IKeyringPair, amount = 600n) {195    const account = this.createAccount();196    await this.transferBalanceFromSubstrate(donor, account, amount);197198    return account;199  }200201  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount = 100n, inTokens = true) {202    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));203  }204205  async getCollectionCreationFee(signer: string) {206    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);207    return await collectionHelper.methods.collectionCreationFee().call();208  }209210  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {211    if (!gasLimit) gasLimit = this.DEFAULT_GAS;212    const web3 = this.helper.getWeb3();213    const gasPrice = await web3.eth.getGasPrice();214    // TODO: check execution status215    await this.helper.executeExtrinsic(216      signer,217      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],218      true,219    );220  }221222  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {223    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);224  }225226  createCollectionMethodName(mode: TCollectionMode) {227    switch (mode) {228      case 'ft':229        return 'createFTCollection';230      case 'nft':231        return 'createNFTCollection';232      case 'rft':233        return 'createRFTCollection';234    }235  }236237  async createCollection(mode: TCollectionMode, signer: string, name: string, description: string, tokenPrefix: string, decimals = 18, mergeDeprecated = false): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[], collection: Contract }> {238    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();239    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);240    const functionName: string = this.createCollectionMethodName(mode);241242    const functionParams = mode === 'ft' ? [name, decimals, description, tokenPrefix] : [name, description, tokenPrefix];243    const result = await collectionHelper.methods[functionName](...functionParams).send({value: Number(collectionCreationPrice)});244245    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);246    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);247    const events = this.helper.eth.normalizeEvents(result.events);248    const collection = await this.helper.ethNativeContract.collectionById(collectionId, mode, signer, mergeDeprecated);249250    return {collectionId, collectionAddress, events, collection};251  }252253  createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {254    return this.createCollection('nft', signer, name, description, tokenPrefix);255  }256257  async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {258    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);259260    const {collectionId, collectionAddress, events} = await this.createCollection('nft', signer, name, description, tokenPrefix);261262    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();263264    return {collectionId, collectionAddress, events};265  }266267  createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {268    return this.createCollection('rft', signer, name, description, tokenPrefix);269  }270271  createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {272    return this.createCollection('ft', signer, name, description, tokenPrefix, decimals);273  }274275  async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {276    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);277278    const {collectionId, collectionAddress, events} = await this.createCollection('rft', signer, name, description, tokenPrefix);279280    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();281282    return {collectionId, collectionAddress, events};283  }284285  async deployCollectorContract(signer: string): Promise<Contract> {286    return await this.helper.ethContract.deployByCode(signer, 'Collector', `287    // SPDX-License-Identifier: UNLICENSED288    pragma solidity ^0.8.6;289290    contract Collector {291      uint256 collected;292      fallback() external payable {293        giveMoney();294      }295      function giveMoney() public payable {296        collected += msg.value;297      }298      function getCollected() public view returns (uint256) {299        return collected;300      }301      function getUnaccounted() public view returns (uint256) {302        return address(this).balance - collected;303      }304305      function withdraw(address payable target) public {306        target.transfer(collected);307        collected = 0;308      }309    }310  `);311  }312313  async deployFlipper(signer: string): Promise<Contract> {314    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `315    // SPDX-License-Identifier: UNLICENSED316    pragma solidity ^0.8.6;317318    contract Flipper {319      bool value = false;320      function flip() public {321        value = !value;322      }323      function getValue() public view returns (bool) {324        return value;325      }326    }327  `);328  }329330  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {331    const before = await this.helper.balance.getEthereum(user);332    await call();333    // In dev mode, the transaction might not finish processing in time334    await this.helper.wait.newBlocks(1);335    const after = await this.helper.balance.getEthereum(user);336337    return before - after;338  }339340  normalizeEvents(events: any): NormalizedEvent[] {341    const output = [];342    for (const key of Object.keys(events)) {343      if (key.match(/^[0-9]+$/)) {344        output.push(events[key]);345      } else if (Array.isArray(events[key])) {346        output.push(...events[key]);347      } else {348        output.push(events[key]);349      }350    }351    output.sort((a, b) => a.logIndex - b.logIndex);352    return output.map(({address, event, returnValues}) => {353      const args: { [key: string]: string } = {};354      for (const key of Object.keys(returnValues)) {355        if (!key.match(/^[0-9]+$/)) {356          args[key] = returnValues[key];357        }358      }359      return {360        address,361        event,362        args,363      };364    });365  }366367  async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {368    const wrappedCode = async () => {369      await code();370      // In dev mode, the transaction might not finish processing in time371      await this.helper.wait.newBlocks(1);372    };373    return await this.helper.arrange.calculcateFee(address, wrappedCode);374  }375}376377class EthAddressGroup extends EthGroupBase {378  extractCollectionId(address: string): number {379    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');380    return parseInt(address.substr(address.length - 8), 16);381  }382383  fromCollectionId(collectionId: number): string {384    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');385    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);386  }387388  extractTokenId(address: string): { collectionId: number, tokenId: number } {389    if (!address.startsWith('0x'))390      throw 'address not starts with "0x"';391    if (address.length > 42)392      throw 'address length is more than 20 bytes';393    return {394      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),395      tokenId: Number('0x' + address.substring(address.length - 8)),396    };397  }398399  fromTokenId(collectionId: number, tokenId: number): string {400    return this.helper.util.getTokenAddress({collectionId, tokenId});401  }402403  normalizeAddress(address: string): string {404    return '0x' + address.substring(address.length - 40);405  }406}407export class EthPropertyGroup extends EthGroupBase {408  property(key: string, value: string): EthProperty {409    return [410      key,411      '0x' + Buffer.from(value).toString('hex'),412    ];413  }414}415export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;416417export class EthCrossAccountGroup extends EthGroupBase {418  createAccount(): CrossAddress {419    return this.fromAddress(this.helper.eth.createAccount());420  }421422  async createAccountWithBalance(donor: IKeyringPair, amount = 100n) {423    return this.fromAddress(await this.helper.eth.createAccountWithBalance(donor, amount));424  }425426  fromAddress(address: TEthereumAccount): CrossAddress {427    return {428      eth: address,429      sub: '0',430    };431  }432433  fromKeyringPair(keyring: IKeyringPair): CrossAddress {434    return {435      eth: '0x0000000000000000000000000000000000000000',436      sub: keyring.addressRaw,437    };438  }439}440441export class FeeGas {442  fee: number | bigint = 0n;443444  gas: number | bigint = 0n;445446  public static async build(helper: EthUniqueHelper, fee: bigint): Promise<FeeGas> {447    const instance = new FeeGas();448    instance.fee = instance.convertToTokens(fee);449    instance.gas = await instance.convertToGas(fee, helper);450    return instance;451  }452453  private async convertToGas(fee: bigint, helper: EthUniqueHelper): Promise<bigint> {454    const gasPrice = BigInt(await helper.getWeb3().eth.getGasPrice());455    return fee / gasPrice;456  }457458  private convertToTokens(value: bigint, nominal = 1_000_000_000_000_000_000n): number {459    return Number((value * 1000n) / nominal) / 1000;460  }461}462463class EthArrangeGroup extends ArrangeGroup {464  helper: EthUniqueHelper;465466  constructor(helper: EthUniqueHelper) {467    super(helper);468    this.helper = helper;469  }470471  async calculcateFeeGas(payer: ICrossAccountId, promise: () => Promise<any>): Promise<FeeGas> {472    const fee = await this.calculcateFee(payer, promise);473    return await FeeGas.build(this.helper, fee);474  }475}476export class EthUniqueHelper extends DevUniqueHelper {477  web3: Web3 | null = null;478  web3Provider: WebsocketProvider | null = null;479480  eth: EthGroup;481  ethAddress: EthAddressGroup;482  ethCrossAccount: EthCrossAccountGroup;483  ethNativeContract: NativeContractGroup;484  ethContract: ContractGroup;485  ethProperty: EthPropertyGroup;486  arrange: EthArrangeGroup;487  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: { [key: string]: any } = {}) {488    options.helperBase = options.helperBase ?? EthUniqueHelper;489490    super(logger, options);491    this.eth = new EthGroup(this);492    this.ethAddress = new EthAddressGroup(this);493    this.ethCrossAccount = new EthCrossAccountGroup(this);494    this.ethNativeContract = new NativeContractGroup(this);495    this.ethContract = new ContractGroup(this);496    this.ethProperty = new EthPropertyGroup(this);497    this.arrange = new EthArrangeGroup(this);498    super.arrange = this.arrange;499  }500501  getWeb3(): Web3 {502    if (this.web3 === null) throw Error('Web3 not connected');503    return this.web3;504  }505506  connectWeb3(wsEndpoint: string) {507    if (this.web3 !== null) return;508    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);509    this.web3 = new Web3(this.web3Provider);510  }511512  async disconnect() {513    if (this.web3 === null) return;514    this.web3Provider?.connection.close();515516    await super.disconnect();517  }518519  clearApi() {520    super.clearApi();521    this.web3 = null;522  }523524  clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {525    const newHelper = super.clone(helperCls, options) as EthUniqueHelper;526    newHelper.web3 = this.web3;527    newHelper.web3Provider = this.web3Provider;528529    return newHelper;530  }531}
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 solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {ArrangeGroup, DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, CrossAddress, NormalizedEvent, EthProperty} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../abi/collectionHelpers.json' assert {type: 'json'};25import nativeFungibleAbi from '../../abi/nativeFungible.json' assert {type: 'json'};26import fungibleAbi from '../../abi/fungible.json' assert {type: 'json'};27import fungibleDeprecatedAbi from '../../abi/fungibleDeprecated.json' assert {type: 'json'};28import nonFungibleAbi from '../../abi/nonFungible.json' assert {type: 'json'};29import nonFungibleDeprecatedAbi from '../../abi/nonFungibleDeprecated.json' assert {type: 'json'};30import refungibleAbi from '../../abi/reFungible.json' assert {type: 'json'};31import refungibleDeprecatedAbi from '../../abi/reFungibleDeprecated.json' assert {type: 'json'};32import refungibleTokenAbi from '../../abi/reFungibleToken.json' assert {type: 'json'};33import refungibleTokenDeprecatedAbi from '../../abi/reFungibleTokenDeprecated.json' assert {type: 'json'};34import contractHelpersAbi from '../../abi/contractHelpers.json' assert {type: 'json'};35import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';36import {TCollectionMode} from '../../../util/playgrounds/types';3738class EthGroupBase {39  helper: EthUniqueHelper;40  gasPrice?: string;4142  constructor(helper: EthUniqueHelper) {43    this.helper = helper;44  }45  async getGasPrice() {46    if (this.gasPrice)47      return this.gasPrice;48    this.gasPrice = await this.helper.getWeb3().eth.getGasPrice();49    return this.gasPrice;50  }51}525354class ContractGroup extends EthGroupBase {55  async findImports(imports?: ContractImports[]) {56    if (!imports) return function(path: string) {57      return {error: `File not found: ${path}`};58    };5960    const knownImports = {} as { [key: string]: string };61    for (const imp of imports) {62      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();63    }6465    return function(path: string) {66      if (path in knownImports) return {contents: knownImports[path]};67      return {error: `File not found: ${path}`};68    };69  }7071  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {72    const compiled = JSON.parse(solc.compile(JSON.stringify({73      language: 'Solidity',74      sources: {75        [`${name}.sol`]: {76          content: src,77        },78      },79      settings: {80        outputSelection: {81          '*': {82            '*': ['*'],83          },84        },85      },86    }), {import: await this.findImports(imports)}));8788    const hasErrors = compiled['errors']89      && compiled['errors'].length > 090      && compiled.errors.some(function(err: any) {91        return err.severity == 'error';92      });9394    if (hasErrors) {95      throw compiled.errors;96    }97    const out = compiled.contracts[`${name}.sol`][name];9899    return {100      abi: out.abi,101      object: '0x' + out.evm.bytecode.object,102    };103  }104105  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[], gas?: number): Promise<Contract> {106    const compiledContract = await this.compile(name, src, imports);107    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object, gas);108  }109110  async deployByAbi(signer: string, abi: any, object: string, gas?: number): Promise<Contract> {111    const web3 = this.helper.getWeb3();112    const contract = new web3.eth.Contract(abi, undefined, {113      data: object,114      from: signer,115      gas: gas ?? this.helper.eth.DEFAULT_GAS,116      gasPrice: await this.getGasPrice(),117    });118    return await contract.deploy({data: object}).send({from: signer});119  }120121}122123class NativeContractGroup extends EthGroupBase {124125  async contractHelpers(caller: string): Promise<Contract> {126    const web3 = this.helper.getWeb3();127    return new web3.eth.Contract(contractHelpersAbi as any, this.helper.getApi().consts.evmContractHelpers.contractAddress.toString(), {128      from: caller,129      gas: this.helper.eth.DEFAULT_GAS,130      gasPrice: await this.getGasPrice(),131    });132  }133134  async collectionHelpers(caller: string) {135    const web3 = this.helper.getWeb3();136    return new web3.eth.Contract(collectionHelpersAbi as any, this.helper.getApi().consts.common.contractAddress.toString(), {137      from: caller,138      gas: this.helper.eth.DEFAULT_GAS,139      gasPrice: await this.getGasPrice(),140    });141  }142143  async collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false) {144    let abi = {145      'nft': nonFungibleAbi,146      'rft': refungibleAbi,147      'ft': fungibleAbi,148    }[mode];149    if (mergeDeprecated) {150      const deprecated = {151        'nft': nonFungibleDeprecatedAbi,152        'rft': refungibleDeprecatedAbi,153        'ft': fungibleDeprecatedAbi,154      }[mode];155      abi = [...abi, ...deprecated];156    }157    const web3 = this.helper.getWeb3();158    return new web3.eth.Contract(abi as any, address, {159      gas: this.helper.eth.DEFAULT_GAS,160      gasPrice: await this.getGasPrice(),161      ...(caller ? {from: caller} : {}),162    });163  }164165  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string, mergeDeprecated = false) {166    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller, mergeDeprecated);167  }168169  async rftToken(address: string, caller?: string, mergeDeprecated = false) {170    const web3 = this.helper.getWeb3();171    const abi = mergeDeprecated ? [...refungibleTokenAbi, ...refungibleTokenDeprecatedAbi] : refungibleTokenAbi;172    return new web3.eth.Contract(abi as any, address, {173      gas: this.helper.eth.DEFAULT_GAS,174      gasPrice: await this.getGasPrice(),175      ...(caller ? {from: caller} : {}),176    });177  }178179  rftTokenById(collectionId: number, tokenId: number, caller?: string, mergeDeprecated = false) {180    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller, mergeDeprecated);181  }182}183184185class EthGroup extends EthGroupBase {186  DEFAULT_GAS = 2_500_000;187188  createAccount() {189    const web3 = this.helper.getWeb3();190    const account = web3.eth.accounts.create();191    web3.eth.accounts.wallet.add(account.privateKey);192    return account.address;193  }194195  async createAccountWithBalance(donor: IKeyringPair, amount = 600n) {196    const account = this.createAccount();197    await this.transferBalanceFromSubstrate(donor, account, amount);198199    return account;200  }201202  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount = 100n, inTokens = true) {203    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));204  }205206  async getCollectionCreationFee(signer: string) {207    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);208    return await collectionHelper.methods.collectionCreationFee().call();209  }210211  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {212    if (!gasLimit) gasLimit = this.DEFAULT_GAS;213    const web3 = this.helper.getWeb3();214    const gasPrice = await web3.eth.getGasPrice();215    // TODO: check execution status216    await this.helper.executeExtrinsic(217      signer,218      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],219      true,220    );221  }222223  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {224    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);225  }226227  createCollectionMethodName(mode: TCollectionMode) {228    switch (mode) {229      case 'ft':230        return 'createFTCollection';231      case 'nft':232        return 'createNFTCollection';233      case 'rft':234        return 'createRFTCollection';235    }236  }237238  async createCollection(mode: TCollectionMode, signer: string, name: string, description: string, tokenPrefix: string, decimals = 18, mergeDeprecated = false): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[], collection: Contract }> {239    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();240    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);241    const functionName: string = this.createCollectionMethodName(mode);242243    const functionParams = mode === 'ft' ? [name, decimals, description, tokenPrefix] : [name, description, tokenPrefix];244    const result = await collectionHelper.methods[functionName](...functionParams).send({value: Number(collectionCreationPrice)});245246    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);247    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);248    const events = this.helper.eth.normalizeEvents(result.events);249    const collection = await this.helper.ethNativeContract.collectionById(collectionId, mode, signer, mergeDeprecated);250251    return {collectionId, collectionAddress, events, collection};252  }253254  createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {255    return this.createCollection('nft', signer, name, description, tokenPrefix);256  }257258  async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {259    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);260261    const {collectionId, collectionAddress, events} = await this.createCollection('nft', signer, name, description, tokenPrefix);262263    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();264265    return {collectionId, collectionAddress, events};266  }267268  createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {269    return this.createCollection('rft', signer, name, description, tokenPrefix);270  }271272  createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {273    return this.createCollection('ft', signer, name, description, tokenPrefix, decimals);274  }275276  async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {277    const collectionHelper = await this.helper.ethNativeContract.collectionHelpers(signer);278279    const {collectionId, collectionAddress, events} = await this.createCollection('rft', signer, name, description, tokenPrefix);280281    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();282283    return {collectionId, collectionAddress, events};284  }285286  async deployCollectorContract(signer: string): Promise<Contract> {287    return await this.helper.ethContract.deployByCode(signer, 'Collector', `288    // SPDX-License-Identifier: UNLICENSED289    pragma solidity ^0.8.6;290291    contract Collector {292      uint256 collected;293      fallback() external payable {294        giveMoney();295      }296      function giveMoney() public payable {297        collected += msg.value;298      }299      function getCollected() public view returns (uint256) {300        return collected;301      }302      function getUnaccounted() public view returns (uint256) {303        return address(this).balance - collected;304      }305306      function withdraw(address payable target) public {307        target.transfer(collected);308        collected = 0;309      }310    }311  `);312  }313314  async deployFlipper(signer: string): Promise<Contract> {315    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `316    // SPDX-License-Identifier: UNLICENSED317    pragma solidity ^0.8.6;318319    contract Flipper {320      bool value = false;321      function flip() public {322        value = !value;323      }324      function getValue() public view returns (bool) {325        return value;326      }327    }328  `);329  }330331  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {332    const before = await this.helper.balance.getEthereum(user);333    await call();334    // In dev mode, the transaction might not finish processing in time335    await this.helper.wait.newBlocks(1);336    const after = await this.helper.balance.getEthereum(user);337338    return before - after;339  }340341  normalizeEvents(events: any): NormalizedEvent[] {342    const output = [];343    for (const key of Object.keys(events)) {344      if (key.match(/^[0-9]+$/)) {345        output.push(events[key]);346      } else if (Array.isArray(events[key])) {347        output.push(...events[key]);348      } else {349        output.push(events[key]);350      }351    }352    output.sort((a, b) => a.logIndex - b.logIndex);353    return output.map(({address, event, returnValues}) => {354      const args: { [key: string]: string } = {};355      for (const key of Object.keys(returnValues)) {356        if (!key.match(/^[0-9]+$/)) {357          args[key] = returnValues[key];358        }359      }360      return {361        address,362        event,363        args,364      };365    });366  }367368  async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {369    const wrappedCode = async () => {370      await code();371      // In dev mode, the transaction might not finish processing in time372      await this.helper.wait.newBlocks(1);373    };374    return await this.helper.arrange.calculcateFee(address, wrappedCode);375  }376}377378class EthAddressGroup extends EthGroupBase {379  extractCollectionId(address: string): number {380    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');381    return parseInt(address.substr(address.length - 8), 16);382  }383384  fromCollectionId(collectionId: number): string {385    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');386    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);387  }388389  extractTokenId(address: string): { collectionId: number, tokenId: number } {390    if (!address.startsWith('0x'))391      throw 'address not starts with "0x"';392    if (address.length > 42)393      throw 'address length is more than 20 bytes';394    return {395      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),396      tokenId: Number('0x' + address.substring(address.length - 8)),397    };398  }399400  fromTokenId(collectionId: number, tokenId: number): string {401    return this.helper.util.getTokenAddress({collectionId, tokenId});402  }403404  normalizeAddress(address: string): string {405    return '0x' + address.substring(address.length - 40);406  }407}408export class EthPropertyGroup extends EthGroupBase {409  property(key: string, value: string): EthProperty {410    return [411      key,412      '0x' + Buffer.from(value).toString('hex'),413    ];414  }415}416export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;417418export class EthCrossAccountGroup extends EthGroupBase {419  createAccount(): CrossAddress {420    return this.fromAddress(this.helper.eth.createAccount());421  }422423  async createAccountWithBalance(donor: IKeyringPair, amount = 100n) {424    return this.fromAddress(await this.helper.eth.createAccountWithBalance(donor, amount));425  }426427  fromAddress(address: TEthereumAccount): CrossAddress {428    return {429      eth: address,430      sub: '0',431    };432  }433434  fromKeyringPair(keyring: IKeyringPair): CrossAddress {435    return {436      eth: '0x0000000000000000000000000000000000000000',437      sub: keyring.addressRaw,438    };439  }440}441442export class FeeGas {443  fee: number | bigint = 0n;444445  gas: number | bigint = 0n;446447  public static async build(helper: EthUniqueHelper, fee: bigint): Promise<FeeGas> {448    const instance = new FeeGas();449    instance.fee = instance.convertToTokens(fee);450    instance.gas = await instance.convertToGas(fee, helper);451    return instance;452  }453454  private async convertToGas(fee: bigint, helper: EthUniqueHelper): Promise<bigint> {455    const gasPrice = BigInt(await helper.getWeb3().eth.getGasPrice());456    return fee / gasPrice;457  }458459  private convertToTokens(value: bigint, nominal = 1_000_000_000_000_000_000n): number {460    return Number((value * 1000n) / nominal) / 1000;461  }462}463464class EthArrangeGroup extends ArrangeGroup {465  helper: EthUniqueHelper;466467  constructor(helper: EthUniqueHelper) {468    super(helper);469    this.helper = helper;470  }471472  async calculcateFeeGas(payer: ICrossAccountId, promise: () => Promise<any>): Promise<FeeGas> {473    const fee = await this.calculcateFee(payer, promise);474    return await FeeGas.build(this.helper, fee);475  }476}477export class EthUniqueHelper extends DevUniqueHelper {478  web3: Web3 | null = null;479  web3Provider: WebsocketProvider | null = null;480481  eth: EthGroup;482  ethAddress: EthAddressGroup;483  ethCrossAccount: EthCrossAccountGroup;484  ethNativeContract: NativeContractGroup;485  ethContract: ContractGroup;486  ethProperty: EthPropertyGroup;487  arrange: EthArrangeGroup;488  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: { [key: string]: any } = {}) {489    options.helperBase = options.helperBase ?? EthUniqueHelper;490491    super(logger, options);492    this.eth = new EthGroup(this);493    this.ethAddress = new EthAddressGroup(this);494    this.ethCrossAccount = new EthCrossAccountGroup(this);495    this.ethNativeContract = new NativeContractGroup(this);496    this.ethContract = new ContractGroup(this);497    this.ethProperty = new EthPropertyGroup(this);498    this.arrange = new EthArrangeGroup(this);499    super.arrange = this.arrange;500  }501502  getWeb3(): Web3 {503    if (this.web3 === null) throw Error('Web3 not connected');504    return this.web3;505  }506507  connectWeb3(wsEndpoint: string) {508    if (this.web3 !== null) return;509    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);510    this.web3 = new Web3(this.web3Provider);511  }512513  async disconnect() {514    if (this.web3 === null) return;515    this.web3Provider?.connection.close();516517    await super.disconnect();518  }519520  clearApi() {521    super.clearApi();522    this.web3 = null;523  }524525  clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {526    const newHelper = super.clone(helperCls, options) as EthUniqueHelper;527    newHelper.web3 = this.web3;528    newHelper.web3Provider = this.web3Provider;529530    return newHelper;531  }532}