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';2122export const GAS_ARGS = { gas: 0x1000000, gasPrice: '0x01' };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 36 provider.connection.close();37 web3Connected = false;38 }39}4041424344export async function usingWeb3Http<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {45 const provider = new Web3.providers.HttpProvider(config.frontierUrl);46 const web3: Web3 = new Web3(provider);4748 return await cb(web3);49}5051export function collectionIdToAddress(address: number): string {52 if (address >= 0xffffffff || address < 0) throw new Error('id overflow');53 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,54 address >> 24,55 (address >> 16) & 0xff,56 (address >> 8) & 0xff,57 address & 0xff,58 ]);59 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));60}6162export function createEthAccount(web3: Web3) {63 const account = web3.eth.accounts.create();64 web3.eth.accounts.wallet.add(account.privateKey);65 return account.address;66}6768export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {69 const alice = privateKey('//Alice');70 const account = createEthAccount(web3);71 await transferBalanceToEth(api, alice, account);7273 return account;74}7576export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 999999999999999) {77 const tx = api.tx.balances.transfer(evmToAddress(target), amount);78 const events = await submitTransactionAsync(source, tx);79 const result = getGenericResult(events);80 expect(result.success).to.be.true;81}8283export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {84 let i: any = it;85 if (opts.only) i = i.only;86 else if (opts.skip) i = i.skip;87 i(name, async () => {88 await usingApi(async api => {89 await usingWeb3(async web3 => {90 await cb({ api, web3 });91 });92 });93 });94}95itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { only: true });96itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { skip: true });9798export async function generateSubstrateEthPair(web3: Web3) {99 const account = web3.eth.accounts.create();100 evmToAddress(account.address);101}102103type NormalizedEvent = {104 address: string,105 event: string,106 args: { [key: string]: string }107};108109export function normalizeEvents(events: any): NormalizedEvent[] {110 const output = [];111 for (const key of Object.keys(events)) {112 if (key.match(/^[0-9]+$/)) {113 output.push(events[key]);114 } else if (Array.isArray(events[key])) {115 output.push(...events[key]);116 } else {117 output.push(events[key]);118 }119 }120 output.sort((a, b) => a.logIndex - b.logIndex);121 return output.map(({ address, event, returnValues }) => {122 const args: { [key: string]: string } = {};123 for (const key of Object.keys(returnValues)) {124 if (!key.match(/^[0-9]+$/)) {125 args[key] = returnValues[key];126 }127 }128 return {129 address,130 event,131 args,132 };133 });134}135136export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {137 const out: any = [];138 contract.events.allEvents((_: any, event: any) => {139 out.push(event);140 });141 await action();142 return normalizeEvents(out);143}144145export function subToEth(eth: string): string {146 const bytes = addressToEvm(eth);147 const string = '0x' + Buffer.from(bytes).toString('hex');148 return Web3.utils.toChecksumAddress(string);149}150151export function compileContract(name: string, src: string) {152 const out = JSON.parse(solc.compile(JSON.stringify({153 language: 'Solidity',154 sources: {155 [`${name}.sol`]: {156 content: `157 // SPDX-License-Identifier: UNLICENSED158 pragma solidity ^0.8.6;159160 ${src}161 `,162 },163 },164 settings: {165 outputSelection: {166 '*': {167 '*': ['*'],168 },169 },170 },171 }))).contracts[`${name}.sol`][name];172173 return {174 abi: out.abi,175 object: '0x' + out.evm.bytecode.object,176 };177}178179export async function deployFlipper(web3: Web3, deployer: string) {180 const compiled = compileContract('Flipper', `181 contract Flipper {182 bool value = false;183 function flip() public {184 value = !value;185 }186 function getValue() public view returns (bool) {187 return value;188 }189 }190 `);191 const Flipper = new web3.eth.Contract(compiled.abi, undefined, {192 data: compiled.object,193 from: deployer,194 ...GAS_ARGS,195 });196 const flipper = await Flipper.deploy({ data: compiled.object }).send({from: deployer});197198 return flipper;199}200201export async function deployCollector(web3: Web3, deployer: string) {202 const compiled = compileContract('Collector', `203 contract Collector {204 uint256 collected;205 function giveMoney() public payable {206 collected += msg.value;207 }208 function getCollected() public view returns (uint256) {209 return collected;210 }211 }212 `);213 const Collector = new web3.eth.Contract(compiled.abi, undefined, {214 data: compiled.object,215 from: deployer,216 ...GAS_ARGS,217 });218 const collector = await Collector.deploy({ data: compiled.object }).send({ from: deployer });219220 return collector;221}222223export function contractHelpers(web3: Web3, caller: string) {224 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});225}226227export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {228 return (await getBalance(api, [evmToAddress(address)]))[0];229}230231export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {232 const before = await ethBalanceViaSub(api, user);233234 await call();235236 const after = await ethBalanceViaSub(api, user);237238 239 expect(after < before).to.be.true;240241 return before - after;242}