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

difftreelog

source

tests/src/eth/util/playgrounds/unique.dev.ts15.9 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract, TEthCrossAccount, NormalizedEvent, EthProperty} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../abi/collectionHelpers.json';25import fungibleAbi from '../../abi/fungible.json';26import fungibleDeprecatedAbi from '../../abi/fungibleDeprecated.json';27import nonFungibleAbi from '../../abi/nonFungible.json';28import nonFungibleDeprecatedAbi from '../../abi/nonFungibleDeprecated.json';29import refungibleAbi from '../../abi/reFungible.json';30import refungibleDeprecatedAbi from '../../abi/reFungibleDeprecated.json';31import refungibleTokenAbi from '../../abi/reFungibleToken.json';32import contractHelpersAbi from '../../abi/contractHelpers.json';33import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';34import {TCollectionMode} from '../../../util/playgrounds/types';3536class EthGroupBase {37  helper: EthUniqueHelper;3839  constructor(helper: EthUniqueHelper) {40    this.helper = helper;41  }42}434445class ContractGroup extends EthGroupBase {46  async findImports(imports?: ContractImports[]){47    if(!imports) return function(path: string) {48      return {error: `File not found: ${path}`};49    };5051    const knownImports = {} as {[key: string]: string};52    for(const imp of imports) {53      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();54    }5556    return function(path: string) {57      if(path in knownImports) return {contents: knownImports[path]};58      return {error: `File not found: ${path}`};59    };60  }6162  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {63    const out = JSON.parse(solc.compile(JSON.stringify({64      language: 'Solidity',65      sources: {66        [`${name}.sol`]: {67          content: src,68        },69      },70      settings: {71        outputSelection: {72          '*': {73            '*': ['*'],74          },75        },76      },77    }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];7879    return {80      abi: out.abi,81      object: '0x' + out.evm.bytecode.object,82    };83  }8485  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[], gas?: number): Promise<Contract> {86    const compiledContract = await this.compile(name, src, imports);87    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object, gas);88  }8990  async deployByAbi(signer: string, abi: any, object: string, gas?: number): Promise<Contract> {91    const web3 = this.helper.getWeb3();92    const contract = new web3.eth.Contract(abi, undefined, {93      data: object,94      from: signer,95      gas: gas ?? this.helper.eth.DEFAULT_GAS,96    });97    return await contract.deploy({data: object}).send({from: signer});98  }99100}101102class NativeContractGroup extends EthGroupBase {103104  contractHelpers(caller: string): Contract {105    const web3 = this.helper.getWeb3();106    return new web3.eth.Contract(contractHelpersAbi as any, this.helper.getApi().consts.evmContractHelpers.contractAddress.toString(), {from: caller, gas: this.helper.eth.DEFAULT_GAS});107  }108109  collectionHelpers(caller: string) {110    const web3 = this.helper.getWeb3();111    return new web3.eth.Contract(collectionHelpersAbi as any, this.helper.getApi().consts.common.contractAddress.toString(), {from: caller, gas: this.helper.eth.DEFAULT_GAS});112  }113114  collection(address: string, mode: TCollectionMode, caller?: string, mergeDeprecated = false): Contract {115    let abi = {116      'nft': nonFungibleAbi,117      'rft': refungibleAbi,118      'ft': fungibleAbi,119    }[mode];120    if (mergeDeprecated) {121      const deprecated = {122        'nft': nonFungibleDeprecatedAbi,123        'rft': refungibleDeprecatedAbi,124        'ft': fungibleDeprecatedAbi,125      }[mode];126      abi = [...abi,...deprecated];127    }128    const web3 = this.helper.getWeb3();129    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});130  }131132  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {133    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);134  }135136  rftToken(address: string, caller?: string): Contract {137    const web3 = this.helper.getWeb3();138    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});139  }140141  rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {142    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);143  }144}145146147class EthGroup extends EthGroupBase {148  DEFAULT_GAS = 2_500_000;149150  createAccount() {151    const web3 = this.helper.getWeb3();152    const account = web3.eth.accounts.create();153    web3.eth.accounts.wallet.add(account.privateKey);154    return account.address;155  }156157  async createAccountWithBalance(donor: IKeyringPair, amount=100n) {158    const account = this.createAccount();159    await this.transferBalanceFromSubstrate(donor, account, amount);160161    return account;162  }163164  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=100n, inTokens=true) {165    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));166  }167168  async getCollectionCreationFee(signer: string) {169    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);170    return await collectionHelper.methods.collectionCreationFee().call();171  }172173  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {174    if(!gasLimit) gasLimit = this.DEFAULT_GAS;175    const web3 = this.helper.getWeb3();176    const gasPrice = await web3.eth.getGasPrice();177    // TODO: check execution status178    await this.helper.executeExtrinsic(179      signer,180      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],181      true,182    );183  }184185  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {186    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);187  }188189  async createCollecion(functionName: 'createNFTCollection' | 'createRFTCollection' | 'createFTCollection', signer: string, name: string, description: string, tokenPrefix: string, decimals?: number): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {190    const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();191    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);192193    const functionParams = functionName === 'createFTCollection' ? [name, decimals, description, tokenPrefix] : [name, description, tokenPrefix];194    const result = await collectionHelper.methods[functionName](...functionParams).send({value: Number(collectionCreationPrice)});195196    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);197    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);198    const events = this.helper.eth.normalizeEvents(result.events);199200    return {collectionId, collectionAddress, events};201  }202203  createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {204    return this.createCollecion('createNFTCollection', signer, name, description, tokenPrefix);205  }206207  async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {208    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);209210    const {collectionId, collectionAddress, events} = await this.createCollecion('createNFTCollection', signer, name, description, tokenPrefix);211212    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();213214    return {collectionId, collectionAddress, events};215  }216217  createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[]}> {218    return this.createCollecion('createRFTCollection', signer, name, description, tokenPrefix);219  }220221  createFungibleCollection(signer: string, name: string, decimals: number, description: string, tokenPrefix: string): Promise<{ collectionId: number, collectionAddress: string, events: NormalizedEvent[]}> {222    return this.createCollecion('createFTCollection', signer, name, description, tokenPrefix, decimals);223  }224225  async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string, events: NormalizedEvent[] }> {226    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);227228    const {collectionId, collectionAddress, events} = await this.createCollecion('createRFTCollection', signer, name, description, tokenPrefix);229230    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();231232    return {collectionId, collectionAddress, events};233  }234235  async deployCollectorContract(signer: string): Promise<Contract> {236    return await this.helper.ethContract.deployByCode(signer, 'Collector', `237    // SPDX-License-Identifier: UNLICENSED238    pragma solidity ^0.8.6;239240    contract Collector {241      uint256 collected;242      fallback() external payable {243        giveMoney();244      }245      function giveMoney() public payable {246        collected += msg.value;247      }248      function getCollected() public view returns (uint256) {249        return collected;250      }251      function getUnaccounted() public view returns (uint256) {252        return address(this).balance - collected;253      }254255      function withdraw(address payable target) public {256        target.transfer(collected);257        collected = 0;258      }259    }260  `);261  }262263  async deployFlipper(signer: string): Promise<Contract> {264    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `265    // SPDX-License-Identifier: UNLICENSED266    pragma solidity ^0.8.6;267268    contract Flipper {269      bool value = false;270      function flip() public {271        value = !value;272      }273      function getValue() public view returns (bool) {274        return value;275      }276    }277  `);278  }279280  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {281    const before = await this.helper.balance.getEthereum(user);282    await call();283    // In dev mode, the transaction might not finish processing in time284    await this.helper.wait.newBlocks(1);285    const after = await this.helper.balance.getEthereum(user);286287    return before - after;288  }289290  normalizeEvents(events: any): NormalizedEvent[] {291    const output = [];292    for (const key of Object.keys(events)) {293      if (key.match(/^[0-9]+$/)) {294        output.push(events[key]);295      } else if (Array.isArray(events[key])) {296        output.push(...events[key]);297      } else {298        output.push(events[key]);299      }300    }301    output.sort((a, b) => a.logIndex - b.logIndex);302    return output.map(({address, event, returnValues}) => {303      const args: { [key: string]: string } = {};304      for (const key of Object.keys(returnValues)) {305        if (!key.match(/^[0-9]+$/)) {306          args[key] = returnValues[key];307        }308      }309      return {310        address,311        event,312        args,313      };314    });315  }316317  async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {318    const wrappedCode = async () => {319      await code();320      // In dev mode, the transaction might not finish processing in time321      await this.helper.wait.newBlocks(1);322    };323    return await this.helper.arrange.calculcateFee(address, wrappedCode);324  }325}326327class EthAddressGroup extends EthGroupBase {328  extractCollectionId(address: string): number {329    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');330    return parseInt(address.substr(address.length - 8), 16);331  }332333  fromCollectionId(collectionId: number): string {334    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');335    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);336  }337338  extractTokenId(address: string): {collectionId: number, tokenId: number} {339    if (!address.startsWith('0x'))340      throw 'address not starts with "0x"';341    if (address.length > 42)342      throw 'address length is more than 20 bytes';343    return {344      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),345      tokenId: Number('0x' + address.substring(address.length - 8)),346    };347  }348349  fromTokenId(collectionId: number, tokenId: number): string  {350    return this.helper.util.getTokenAddress({collectionId, tokenId});351  }352353  normalizeAddress(address: string): string {354    return '0x' + address.substring(address.length - 40);355  }356}357export class EthPropertyGroup extends EthGroupBase {358  property(key: string, value: string): EthProperty {359    return [360      key,361      '0x'+Buffer.from(value).toString('hex'),362    ];363  }364}365export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;366367export class EthCrossAccountGroup extends EthGroupBase {368  fromAddress(address: TEthereumAccount): TEthCrossAccount {369    return {370      eth: address,371      sub: '0',372    };373  }374375  fromKeyringPair(keyring: IKeyringPair): TEthCrossAccount {376    return {377      eth: '0x0000000000000000000000000000000000000000',378      sub: keyring.addressRaw,379    };380  }381}382383export class EthUniqueHelper extends DevUniqueHelper {384  web3: Web3 | null = null;385  web3Provider: WebsocketProvider | null = null;386387  eth: EthGroup;388  ethAddress: EthAddressGroup;389  ethCrossAccount: EthCrossAccountGroup;390  ethNativeContract: NativeContractGroup;391  ethContract: ContractGroup;392  ethProperty: EthPropertyGroup;393394  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {395    options.helperBase = options.helperBase ?? EthUniqueHelper;396397    super(logger, options);398    this.eth = new EthGroup(this);399    this.ethAddress = new EthAddressGroup(this);400    this.ethCrossAccount = new EthCrossAccountGroup(this);401    this.ethNativeContract = new NativeContractGroup(this);402    this.ethContract = new ContractGroup(this);403    this.ethProperty = new EthPropertyGroup(this);404  }405406  getWeb3(): Web3 {407    if(this.web3 === null) throw Error('Web3 not connected');408    return this.web3;409  }410411  connectWeb3(wsEndpoint: string) {412    if(this.web3 !== null) return;413    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);414    this.web3 = new Web3(this.web3Provider);415  }416417  async disconnect() {418    if(this.web3 === null) return;419    this.web3Provider?.connection.close();420421    await super.disconnect();422  }423424  clearApi() {425    super.clearApi();426    this.web3 = null;427  }428429  clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {430    const newHelper = super.clone(helperCls, options) as EthUniqueHelper;431    newHelper.web3 = this.web3;432    newHelper.web3Provider = this.web3Provider;433434    return newHelper;435  }436}