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';3233export const GAS_ARGS = {gas: 2500000};3435export enum SponsoringMode {36 Disabled = 0,37 Allowlisted = 1,38 Generous = 2,39}4041let web3Connected = false;42export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {43 if (web3Connected) throw new Error('do not nest usingWeb3 calls');44 web3Connected = true;4546 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);47 const web3 = new Web3(provider);4849 try {50 return await cb(web3);51 } finally {52 53 provider.connection.close();54 web3Connected = false;55 }56}5758export function collectionIdToAddress(address: number): string {59 if (address >= 0xffffffff || address < 0) throw new Error('id overflow');60 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,61 address >> 24,62 (address >> 16) & 0xff,63 (address >> 8) & 0xff,64 address & 0xff,65 ]);66 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));67}6869export function createEthAccount(web3: Web3) {70 const account = web3.eth.accounts.create();71 web3.eth.accounts.wallet.add(account.privateKey);72 return account.address;73}7475export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {76 const alice = privateKey('//Alice');77 const account = createEthAccount(web3);78 await transferBalanceToEth(api, alice, account);7980 return account;81}8283export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {84 const tx = api.tx.balances.transfer(evmToAddress(target), amount);85 const events = await submitTransactionAsync(source, tx);86 const result = getGenericResult(events);87 expect(result.success).to.be.true;88}8990export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {91 let i: any = it;92 if (opts.only) i = i.only;93 else if (opts.skip) i = i.skip;94 i(name, async () => {95 await usingApi(async api => {96 await usingWeb3(async web3 => {97 await cb({api, web3});98 });99 });100 });101}102itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});103itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});104105export async function generateSubstrateEthPair(web3: Web3) {106 const account = web3.eth.accounts.create();107 evmToAddress(account.address);108}109110type NormalizedEvent = {111 address: string,112 event: string,113 args: { [key: string]: string }114};115116export function normalizeEvents(events: any): NormalizedEvent[] {117 const output = [];118 for (const key of Object.keys(events)) {119 if (key.match(/^[0-9]+$/)) {120 output.push(events[key]);121 } else if (Array.isArray(events[key])) {122 output.push(...events[key]);123 } else {124 output.push(events[key]);125 }126 }127 output.sort((a, b) => a.logIndex - b.logIndex);128 return output.map(({address, event, returnValues}) => {129 const args: { [key: string]: string } = {};130 for (const key of Object.keys(returnValues)) {131 if (!key.match(/^[0-9]+$/)) {132 args[key] = returnValues[key];133 }134 }135 return {136 address,137 event,138 args,139 };140 });141}142143export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {144 const out: any = [];145 contract.events.allEvents((_: any, event: any) => {146 out.push(event);147 });148 await action();149 return normalizeEvents(out);150}151152export function subToEthLowercase(eth: string): string {153 const bytes = addressToEvm(eth);154 return '0x' + Buffer.from(bytes).toString('hex');155}156157export function subToEth(eth: string): string {158 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));159}160161export function compileContract(name: string, src: string) {162 const out = JSON.parse(solc.compile(JSON.stringify({163 language: 'Solidity',164 sources: {165 [`${name}.sol`]: {166 content: `167 // SPDX-License-Identifier: UNLICENSED168 pragma solidity ^0.8.6;169170 ${src}171 `,172 },173 },174 settings: {175 outputSelection: {176 '*': {177 '*': ['*'],178 },179 },180 },181 }))).contracts[`${name}.sol`][name];182183 return {184 abi: out.abi,185 object: '0x' + out.evm.bytecode.object,186 };187}188189export async function deployFlipper(web3: Web3, deployer: string) {190 const compiled = compileContract('Flipper', `191 contract Flipper {192 bool value = false;193 function flip() public {194 value = !value;195 }196 function getValue() public view returns (bool) {197 return value;198 }199 }200 `);201 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {202 data: compiled.object,203 from: deployer,204 ...GAS_ARGS,205 });206 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});207208 return flipper;209}210211export async function deployCollector(web3: Web3, deployer: string) {212 const compiled = compileContract('Collector', `213 contract Collector {214 uint256 collected;215 fallback() external payable {216 giveMoney();217 }218 function giveMoney() public payable {219 collected += msg.value;220 }221 function getCollected() public view returns (uint256) {222 return collected;223 }224 function getUnaccounted() public view returns (uint256) {225 return address(this).balance - collected;226 }227228 function withdraw(address payable target) public {229 target.transfer(collected);230 collected = 0;231 }232 }233 `);234 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {235 data: compiled.object,236 from: deployer,237 ...GAS_ARGS,238 });239 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});240241 return collector;242}243244export function contractHelpers(web3: Web3, caller: string) {245 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});246}247248249250251252253254255256257258259260export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {261 const tx = api.tx.evm.call(262 subToEth(from.address),263 to.options.address,264 mkTx(to.methods).encodeABI(),265 value,266 GAS_ARGS.gas,267 await web3.eth.getGasPrice(),268 null,269 null,270 [],271 );272 const events = await submitTransactionAsync(from, tx);273 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;274}275276export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {277 return (await getBalance(api, [evmToAddress(address)]))[0];278}279280281282283284285export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {286 const before = await ethBalanceViaSub(api, user);287288 await call();289290 const after = await ethBalanceViaSub(api, user);291292 293 expect(after < before).to.be.true;294295 return before - after;296}