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}5859function encodeIntBE(v: number): number[] {60 if (v >= 0xffffffff || v < 0) throw new Error('id overflow');61 return [62 v >> 24,63 (v >> 16) & 0xff,64 (v >> 8) & 0xff,65 v & 0xff,66 ];67}6869export function collectionIdToAddress(collection: number): string {70 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,71 ...encodeIntBE(collection),72 ]);73 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));74}7576export function tokenIdToAddress(collection: number, token: number): string {77 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,78 ...encodeIntBE(collection),79 ...encodeIntBE(token),80 ]);81 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));82}8384export function createEthAccount(web3: Web3) {85 const account = web3.eth.accounts.create();86 web3.eth.accounts.wallet.add(account.privateKey);87 return account.address;88}8990export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {91 const alice = privateKey('//Alice');92 const account = createEthAccount(web3);93 await transferBalanceToEth(api, alice, account);9495 return account;96}9798export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {99 const tx = api.tx.balances.transfer(evmToAddress(target), amount);100 const events = await submitTransactionAsync(source, tx);101 const result = getGenericResult(events);102 expect(result.success).to.be.true;103}104105export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {106 let i: any = it;107 if (opts.only) i = i.only;108 else if (opts.skip) i = i.skip;109 i(name, async () => {110 await usingApi(async api => {111 await usingWeb3(async web3 => {112 await cb({api, web3});113 });114 });115 });116}117itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});118itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});119120export async function generateSubstrateEthPair(web3: Web3) {121 const account = web3.eth.accounts.create();122 evmToAddress(account.address);123}124125type NormalizedEvent = {126 address: string,127 event: string,128 args: { [key: string]: string }129};130131export function normalizeEvents(events: any): NormalizedEvent[] {132 const output = [];133 for (const key of Object.keys(events)) {134 if (key.match(/^[0-9]+$/)) {135 output.push(events[key]);136 } else if (Array.isArray(events[key])) {137 output.push(...events[key]);138 } else {139 output.push(events[key]);140 }141 }142 output.sort((a, b) => a.logIndex - b.logIndex);143 return output.map(({address, event, returnValues}) => {144 const args: { [key: string]: string } = {};145 for (const key of Object.keys(returnValues)) {146 if (!key.match(/^[0-9]+$/)) {147 args[key] = returnValues[key];148 }149 }150 return {151 address,152 event,153 args,154 };155 });156}157158export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {159 const out: any = [];160 contract.events.allEvents((_: any, event: any) => {161 out.push(event);162 });163 await action();164 return normalizeEvents(out);165}166167export function subToEthLowercase(eth: string): string {168 const bytes = addressToEvm(eth);169 return '0x' + Buffer.from(bytes).toString('hex');170}171172export function subToEth(eth: string): string {173 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));174}175176export function compileContract(name: string, src: string) {177 const out = JSON.parse(solc.compile(JSON.stringify({178 language: 'Solidity',179 sources: {180 [`${name}.sol`]: {181 content: `182 // SPDX-License-Identifier: UNLICENSED183 pragma solidity ^0.8.6;184185 ${src}186 `,187 },188 },189 settings: {190 outputSelection: {191 '*': {192 '*': ['*'],193 },194 },195 },196 }))).contracts[`${name}.sol`][name];197198 return {199 abi: out.abi,200 object: '0x' + out.evm.bytecode.object,201 };202}203204export async function deployFlipper(web3: Web3, deployer: string) {205 const compiled = compileContract('Flipper', `206 contract Flipper {207 bool value = false;208 function flip() public {209 value = !value;210 }211 function getValue() public view returns (bool) {212 return value;213 }214 }215 `);216 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {217 data: compiled.object,218 from: deployer,219 ...GAS_ARGS,220 });221 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});222223 return flipper;224}225226export async function deployCollector(web3: Web3, deployer: string) {227 const compiled = compileContract('Collector', `228 contract Collector {229 uint256 collected;230 fallback() external payable {231 giveMoney();232 }233 function giveMoney() public payable {234 collected += msg.value;235 }236 function getCollected() public view returns (uint256) {237 return collected;238 }239 function getUnaccounted() public view returns (uint256) {240 return address(this).balance - collected;241 }242243 function withdraw(address payable target) public {244 target.transfer(collected);245 collected = 0;246 }247 }248 `);249 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {250 data: compiled.object,251 from: deployer,252 ...GAS_ARGS,253 });254 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});255256 return collector;257}258259260261262263264265export function contractHelpers(web3: Web3, caller: string) {266 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});267}268269270271272273274275276277278279280281export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {282 const tx = api.tx.evm.call(283 subToEth(from.address),284 to.options.address,285 mkTx(to.methods).encodeABI(),286 value,287 GAS_ARGS.gas,288 await web3.eth.getGasPrice(),289 null,290 null,291 [],292 );293 const events = await submitTransactionAsync(from, tx);294 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;295}296297export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {298 return (await getBalance(api, [evmToAddress(address)]))[0];299}300301302303304305306export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {307 const before = await ethBalanceViaSub(api, user);308309 await call();310311 312 await waitNewBlocks(api, 1);313 const after = await ethBalanceViaSub(api, user);314315 316 expect(after < before).to.be.true;317318 return before - after;319}