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 return Number('0x' + address.substring(address.length - 8));78}7980export function tokenIdToAddress(collection: number, token: number): string {81 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,82 ...encodeIntBE(collection),83 ...encodeIntBE(token),84 ]);85 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));86}87export function tokenIdToCross(collection: number, token: number): CrossAccountId {88 return {89 Ethereum: tokenIdToAddress(collection, token),90 };9192export function createEthAccount(web3: Web3) {93 const account = web3.eth.accounts.create();94 web3.eth.accounts.wallet.add(account.privateKey);95 return account.address;96}9798export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {99 const alice = privateKey('//Alice');100 const account = createEthAccount(web3);101 await transferBalanceToEth(api, alice, account);102103 return account;104}105106export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {107 const tx = api.tx.balances.transfer(evmToAddress(target), amount);108 const events = await submitTransactionAsync(source, tx);109 const result = getGenericResult(events);110 expect(result.success).to.be.true;111}112113export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {114 let i: any = it;115 if (opts.only) i = i.only;116 else if (opts.skip) i = i.skip;117 i(name, async () => {118 await usingApi(async api => {119 await usingWeb3(async web3 => {120 await cb({api, web3});121 });122 });123 });124}125itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});126itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});127128export async function generateSubstrateEthPair(web3: Web3) {129 const account = web3.eth.accounts.create();130 evmToAddress(account.address);131}132133type NormalizedEvent = {134 address: string,135 event: string,136 args: { [key: string]: string }137};138139export function normalizeEvents(events: any): NormalizedEvent[] {140 const output = [];141 for (const key of Object.keys(events)) {142 if (key.match(/^[0-9]+$/)) {143 output.push(events[key]);144 } else if (Array.isArray(events[key])) {145 output.push(...events[key]);146 } else {147 output.push(events[key]);148 }149 }150 output.sort((a, b) => a.logIndex - b.logIndex);151 return output.map(({address, event, returnValues}) => {152 const args: { [key: string]: string } = {};153 for (const key of Object.keys(returnValues)) {154 if (!key.match(/^[0-9]+$/)) {155 args[key] = returnValues[key];156 }157 }158 return {159 address,160 event,161 args,162 };163 });164}165166export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {167 const out: any = [];168 contract.events.allEvents((_: any, event: any) => {169 out.push(event);170 });171 await action();172 return normalizeEvents(out);173}174175export function subToEthLowercase(eth: string): string {176 const bytes = addressToEvm(eth);177 return '0x' + Buffer.from(bytes).toString('hex');178}179180export function subToEth(eth: string): string {181 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));182}183184export function compileContract(name: string, src: string) {185 const out = JSON.parse(solc.compile(JSON.stringify({186 language: 'Solidity',187 sources: {188 [`${name}.sol`]: {189 content: `190 // SPDX-License-Identifier: UNLICENSED191 pragma solidity ^0.8.6;192193 ${src}194 `,195 },196 },197 settings: {198 outputSelection: {199 '*': {200 '*': ['*'],201 },202 },203 },204 }))).contracts[`${name}.sol`][name];205206 return {207 abi: out.abi,208 object: '0x' + out.evm.bytecode.object,209 };210}211212export async function deployFlipper(web3: Web3, deployer: string) {213 const compiled = compileContract('Flipper', `214 contract Flipper {215 bool value = false;216 function flip() public {217 value = !value;218 }219 function getValue() public view returns (bool) {220 return value;221 }222 }223 `);224 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {225 data: compiled.object,226 from: deployer,227 ...GAS_ARGS,228 });229 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});230231 return flipper;232}233234export async function deployCollector(web3: Web3, deployer: string) {235 const compiled = compileContract('Collector', `236 contract Collector {237 uint256 collected;238 fallback() external payable {239 giveMoney();240 }241 function giveMoney() public payable {242 collected += msg.value;243 }244 function getCollected() public view returns (uint256) {245 return collected;246 }247 function getUnaccounted() public view returns (uint256) {248 return address(this).balance - collected;249 }250251 function withdraw(address payable target) public {252 target.transfer(collected);253 collected = 0;254 }255 }256 `);257 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {258 data: compiled.object,259 from: deployer,260 ...GAS_ARGS,261 });262 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});263264 return collector;265}266267268269270271272273export function contractHelpers(web3: Web3, caller: string) {274 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});275}276277278279280281282283export function collectionHelper(web3: Web3, caller: string) {284 return new web3.eth.Contract(collectionAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});285}286287288289290291292293294295296297298299export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {300 const tx = api.tx.evm.call(301 subToEth(from.address),302 to.options.address,303 mkTx(to.methods).encodeABI(),304 value,305 GAS_ARGS.gas,306 await web3.eth.getGasPrice(),307 null,308 null,309 [],310 );311 const events = await submitTransactionAsync(from, tx);312 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;313}314315export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {316 return (await getBalance(api, [evmToAddress(address)]))[0];317}318319320321322323324export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {325 const before = await ethBalanceViaSub(api, user);326327 await call();328329 330 await waitNewBlocks(api, 1);331 const after = await ethBalanceViaSub(api, user);332333 334 expect(after < before).to.be.true;335336 return before - after;337}338339type ElementOf<A> = A extends readonly (infer T)[] ? T : never;340341export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {342 if(args.length === 0) {343 yield internalRest as any;344 return;345 }346 for(const value of args[0]) {347 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;348 }349}