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, 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 = 0,26 Allowlisted = 1,27 Generous = 2,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 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}236237238239240241242243244245246247248249export 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}266267268269270271272export 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 280 expect(after < before).to.be.true;281282 return before - after;283}