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 subToEthLowercase(eth: string): string {147 const bytes = addressToEvm(eth);148 return '0x' + Buffer.from(bytes).toString('hex');149}150151export function subToEth(eth: string): string {152 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));153}154155export function compileContract(name: string, src: string) {156 const out = JSON.parse(solc.compile(JSON.stringify({157 language: 'Solidity',158 sources: {159 [`${name}.sol`]: {160 content: `161 // SPDX-License-Identifier: UNLICENSED162 pragma solidity ^0.8.6;163164 ${src}165 `,166 },167 },168 settings: {169 outputSelection: {170 '*': {171 '*': ['*'],172 },173 },174 },175 }))).contracts[`${name}.sol`][name];176177 return {178 abi: out.abi,179 object: '0x' + out.evm.bytecode.object,180 };181}182183export async function deployFlipper(web3: Web3, deployer: string) {184 const compiled = compileContract('Flipper', `185 contract Flipper {186 bool value = false;187 function flip() public {188 value = !value;189 }190 function getValue() public view returns (bool) {191 return value;192 }193 }194 `);195 const Flipper = new web3.eth.Contract(compiled.abi, undefined, {196 data: compiled.object,197 from: deployer,198 ...GAS_ARGS,199 });200 const flipper = await Flipper.deploy({ data: compiled.object }).send({from: deployer});201202 return flipper;203}204205export async function deployCollector(web3: Web3, deployer: string) {206 const compiled = compileContract('Collector', `207 contract Collector {208 uint256 collected;209 fallback() external payable {210 giveMoney();211 }212 function giveMoney() public payable {213 collected += msg.value;214 }215 function getCollected() public view returns (uint256) {216 return collected;217 }218 function getUnaccounted() public view returns (uint256) {219 return address(this).balance - collected;220 }221222 function withdraw(address payable target) public {223 target.transfer(collected);224 collected = 0;225 }226 }227 `);228 const Collector = new web3.eth.Contract(compiled.abi, undefined, {229 data: compiled.object,230 from: deployer,231 ...GAS_ARGS,232 });233 const collector = await Collector.deploy({ data: compiled.object }).send({ from: deployer });234235 return collector;236}237238export function contractHelpers(web3: Web3, caller: string) {239 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});240}241242export async function executeEthTxOnSub(api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, { value = 0 }: {value?: bigint | number} = { }) {243 const tx = api.tx.evm.call(244 subToEth(from.address),245 to.options.address,246 mkTx(to.methods).encodeABI(),247 value,248 GAS_ARGS.gas,249 GAS_ARGS.gasPrice,250 null,251 );252 const events = await submitTransactionAsync(from, tx);253 expect(events.find(({ event: {section, method}})=>section === 'evm' && method === 'Executed')).to.be.not.undefined;254}255256export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {257 return (await getBalance(api, [evmToAddress(address)]))[0];258}259260export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {261 const before = await ethBalanceViaSub(api, user);262263 await call();264 await waitNewBlocks(api, 1);265266 const after = await ethBalanceViaSub(api, user);267268 269 expect(after < before).to.be.true;270271 return before - after;272}