1234567891011121314151617181920import {ApiPromise} from '@polkadot/api';21import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';22import Web3 from 'web3';23import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';24import {IKeyringPair} from '@polkadot/types/types';25import {expect} from 'chai';26import {getGenericResult, UNIQUE} from '../../util/helpers';27import * as solc from 'solc';28import config from '../../config';29import privateKey from '../../substrate/privateKey';30import contractHelpersAbi from './contractHelpersAbi.json';31import getBalance from '../../substrate/get-balance';32import waitNewBlocks from '../../substrate/wait-new-blocks';3334export const GAS_ARGS = {gas: 2500000};3536export enum SponsoringMode {37 Disabled = 0,38 Allowlisted = 1,39 Generous = 2,40}4142let web3Connected = false;43export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {44 if (web3Connected) throw new Error('do not nest usingWeb3 calls');45 web3Connected = true;4647 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);48 const web3 = new Web3(provider);4950 try {51 return await cb(web3);52 } finally {53 54 provider.connection.close();55 web3Connected = false;56 }57}5859export function collectionIdToAddress(address: number): string {60 if (address >= 0xffffffff || address < 0) throw new Error('id overflow');61 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,62 address >> 24,63 (address >> 16) & 0xff,64 (address >> 8) & 0xff,65 address & 0xff,66 ]);67 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));68}6970export function createEthAccount(web3: Web3) {71 const account = web3.eth.accounts.create();72 web3.eth.accounts.wallet.add(account.privateKey);73 return account.address;74}7576export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {77 const alice = privateKey('//Alice');78 const account = createEthAccount(web3);79 await transferBalanceToEth(api, alice, account);8081 return account;82}8384export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {85 const tx = api.tx.balances.transfer(evmToAddress(target), amount);86 const events = await submitTransactionAsync(source, tx);87 const result = getGenericResult(events);88 expect(result.success).to.be.true;89}9091export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {92 let i: any = it;93 if (opts.only) i = i.only;94 else if (opts.skip) i = i.skip;95 i(name, async () => {96 await usingApi(async api => {97 await usingWeb3(async web3 => {98 await cb({api, web3});99 });100 });101 });102}103itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});104itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});105106export async function generateSubstrateEthPair(web3: Web3) {107 const account = web3.eth.accounts.create();108 evmToAddress(account.address);109}110111type NormalizedEvent = {112 address: string,113 event: string,114 args: { [key: string]: string }115};116117export function normalizeEvents(events: any): NormalizedEvent[] {118 const output = [];119 for (const key of Object.keys(events)) {120 if (key.match(/^[0-9]+$/)) {121 output.push(events[key]);122 } else if (Array.isArray(events[key])) {123 output.push(...events[key]);124 } else {125 output.push(events[key]);126 }127 }128 output.sort((a, b) => a.logIndex - b.logIndex);129 return output.map(({address, event, returnValues}) => {130 const args: { [key: string]: string } = {};131 for (const key of Object.keys(returnValues)) {132 if (!key.match(/^[0-9]+$/)) {133 args[key] = returnValues[key];134 }135 }136 return {137 address,138 event,139 args,140 };141 });142}143144export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {145 const out: any = [];146 contract.events.allEvents((_: any, event: any) => {147 out.push(event);148 });149 await action();150 return normalizeEvents(out);151}152153export function subToEthLowercase(eth: string): string {154 const bytes = addressToEvm(eth);155 return '0x' + Buffer.from(bytes).toString('hex');156}157158export function subToEth(eth: string): string {159 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));160}161162export function compileContract(name: string, src: string) {163 const out = JSON.parse(solc.compile(JSON.stringify({164 language: 'Solidity',165 sources: {166 [`${name}.sol`]: {167 content: `168 // SPDX-License-Identifier: UNLICENSED169 pragma solidity ^0.8.6;170171 ${src}172 `,173 },174 },175 settings: {176 outputSelection: {177 '*': {178 '*': ['*'],179 },180 },181 },182 }))).contracts[`${name}.sol`][name];183184 return {185 abi: out.abi,186 object: '0x' + out.evm.bytecode.object,187 };188}189190export async function deployFlipper(web3: Web3, deployer: string) {191 const compiled = compileContract('Flipper', `192 contract Flipper {193 bool value = false;194 function flip() public {195 value = !value;196 }197 function getValue() public view returns (bool) {198 return value;199 }200 }201 `);202 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {203 data: compiled.object,204 from: deployer,205 ...GAS_ARGS,206 });207 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});208209 return flipper;210}211212export async function deployCollector(web3: Web3, deployer: string) {213 const compiled = compileContract('Collector', `214 contract Collector {215 uint256 collected;216 fallback() external payable {217 giveMoney();218 }219 function giveMoney() public payable {220 collected += msg.value;221 }222 function getCollected() public view returns (uint256) {223 return collected;224 }225 function getUnaccounted() public view returns (uint256) {226 return address(this).balance - collected;227 }228229 function withdraw(address payable target) public {230 target.transfer(collected);231 collected = 0;232 }233 }234 `);235 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {236 data: compiled.object,237 from: deployer,238 ...GAS_ARGS,239 });240 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});241242 return collector;243}244245export function contractHelpers(web3: Web3, caller: string) {246 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});247}248249250251252253254255256257258259260261export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {262 const tx = api.tx.evm.call(263 subToEth(from.address),264 to.options.address,265 mkTx(to.methods).encodeABI(),266 value,267 GAS_ARGS.gas,268 await web3.eth.getGasPrice(),269 null,270 null,271 [],272 );273 const events = await submitTransactionAsync(from, tx);274 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;275}276277export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {278 return (await getBalance(api, [evmToAddress(address)]))[0];279}280281282283284285286export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {287 const before = await ethBalanceViaSub(api, user);288289 await call();290291 292 await waitNewBlocks(api, 1);293 const after = await ethBalanceViaSub(api, user);294295 296 expect(after < before).to.be.true;297298 return before - after;299}