git.delta.rocks / unique-network / refs/commits / 5ec07294ed3b

difftreelog

source

tests/src/eth/util/helpers.ts11.9 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// eslint-disable-next-line @typescript-eslint/triple-slash-reference18/// <reference path="helpers.d.ts" />1920import {ApiPromise} from '@polkadot/api';21import {IKeyringPair} from '@polkadot/types/types';22import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';23import {expect} from 'chai';24import * as solc from 'solc';25import Web3 from 'web3';26import config from '../../config';27import getBalance from '../../substrate/get-balance';28import privateKey from '../../substrate/privateKey';29import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';30import waitNewBlocks from '../../substrate/wait-new-blocks';31import {CrossAccountId, getDetailedCollectionInfo, getGenericResult, UNIQUE} from '../../util/helpers';32import collectionHelpersAbi from '../collectionHelpersAbi.json';33import nonFungibleAbi from '../nonFungibleAbi.json';34import contractHelpersAbi from './contractHelpersAbi.json';3536export const GAS_ARGS = {gas: 2500000};3738export enum SponsoringMode {39  Disabled = 0,40  Allowlisted = 1,41  Generous = 2,42}4344let web3Connected = false;45export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {46  if (web3Connected) throw new Error('do not nest usingWeb3 calls');47  web3Connected = true;4849  const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);50  const web3 = new Web3(provider);5152  try {53    return await cb(web3);54  } finally {55    // provider.disconnect(3000, 'normal disconnect');56    provider.connection.close();57    web3Connected = false;58  }59}6061function encodeIntBE(v: number): number[] {62  if (v >= 0xffffffff || v < 0) throw new Error('id overflow');63  return [64    v >> 24,65    (v >> 16) & 0xff,66    (v >> 8) & 0xff,67    v & 0xff,68  ];69}7071export async function getCollectionAddressFromResult(api: ApiPromise, result: any) {72  const collectionIdAddress = normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);73  const collectionId = collectionIdFromAddress(collectionIdAddress);  74  const collection = (await getDetailedCollectionInfo(api, collectionId))!;75  return {collectionIdAddress, collectionId, collection};76}7778export function collectionIdToAddress(collection: number): string {79  const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,80    ...encodeIntBE(collection),81  ]);82  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));83}84export function collectionIdFromAddress(address: string): number {85  if (!address.startsWith('0x'))86    throw 'address not starts with "0x"';87  if (address.length > 42)88    throw 'address length is more than 20 bytes';89  return Number('0x' + address.substring(address.length - 8));90}91  92export function normalizeAddress(address: string): string {93  return '0x' + address.substring(address.length - 40);94}9596export function tokenIdToAddress(collection: number, token: number): string {97  const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,98    ...encodeIntBE(collection),99    ...encodeIntBE(token),100  ]);101  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));102}103export function tokenIdToCross(collection: number, token: number): CrossAccountId {104  return {105    Ethereum: tokenIdToAddress(collection, token),106  };107}108109export function createEthAccount(web3: Web3) {110  const account = web3.eth.accounts.create();111  web3.eth.accounts.wallet.add(account.privateKey);112  return account.address;113}114115export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair) {116  const alice = privateKeyWrapper('//Alice');117  const account = createEthAccount(web3);118  await transferBalanceToEth(api, alice, account);119120  return account;121}122123export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {124  const tx = api.tx.balances.transfer(evmToAddress(target), amount);125  const events = await submitTransactionAsync(source, tx);126  const result = getGenericResult(events);127  expect(result.success).to.be.true;128}129130export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {131  let i: any = it;132  if (opts.only) i = i.only;133  else if (opts.skip) i = i.skip;134  i(name, async () => {135    await usingApi(async (api, privateKeyWrapper) => {136      await usingWeb3(async web3 => {137        await cb({api, web3, privateKeyWrapper});138      });139    });140  });141}142itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {only: true});143itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {skip: true});144145export async function generateSubstrateEthPair(web3: Web3) {146  const account = web3.eth.accounts.create();147  evmToAddress(account.address);148}149150type NormalizedEvent = {151    address: string,152    event: string,153    args: { [key: string]: string }154};155156export function normalizeEvents(events: any): NormalizedEvent[] {157  const output = [];158  for (const key of Object.keys(events)) {159    if (key.match(/^[0-9]+$/)) {160      output.push(events[key]);161    } else if (Array.isArray(events[key])) {162      output.push(...events[key]);163    } else {164      output.push(events[key]);165    }166  }167  output.sort((a, b) => a.logIndex - b.logIndex);168  return output.map(({address, event, returnValues}) => {169    const args: { [key: string]: string } = {};170    for (const key of Object.keys(returnValues)) {171      if (!key.match(/^[0-9]+$/)) {172        args[key] = returnValues[key];173      }174    }175    return {176      address,177      event,178      args,179    };180  });181}182183export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {184  const out: any = [];185  contract.events.allEvents((_: any, event: any) => {186    out.push(event);187  });188  await action();189  return normalizeEvents(out);190}191192export function subToEthLowercase(eth: string): string {193  const bytes = addressToEvm(eth);194  return '0x' + Buffer.from(bytes).toString('hex');195}196197export function subToEth(eth: string): string {198  return Web3.utils.toChecksumAddress(subToEthLowercase(eth));199}200201export function compileContract(name: string, src: string) {202  const out = JSON.parse(solc.compile(JSON.stringify({203    language: 'Solidity',204    sources: {205      [`${name}.sol`]: {206        content: `207          // SPDX-License-Identifier: UNLICENSED208          pragma solidity ^0.8.6;209210          ${src}211        `,212      },213    },214    settings: {215      outputSelection: {216        '*': {217          '*': ['*'],218        },219      },220    },221  }))).contracts[`${name}.sol`][name];222223  return {224    abi: out.abi,225    object: '0x' + out.evm.bytecode.object,226  };227}228229export async function deployFlipper(web3: Web3, deployer: string) {230  const compiled = compileContract('Flipper', `231    contract Flipper {232      bool value = false;233      function flip() public {234        value = !value;235      }236      function getValue() public view returns (bool) {237        return value;238      }239    }240  `);241  const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {242    data: compiled.object,243    from: deployer,244    ...GAS_ARGS,245  });246  const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});247248  return flipper;249}250251export async function deployCollector(web3: Web3, deployer: string) {252  const compiled = compileContract('Collector', `253    contract Collector {254      uint256 collected;255      fallback() external payable {256        giveMoney();257      }258      function giveMoney() public payable {259        collected += msg.value;260      }261      function getCollected() public view returns (uint256) {262        return collected;263      }264      function getUnaccounted() public view returns (uint256) {265        return address(this).balance - collected;266      }267268      function withdraw(address payable target) public {269        target.transfer(collected);270        collected = 0;271      }272    }273  `);274  const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {275    data: compiled.object,276    from: deployer,277    ...GAS_ARGS,278  });279  const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});280281  return collector;282}283284/** 285 * pallet evm_contract_helpers286 * @param web3 287 * @param caller - eth address288 * @returns 289 */290export function contractHelpers(web3: Web3, caller: string) {291  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});292}293294/** 295 * evm collection helper296 * @param web3 297 * @param caller - eth address298 * @returns 299 */300export function evmCollectionHelpers(web3: Web3, caller: string) {301  return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});302}303304/** 305 * evm collection306 * @param web3 307 * @param caller - eth address308 * @returns 309 */310export function evmCollection(web3: Web3, caller: string, collection: string) {311  return new web3.eth.Contract(nonFungibleAbi as any, collection, {from: caller, ...GAS_ARGS});312}313314/**315 * Execute ethereum method call using substrate account316 * @param to target contract317 * @param mkTx - closure, receiving `contract.methods`, and returning method call,318 * to be used as following (assuming `to` = erc20 contract):319 * `m => m.transfer(to, amount)`320 *321 * # Example322 * ```ts323 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));324 * ```325 */326export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {327  const tx = api.tx.evm.call(328    subToEth(from.address),329    to.options.address,330    mkTx(to.methods).encodeABI(),331    value,332    GAS_ARGS.gas,333    await web3.eth.getGasPrice(),334    null,335    null,336    [],337  );338  const events = await submitTransactionAsync(from, tx);339  expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;340}341342export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {343  return (await getBalance(api, [evmToAddress(address)]))[0];344}345346/**347 * Measure how much gas given closure consumes348 *349 * @param user which user balance will be checked350 */351export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {352  const before = await ethBalanceViaSub(api, user);353354  await call();355356  // In dev mode, the transaction might not finish processing in time357  await waitNewBlocks(api, 1);358  const after = await ethBalanceViaSub(api, user);359360  // Can't use .to.be.less, because chai doesn't supports bigint361  expect(after < before).to.be.true;362363  return before - after;364}365366type ElementOf<A> = A extends readonly (infer T)[] ? T : never;367// I want a fancier api, not a memory efficiency368export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {369  if(args.length === 0) {370    yield internalRest as any;371    return;372  }373  for(const value of args[0]) {374    yield* cartesian([...internalRest, value], ...args.slice(1)) as any;375  }376}