123456789import { 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 } 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';21import waitNewBlocks from '../../substrate/wait-new-blocks';2223export const GAS_ARGS = { gas: 0x1000000, gasPrice: '0x01' };2425let web3Connected = false;26export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {27 if (web3Connected) throw new Error('do not nest usingWeb3 calls');28 web3Connected = true;2930 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);31 const web3 = new Web3(provider);3233 try {34 return await cb(web3);35 } finally {36 37 provider.connection.close();38 web3Connected = false;39 }40}4142434445export async function usingWeb3Http<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {46 const provider = new Web3.providers.HttpProvider(config.frontierUrl);47 const web3: Web3 = new Web3(provider);4849 return await cb(web3);50}5152export function collectionIdToAddress(address: number): string {53 if (address >= 0xffffffff || address < 0) throw new Error('id overflow');54 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,55 address >> 24,56 (address >> 16) & 0xff,57 (address >> 8) & 0xff,58 address & 0xff,59 ]);60 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));61}6263export function createEthAccount(web3: Web3) {64 const account = web3.eth.accounts.create();65 web3.eth.accounts.wallet.add(account.privateKey);66 return account.address;67}6869export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {70 const alice = privateKey('//Alice');71 const account = createEthAccount(web3);72 await transferBalanceToEth(api, alice, account);7374 return account;75}7677export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 999999999999999) {78 const tx = api.tx.balances.transfer(evmToAddress(target), amount);79 const events = await submitTransactionAsync(source, tx);80 const result = getGenericResult(events);81 expect(result.success).to.be.true;82}8384export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {85 let i: any = it;86 if (opts.only) i = i.only;87 else if (opts.skip) i = i.skip;88 i(name, async () => {89 await usingApi(async api => {90 await usingWeb3(async web3 => {91 await cb({ api, web3 });92 });93 });94 });95}96itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { only: true });97itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { skip: true });9899export async function generateSubstrateEthPair(web3: Web3) {100 const account = web3.eth.accounts.create();101 evmToAddress(account.address);102}103104type NormalizedEvent = {105 address: string,106 event: string,107 args: { [key: string]: string }108};109110export function normalizeEvents(events: any): NormalizedEvent[] {111 const output = [];112 for (const key of Object.keys(events)) {113 if (key.match(/^[0-9]+$/)) {114 output.push(events[key]);115 } else if (Array.isArray(events[key])) {116 output.push(...events[key]);117 } else {118 output.push(events[key]);119 }120 }121 output.sort((a, b) => a.logIndex - b.logIndex);122 return output.map(({ address, event, returnValues }) => {123 const args: { [key: string]: string } = {};124 for (const key of Object.keys(returnValues)) {125 if (!key.match(/^[0-9]+$/)) {126 args[key] = returnValues[key];127 }128 }129 return {130 address,131 event,132 args,133 };134 });135}136137export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {138 const out: any = [];139 contract.events.allEvents((_: any, event: any) => {140 out.push(event);141 });142 await action();143 return normalizeEvents(out);144}145146export function subToEth(eth: string): string {147 const bytes = addressToEvm(eth);148 const string = '0x' + Buffer.from(bytes).toString('hex');149 return Web3.utils.toChecksumAddress(string);150}151152export function compileContract(name: string, src: string) {153 const out = JSON.parse(solc.compile(JSON.stringify({154 language: 'Solidity',155 sources: {156 [`${name}.sol`]: {157 content: `158 // SPDX-License-Identifier: UNLICENSED159 pragma solidity ^0.8.6;160161 ${src}162 `,163 },164 },165 settings: {166 outputSelection: {167 '*': {168 '*': ['*'],169 },170 },171 },172 }))).contracts[`${name}.sol`][name];173174 return {175 abi: out.abi,176 object: '0x' + out.evm.bytecode.object,177 };178}179180export async function deployFlipper(web3: Web3, deployer: string) {181 const compiled = compileContract('Flipper', `182 contract Flipper {183 bool value = false;184 function flip() public {185 value = !value;186 }187 function getValue() public view returns (bool) {188 return value;189 }190 }191 `);192 const Flipper = new web3.eth.Contract(compiled.abi, undefined, {193 data: compiled.object,194 from: deployer,195 ...GAS_ARGS,196 });197 const flipper = await Flipper.deploy({ data: compiled.object }).send({from: deployer});198199 return flipper;200}201202export async function deployCollector(web3: Web3, deployer: string) {203 const compiled = compileContract('Collector', `204 contract Collector {205 uint256 collected;206 fallback() external payable {207 giveMoney();208 }209 function giveMoney() public payable {210 collected += msg.value;211 }212 function getCollected() public view returns (uint256) {213 return collected;214 }215 function getUnaccounted() public view returns (uint256) {216 return address(this).balance - collected;217 }218219 function withdraw(address payable target) public {220 target.transfer(collected);221 collected = 0;222 }223 }224 `);225 const Collector = new web3.eth.Contract(compiled.abi, undefined, {226 data: compiled.object,227 from: deployer,228 ...GAS_ARGS,229 });230 const collector = await Collector.deploy({ data: compiled.object }).send({ from: deployer });231232 return collector;233}234235export function contractHelpers(web3: Web3, caller: string) {236 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});237}238239export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {240 return (await getBalance(api, [evmToAddress(address)]))[0];241}242243export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {244 const before = await ethBalanceViaSub(api, user);245246 await call();247 await waitNewBlocks(api, 1);248249 const after = await ethBalanceViaSub(api, user);250251 252 expect(after < before).to.be.true;253254 return before - after;255}