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 {CrossAccountId, 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 collectionAbi from '../collectionAbi.json';32import getBalance from '../../substrate/get-balance';33import waitNewBlocks from '../../substrate/wait-new-blocks';3435export const GAS_ARGS = {gas: 2500000};3637export enum SponsoringMode {38 Disabled = 0,39 Allowlisted = 1,40 Generous = 2,41}4243let web3Connected = false;44export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {45 if (web3Connected) throw new Error('do not nest usingWeb3 calls');46 web3Connected = true;4748 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);49 const web3 = new Web3(provider);5051 try {52 return await cb(web3);53 } finally {54 55 provider.connection.close();56 web3Connected = false;57 }58}5960function encodeIntBE(v: number): number[] {61 if (v >= 0xffffffff || v < 0) throw new Error('id overflow');62 return [63 v >> 24,64 (v >> 16) & 0xff,65 (v >> 8) & 0xff,66 v & 0xff,67 ];68}6970export function collectionIdToAddress(collection: number): string {71 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,72 ...encodeIntBE(collection),73 ]);74 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));75}76export function collectionIdFromAddress(address: string): number {77 if (!address.startsWith('0x'))78 throw 'address not starts with "0x"';79 if (address.length > 42)80 throw 'address length is more than 20 bytes';81 return Number('0x' + address.substring(address.length - 8));82}83 84export function normalizeAddress(address: string): string {85 return '0x' + address.substring(address.length - 40);86}8788export function tokenIdToAddress(collection: number, token: number): string {89 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,90 ...encodeIntBE(collection),91 ...encodeIntBE(token),92 ]);93 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));94}95export function tokenIdToCross(collection: number, token: number): CrossAccountId {96 return {97 Ethereum: tokenIdToAddress(collection, token),98 };99100export function createEthAccount(web3: Web3) {101 const account = web3.eth.accounts.create();102 web3.eth.accounts.wallet.add(account.privateKey);103 return account.address;104}105106export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {107 const alice = privateKey('//Alice');108 const account = createEthAccount(web3);109 await transferBalanceToEth(api, alice, account);110111 return account;112}113114export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {115 const tx = api.tx.balances.transfer(evmToAddress(target), amount);116 const events = await submitTransactionAsync(source, tx);117 const result = getGenericResult(events);118 expect(result.success).to.be.true;119}120121export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {122 let i: any = it;123 if (opts.only) i = i.only;124 else if (opts.skip) i = i.skip;125 i(name, async () => {126 await usingApi(async api => {127 await usingWeb3(async web3 => {128 await cb({api, web3});129 });130 });131 });132}133itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});134itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});135136export async function generateSubstrateEthPair(web3: Web3) {137 const account = web3.eth.accounts.create();138 evmToAddress(account.address);139}140141type NormalizedEvent = {142 address: string,143 event: string,144 args: { [key: string]: string }145};146147export function normalizeEvents(events: any): NormalizedEvent[] {148 const output = [];149 for (const key of Object.keys(events)) {150 if (key.match(/^[0-9]+$/)) {151 output.push(events[key]);152 } else if (Array.isArray(events[key])) {153 output.push(...events[key]);154 } else {155 output.push(events[key]);156 }157 }158 output.sort((a, b) => a.logIndex - b.logIndex);159 return output.map(({address, event, returnValues}) => {160 const args: { [key: string]: string } = {};161 for (const key of Object.keys(returnValues)) {162 if (!key.match(/^[0-9]+$/)) {163 args[key] = returnValues[key];164 }165 }166 return {167 address,168 event,169 args,170 };171 });172}173174export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {175 const out: any = [];176 contract.events.allEvents((_: any, event: any) => {177 out.push(event);178 });179 await action();180 return normalizeEvents(out);181}182183export function subToEthLowercase(eth: string): string {184 const bytes = addressToEvm(eth);185 return '0x' + Buffer.from(bytes).toString('hex');186}187188export function subToEth(eth: string): string {189 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));190}191192export function compileContract(name: string, src: string) {193 const out = JSON.parse(solc.compile(JSON.stringify({194 language: 'Solidity',195 sources: {196 [`${name}.sol`]: {197 content: `198 // SPDX-License-Identifier: UNLICENSED199 pragma solidity ^0.8.6;200201 ${src}202 `,203 },204 },205 settings: {206 outputSelection: {207 '*': {208 '*': ['*'],209 },210 },211 },212 }))).contracts[`${name}.sol`][name];213214 return {215 abi: out.abi,216 object: '0x' + out.evm.bytecode.object,217 };218}219220export async function deployFlipper(web3: Web3, deployer: string) {221 const compiled = compileContract('Flipper', `222 contract Flipper {223 bool value = false;224 function flip() public {225 value = !value;226 }227 function getValue() public view returns (bool) {228 return value;229 }230 }231 `);232 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {233 data: compiled.object,234 from: deployer,235 ...GAS_ARGS,236 });237 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});238239 return flipper;240}241242export async function deployCollector(web3: Web3, deployer: string) {243 const compiled = compileContract('Collector', `244 contract Collector {245 uint256 collected;246 fallback() external payable {247 giveMoney();248 }249 function giveMoney() public payable {250 collected += msg.value;251 }252 function getCollected() public view returns (uint256) {253 return collected;254 }255 function getUnaccounted() public view returns (uint256) {256 return address(this).balance - collected;257 }258259 function withdraw(address payable target) public {260 target.transfer(collected);261 collected = 0;262 }263 }264 `);265 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {266 data: compiled.object,267 from: deployer,268 ...GAS_ARGS,269 });270 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});271272 return collector;273}274275276277278279280281export function contractHelpers(web3: Web3, caller: string) {282 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});283}284285286287288289290291export function collectionHelper(web3: Web3, caller: string) {292 return new web3.eth.Contract(collectionAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});293}294295296297298299300301302303304305306307export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {308 const tx = api.tx.evm.call(309 subToEth(from.address),310 to.options.address,311 mkTx(to.methods).encodeABI(),312 value,313 GAS_ARGS.gas,314 await web3.eth.getGasPrice(),315 null,316 null,317 [],318 );319 const events = await submitTransactionAsync(from, tx);320 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;321}322323export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {324 return (await getBalance(api, [evmToAddress(address)]))[0];325}326327328329330331332export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {333 const before = await ethBalanceViaSub(api, user);334335 await call();336337 338 await waitNewBlocks(api, 1);339 const after = await ethBalanceViaSub(api, user);340341 342 expect(after < before).to.be.true;343344 return before - after;345}346347type ElementOf<A> = A extends readonly (infer T)[] ? T : never;348349export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {350 if(args.length === 0) {351 yield internalRest as any;352 return;353 }354 for(const value of args[0]) {355 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;356 }357}