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

difftreelog

test(contract-helpers) generous sponsoring mode

Yaroslav Bolyukin2022-01-19parent: #a5d7692.patch.diff
in: master

4 files changed

modifiedtests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -10,7 +10,10 @@
   createEthAccountWithBalance,
   transferBalanceToEth,
   deployFlipper,
-  itWeb3} from './util/helpers';
+  itWeb3,
+  SponsoringMode,
+  createEthAccount,
+} from './util/helpers';
 
 describe('Sponsoring EVM contracts', () => {
   itWeb3('Sponsoring can be set by the address that has deployed the contract', async ({api, web3}) => {
@@ -18,7 +21,7 @@
     const flipper = await deployFlipper(web3, owner);
     const helpers = contractHelpers(web3, owner);
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
-    await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
+    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
   });
 
@@ -28,11 +31,11 @@
     const flipper = await deployFlipper(web3, owner);
     const helpers = contractHelpers(web3, owner);
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
-    await expect(helpers.methods.toggleSponsoring(notOwner, true).send({from: notOwner})).to.rejected;
+    await expect(helpers.methods.setSponsoringMode(notOwner, SponsoringMode.Allowlisted).send({from: notOwner})).to.rejected;
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
   });
 
-  itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should decrease (allowlisted)', async ({api, web3}) => {
+  itWeb3('In generous mode, non-allowlisted user transaction will be sponsored', async ({ api, web3 }) => {
     const alice = privateKey('//Alice');
 
     const owner = await createEthAccountWithBalance(api, web3);
@@ -41,11 +44,39 @@
     const flipper = await deployFlipper(web3, owner);
 
     const helpers = contractHelpers(web3, owner);
+
+    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
+    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Generous).send({from: owner});
+    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
+    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
+
+    await transferBalanceToEth(api, alice, flipper.options.address);
+
+    const originalFlipperBalance = await web3.eth.getBalance(flipper.options.address);
+    expect(originalFlipperBalance).to.be.not.equal('0');
+
+    await flipper.methods.flip().send({from: caller});
+    expect(await flipper.methods.getValue().call()).to.be.true;
+
+    // Balance should be taken from flipper instead of caller
+    const balanceAfter = await web3.eth.getBalance(flipper.options.address);
+    expect(+balanceAfter).to.be.lessThan(+originalFlipperBalance);
+  });
+
+  itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should decrease (allowlisted)', async ({api, web3}) => {
+    const alice = privateKey('//Alice');
+
+    const owner = await createEthAccountWithBalance(api, web3);
+    const caller = await createEthAccount(api);
+
+    const flipper = await deployFlipper(web3, owner);
+
+    const helpers = contractHelpers(web3, owner);
     await helpers.methods.toggleAllowlist(flipper.options.address, true).send({from: owner});
     await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});
 
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
-    await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
+    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});
     await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
 
@@ -66,14 +97,14 @@
     const alice = privateKey('//Alice');
 
     const owner = await createEthAccountWithBalance(api, web3);
-    const caller = await createEthAccountWithBalance(api, web3);
+    const caller = await createEthAccount(api);
 
     const flipper = await deployFlipper(web3, owner);
 
     const helpers = contractHelpers(web3, owner);
 
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
-    await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
+    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});
     await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
 
@@ -104,7 +135,7 @@
     await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});
 
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
-    await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
+    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});
     await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
 
@@ -133,7 +164,7 @@
     await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});
 
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
-    await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
+    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});
     await helpers.methods.setSponsoringRateLimit(flipper.options.address, 10).send({from: owner});
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
 
@@ -157,33 +188,4 @@
     const helpers = contractHelpers(web3, owner);
     expect(await helpers.methods.getSponsoringRateLimit(flipper.options.address).call()).to.be.equals('7200');
   });
-
-  itWeb3('If allowlist mode is off and sponsorship is on, sponsorship does not work', async ({api, web3}) => {
-    const alice = privateKey('//Alice');
-
-    const owner = await createEthAccountWithBalance(api, web3);
-    const caller = await createEthAccountWithBalance(api, web3);
-
-    const flipper = await deployFlipper(web3, owner);
-
-    const helpers = contractHelpers(web3, owner);
-
-    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
-    await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
-    await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
-    expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
-
-    await transferBalanceToEth(api, alice, flipper.options.address);
-
-    const originalFlipperBalance = await web3.eth.getBalance(flipper.options.address);
-    expect(originalFlipperBalance).to.be.not.equal('0');
-
-    await flipper.methods.flip().send({from: caller});
-    expect(await flipper.methods.getValue().call()).to.be.true;
-
-    // Balance should be taken from flipper instead of caller
-    const balanceAfter = await web3.eth.getBalance(flipper.options.address);
-    expect(+balanceAfter).to.be.equals(+originalFlipperBalance);
-  });
-
 });
modifiedtests/src/eth/marketplace/marketplace.test.tsdiffbeforeafterboth
--- a/tests/src/eth/marketplace/marketplace.test.ts
+++ b/tests/src/eth/marketplace/marketplace.test.ts
@@ -2,7 +2,7 @@
 import {getBalanceSingle, transferBalanceExpectSuccess} from '../../substrate/get-balance';
 import privateKey from '../../substrate/privateKey';
 import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, createItemExpectSuccess, getTokenOwner, setCollectionLimitsExpectSuccess, setCollectionSponsorExpectSuccess, transferExpectSuccess, transferFromExpectSuccess} from '../../util/helpers';
-import {collectionIdToAddress, contractHelpers, createEthAccountWithBalance, executeEthTxOnSub, GAS_ARGS, itWeb3, subToEth, subToEthLowercase, transferBalanceToEth} from '../util/helpers';
+import {collectionIdToAddress, contractHelpers, createEthAccountWithBalance, executeEthTxOnSub, GAS_ARGS, itWeb3, SponsoringMode, subToEth, subToEthLowercase, transferBalanceToEth} from '../util/helpers';
 import {evmToAddress} from '@polkadot/util-crypto';
 import nonFungibleAbi from '../nonFungibleAbi.json';
 import fungibleAbi from '../fungibleAbi.json';
@@ -20,7 +20,7 @@
     });
     const matcher = await matcherContract.deploy({data: (await readFile(`${__dirname}/MarketPlace.bin`)).toString(), arguments:[matcherOwner]}).send({from: matcherOwner});
     const helpers = contractHelpers(web3, matcherOwner);
-    await helpers.methods.toggleSponsoring(matcher.options.address, true).send({from: matcherOwner});
+    await helpers.methods.setSponsoringMode(matcher.options.address, SponsoringMode.Allowlisted).send({from: matcherOwner});
     await helpers.methods.setSponsoringRateLimit(matcher.options.address, 1).send({from: matcherOwner});
     await transferBalanceToEth(api, alice, matcher.options.address);
 
@@ -147,7 +147,7 @@
     const matcher = await matcherContract.deploy({data: (await readFile(`${__dirname}/MarketPlace.bin`)).toString(), arguments: [matcherOwner]}).send({from: matcherOwner, gas: 10000000});
     await matcher.methods.setEscrow(escrow).send({from: matcherOwner});
     const helpers = contractHelpers(web3, matcherOwner);
-    await helpers.methods.toggleSponsoring(matcher.options.address, true).send({from: matcherOwner});
+    await helpers.methods.setSponsoringMode(matcher.options.address, SponsoringMode.Allowlisted).send({from: matcherOwner});
     await helpers.methods.setSponsoringRateLimit(matcher.options.address, 1).send({from: matcherOwner});
     await transferBalanceToEth(api, alice, matcher.options.address);
 
modifiedtests/src/eth/sponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/sponsoring.test.ts
+++ b/tests/src/eth/sponsoring.test.ts
@@ -1,6 +1,6 @@
 import {expect} from 'chai';
 import privateKey from '../substrate/privateKey';
-import {contractHelpers, createEthAccount, createEthAccountWithBalance, deployCollector, deployFlipper, itWeb3, transferBalanceToEth} from './util/helpers';
+import {contractHelpers, createEthAccount, createEthAccountWithBalance, deployCollector, deployFlipper, itWeb3, SponsoringMode, transferBalanceToEth} from './util/helpers';
 
 describe('EVM sponsoring', () => {
   itWeb3('Fee is deducted from contract if sponsoring is enabled', async ({api, web3}) => {
@@ -18,7 +18,7 @@
     await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({from: owner});
 
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
-    await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
+    await helpers.methods.setSponsoringMode(flipper.options.address, SponsoringMode.Allowlisted).send({from: owner});
     await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
     expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
 
@@ -49,7 +49,7 @@
     await helpers.methods.toggleAllowed(collector.options.address, caller, true).send({from: owner});
 
     expect(await helpers.methods.sponsoringEnabled(collector.options.address).call()).to.be.false;
-    await helpers.methods.toggleSponsoring(collector.options.address, true).send({from: owner});
+    await helpers.methods.setSponsoringMode(collector.options.address, SponsoringMode.Allowlisted).send({from: owner});
     await helpers.methods.setSponsoringRateLimit(collector.options.address, 0).send({from: owner});
     expect(await helpers.methods.sponsoringEnabled(collector.options.address).call()).to.be.true;
 
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
before · tests/src/eth/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56// eslint-disable-next-line @typescript-eslint/triple-slash-reference7/// <reference path="helpers.d.ts" />89import {ApiPromise} from '@polkadot/api';10import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';11import Web3 from 'web3';12import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';13import {IKeyringPair} from '@polkadot/types/types';14import {expect} from 'chai';15import {getGenericResult, UNIQUE} from '../../util/helpers';16import * as solc from 'solc';17import config from '../../config';18import privateKey from '../../substrate/privateKey';19import contractHelpersAbi from './contractHelpersAbi.json';20import getBalance from '../../substrate/get-balance';2122export const GAS_ARGS = {gas: 2500000};2324let web3Connected = false;25export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {26  if (web3Connected) throw new Error('do not nest usingWeb3 calls');27  web3Connected = true;2829  const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);30  const web3 = new Web3(provider);3132  try {33    return await cb(web3);34  } finally {35    // provider.disconnect(3000, 'normal disconnect');36    provider.connection.close();37    web3Connected = false;38  }39}4041export function collectionIdToAddress(address: number): string {42  if (address >= 0xffffffff || address < 0) throw new Error('id overflow');43  const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,44    address >> 24,45    (address >> 16) & 0xff,46    (address >> 8) & 0xff,47    address & 0xff,48  ]);49  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));50}5152export function createEthAccount(web3: Web3) {53  const account = web3.eth.accounts.create();54  web3.eth.accounts.wallet.add(account.privateKey);55  return account.address;56}5758export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {59  const alice = privateKey('//Alice');60  const account = createEthAccount(web3);61  await transferBalanceToEth(api, alice, account);6263  return account;64}6566export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {67  const tx = api.tx.balances.transfer(evmToAddress(target), amount);68  const events = await submitTransactionAsync(source, tx);69  const result = getGenericResult(events);70  expect(result.success).to.be.true;71}7273export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {74  let i: any = it;75  if (opts.only) i = i.only;76  else if (opts.skip) i = i.skip;77  i(name, async () => {78    await usingApi(async api => {79      await usingWeb3(async web3 => {80        await cb({api, web3});81      });82    });83  });84}85itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});86itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});8788export async function generateSubstrateEthPair(web3: Web3) {89  const account = web3.eth.accounts.create();90  evmToAddress(account.address);91}9293type NormalizedEvent = {94    address: string,95    event: string,96    args: { [key: string]: string }97};9899export function normalizeEvents(events: any): NormalizedEvent[] {100  const output = [];101  for (const key of Object.keys(events)) {102    if (key.match(/^[0-9]+$/)) {103      output.push(events[key]);104    } else if (Array.isArray(events[key])) {105      output.push(...events[key]);106    } else {107      output.push(events[key]);108    }109  }110  output.sort((a, b) => a.logIndex - b.logIndex);111  return output.map(({address, event, returnValues}) => {112    const args: { [key: string]: string } = {};113    for (const key of Object.keys(returnValues)) {114      if (!key.match(/^[0-9]+$/)) {115        args[key] = returnValues[key];116      }117    }118    return {119      address,120      event,121      args,122    };123  });124}125126export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {127  const out: any = [];128  contract.events.allEvents((_: any, event: any) => {129    out.push(event);130  });131  await action();132  return normalizeEvents(out);133}134135export function subToEthLowercase(eth: string): string {136  const bytes = addressToEvm(eth);137  return '0x' + Buffer.from(bytes).toString('hex');138}139140export function subToEth(eth: string): string {141  return Web3.utils.toChecksumAddress(subToEthLowercase(eth));142}143144export function compileContract(name: string, src: string) {145  const out = JSON.parse(solc.compile(JSON.stringify({146    language: 'Solidity',147    sources: {148      [`${name}.sol`]: {149        content: `150          // SPDX-License-Identifier: UNLICENSED151          pragma solidity ^0.8.6;152153          ${src}154        `,155      },156    },157    settings: {158      outputSelection: {159        '*': {160          '*': ['*'],161        },162      },163    },164  }))).contracts[`${name}.sol`][name];165166  return {167    abi: out.abi,168    object: '0x' + out.evm.bytecode.object,169  };170}171172export async function deployFlipper(web3: Web3, deployer: string) {173  const compiled = compileContract('Flipper', `174    contract Flipper {175      bool value = false;176      function flip() public {177        value = !value;178      }179      function getValue() public view returns (bool) {180        return value;181      }182    }183  `);184  const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {185    data: compiled.object,186    from: deployer,187    ...GAS_ARGS,188  });189  const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});190191  return flipper;192}193194export async function deployCollector(web3: Web3, deployer: string) {195  const compiled = compileContract('Collector', `196    contract Collector {197      uint256 collected;198      fallback() external payable {199        giveMoney();200      }201      function giveMoney() public payable {202        collected += msg.value;203      }204      function getCollected() public view returns (uint256) {205        return collected;206      }207      function getUnaccounted() public view returns (uint256) {208        return address(this).balance - collected;209      }210211      function withdraw(address payable target) public {212        target.transfer(collected);213        collected = 0;214      }215    }216  `);217  const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {218    data: compiled.object,219    from: deployer,220    ...GAS_ARGS,221  });222  const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});223224  return collector;225}226227export function contractHelpers(web3: Web3, caller: string) {228  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});229}230231/**232 * Execute ethereum method call using substrate account233 * @param to target contract234 * @param mkTx - closure, receiving `contract.methods`, and returning method call,235 * to be used as following (assuming `to` = erc20 contract):236 * `m => m.transfer(to, amount)`237 *238 * # Example239 * ```ts240 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));241 * ```242 */243export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {244  const tx = api.tx.evm.call(245    subToEth(from.address),246    to.options.address,247    mkTx(to.methods).encodeABI(),248    value,249    GAS_ARGS.gas,250    await web3.eth.getGasPrice(),251    null,252  );253  const events = await submitTransactionAsync(from, tx);254  expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;255}256257export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {258  return (await getBalance(api, [evmToAddress(address)]))[0];259}260261/**262 * Measure how much gas given closure consumes263 *264 * @param user which user balance will be checked265 */266export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {267  const before = await ethBalanceViaSub(api, user);268269  await call();270271  const after = await ethBalanceViaSub(api, user);272273  // Can't use .to.be.less, because chai doesn't supports bigint274  expect(after < before).to.be.true;275276  return before - after;277}
after · tests/src/eth/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56// eslint-disable-next-line @typescript-eslint/triple-slash-reference7/// <reference path="helpers.d.ts" />89import {ApiPromise} from '@polkadot/api';10import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';11import Web3 from 'web3';12import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';13import {IKeyringPair} from '@polkadot/types/types';14import {expect} from 'chai';15import {getGenericResult, UNIQUE} from '../../util/helpers';16import * as solc from 'solc';17import config from '../../config';18import privateKey from '../../substrate/privateKey';19import contractHelpersAbi from './contractHelpersAbi.json';20import getBalance from '../../substrate/get-balance';2122export const GAS_ARGS = {gas: 2500000};2324export enum SponsoringMode {25  Disabled,26  Allowlisted,27  Generous,28}2930let web3Connected = false;31export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {32  if (web3Connected) throw new Error('do not nest usingWeb3 calls');33  web3Connected = true;3435  const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);36  const web3 = new Web3(provider);3738  try {39    return await cb(web3);40  } finally {41    // provider.disconnect(3000, 'normal disconnect');42    provider.connection.close();43    web3Connected = false;44  }45}4647export function collectionIdToAddress(address: number): string {48  if (address >= 0xffffffff || address < 0) throw new Error('id overflow');49  const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,50    address >> 24,51    (address >> 16) & 0xff,52    (address >> 8) & 0xff,53    address & 0xff,54  ]);55  return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));56}5758export function createEthAccount(web3: Web3) {59  const account = web3.eth.accounts.create();60  web3.eth.accounts.wallet.add(account.privateKey);61  return account.address;62}6364export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {65  const alice = privateKey('//Alice');66  const account = createEthAccount(web3);67  await transferBalanceToEth(api, alice, account);6869  return account;70}7172export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {73  const tx = api.tx.balances.transfer(evmToAddress(target), amount);74  const events = await submitTransactionAsync(source, tx);75  const result = getGenericResult(events);76  expect(result.success).to.be.true;77}7879export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {80  let i: any = it;81  if (opts.only) i = i.only;82  else if (opts.skip) i = i.skip;83  i(name, async () => {84    await usingApi(async api => {85      await usingWeb3(async web3 => {86        await cb({api, web3});87      });88    });89  });90}91itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});92itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});9394export async function generateSubstrateEthPair(web3: Web3) {95  const account = web3.eth.accounts.create();96  evmToAddress(account.address);97}9899type NormalizedEvent = {100    address: string,101    event: string,102    args: { [key: string]: string }103};104105export function normalizeEvents(events: any): NormalizedEvent[] {106  const output = [];107  for (const key of Object.keys(events)) {108    if (key.match(/^[0-9]+$/)) {109      output.push(events[key]);110    } else if (Array.isArray(events[key])) {111      output.push(...events[key]);112    } else {113      output.push(events[key]);114    }115  }116  output.sort((a, b) => a.logIndex - b.logIndex);117  return output.map(({address, event, returnValues}) => {118    const args: { [key: string]: string } = {};119    for (const key of Object.keys(returnValues)) {120      if (!key.match(/^[0-9]+$/)) {121        args[key] = returnValues[key];122      }123    }124    return {125      address,126      event,127      args,128    };129  });130}131132export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {133  const out: any = [];134  contract.events.allEvents((_: any, event: any) => {135    out.push(event);136  });137  await action();138  return normalizeEvents(out);139}140141export function subToEthLowercase(eth: string): string {142  const bytes = addressToEvm(eth);143  return '0x' + Buffer.from(bytes).toString('hex');144}145146export function subToEth(eth: string): string {147  return Web3.utils.toChecksumAddress(subToEthLowercase(eth));148}149150export function compileContract(name: string, src: string) {151  const out = JSON.parse(solc.compile(JSON.stringify({152    language: 'Solidity',153    sources: {154      [`${name}.sol`]: {155        content: `156          // SPDX-License-Identifier: UNLICENSED157          pragma solidity ^0.8.6;158159          ${src}160        `,161      },162    },163    settings: {164      outputSelection: {165        '*': {166          '*': ['*'],167        },168      },169    },170  }))).contracts[`${name}.sol`][name];171172  return {173    abi: out.abi,174    object: '0x' + out.evm.bytecode.object,175  };176}177178export async function deployFlipper(web3: Web3, deployer: string) {179  const compiled = compileContract('Flipper', `180    contract Flipper {181      bool value = false;182      function flip() public {183        value = !value;184      }185      function getValue() public view returns (bool) {186        return value;187      }188    }189  `);190  const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {191    data: compiled.object,192    from: deployer,193    ...GAS_ARGS,194  });195  const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});196197  return flipper;198}199200export async function deployCollector(web3: Web3, deployer: string) {201  const compiled = compileContract('Collector', `202    contract Collector {203      uint256 collected;204      fallback() external payable {205        giveMoney();206      }207      function giveMoney() public payable {208        collected += msg.value;209      }210      function getCollected() public view returns (uint256) {211        return collected;212      }213      function getUnaccounted() public view returns (uint256) {214        return address(this).balance - collected;215      }216217      function withdraw(address payable target) public {218        target.transfer(collected);219        collected = 0;220      }221    }222  `);223  const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {224    data: compiled.object,225    from: deployer,226    ...GAS_ARGS,227  });228  const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});229230  return collector;231}232233export function contractHelpers(web3: Web3, caller: string) {234  return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});235}236237/**238 * Execute ethereum method call using substrate account239 * @param to target contract240 * @param mkTx - closure, receiving `contract.methods`, and returning method call,241 * to be used as following (assuming `to` = erc20 contract):242 * `m => m.transfer(to, amount)`243 *244 * # Example245 * ```ts246 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));247 * ```248 */249export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {250  const tx = api.tx.evm.call(251    subToEth(from.address),252    to.options.address,253    mkTx(to.methods).encodeABI(),254    value,255    GAS_ARGS.gas,256    await web3.eth.getGasPrice(),257    null,258  );259  const events = await submitTransactionAsync(from, tx);260  expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;261}262263export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {264  return (await getBalance(api, [evmToAddress(address)]))[0];265}266267/**268 * Measure how much gas given closure consumes269 *270 * @param user which user balance will be checked271 */272export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {273  const before = await ethBalanceViaSub(api, user);274275  await call();276277  const after = await ethBalanceViaSub(api, user);278279  // Can't use .to.be.less, because chai doesn't supports bigint280  expect(after < before).to.be.true;281282  return before - after;283}