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 collectionHelperAbi from '../collectionHelperAbi.json';33import getBalance from '../../substrate/get-balance';34import waitNewBlocks from '../../substrate/wait-new-blocks';3536export const GAS_ARGS = {gas: 2500000};3738export enum SponsoringMode {39 Disabled = 0,40 Allowlisted = 1,41 Generous = 2,42}4344let web3Connected = false;45export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {46 if (web3Connected) throw new Error('do not nest usingWeb3 calls');47 web3Connected = true;4849 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);50 const web3 = new Web3(provider);5152 try {53 return await cb(web3);54 } finally {55 56 provider.connection.close();57 web3Connected = false;58 }59}6061function encodeIntBE(v: number): number[] {62 if (v >= 0xffffffff || v < 0) throw new Error('id overflow');63 return [64 v >> 24,65 (v >> 16) & 0xff,66 (v >> 8) & 0xff,67 v & 0xff,68 ];69}7071export function collectionIdToAddress(collection: number): string {72 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,73 ...encodeIntBE(collection),74 ]);75 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));76}77export function collectionIdFromAddress(address: string): number {78 if (!address.startsWith('0x'))79 throw 'address not starts with "0x"';80 if (address.length > 42)81 throw 'address length is more than 20 bytes';82 return Number('0x' + address.substring(address.length - 8));83}84 85export function normalizeAddress(address: string): string {86 return '0x' + address.substring(address.length - 40);87}8889export function tokenIdToAddress(collection: number, token: number): string {90 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,91 ...encodeIntBE(collection),92 ...encodeIntBE(token),93 ]);94 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));95}96export function tokenIdToCross(collection: number, token: number): CrossAccountId {97 return {98 Ethereum: tokenIdToAddress(collection, token),99 };100101export function createEthAccount(web3: Web3) {102 const account = web3.eth.accounts.create();103 web3.eth.accounts.wallet.add(account.privateKey);104 return account.address;105}106107export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {108 const alice = privateKey('//Alice');109 const account = createEthAccount(web3);110 await transferBalanceToEth(api, alice, account);111112 return account;113}114115export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {116 const tx = api.tx.balances.transfer(evmToAddress(target), amount);117 const events = await submitTransactionAsync(source, tx);118 const result = getGenericResult(events);119 expect(result.success).to.be.true;120}121122export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {123 let i: any = it;124 if (opts.only) i = i.only;125 else if (opts.skip) i = i.skip;126 i(name, async () => {127 await usingApi(async api => {128 await usingWeb3(async web3 => {129 await cb({api, web3});130 });131 });132 });133}134itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});135itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});136137export async function generateSubstrateEthPair(web3: Web3) {138 const account = web3.eth.accounts.create();139 evmToAddress(account.address);140}141142type NormalizedEvent = {143 address: string,144 event: string,145 args: { [key: string]: string }146};147148export function normalizeEvents(events: any): NormalizedEvent[] {149 const output = [];150 for (const key of Object.keys(events)) {151 if (key.match(/^[0-9]+$/)) {152 output.push(events[key]);153 } else if (Array.isArray(events[key])) {154 output.push(...events[key]);155 } else {156 output.push(events[key]);157 }158 }159 output.sort((a, b) => a.logIndex - b.logIndex);160 return output.map(({address, event, returnValues}) => {161 const args: { [key: string]: string } = {};162 for (const key of Object.keys(returnValues)) {163 if (!key.match(/^[0-9]+$/)) {164 args[key] = returnValues[key];165 }166 }167 return {168 address,169 event,170 args,171 };172 });173}174175export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {176 const out: any = [];177 contract.events.allEvents((_: any, event: any) => {178 out.push(event);179 });180 await action();181 return normalizeEvents(out);182}183184export function subToEthLowercase(eth: string): string {185 const bytes = addressToEvm(eth);186 return '0x' + Buffer.from(bytes).toString('hex');187}188189export function subToEth(eth: string): string {190 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));191}192193export function compileContract(name: string, src: string) {194 const out = JSON.parse(solc.compile(JSON.stringify({195 language: 'Solidity',196 sources: {197 [`${name}.sol`]: {198 content: `199 // SPDX-License-Identifier: UNLICENSED200 pragma solidity ^0.8.6;201202 ${src}203 `,204 },205 },206 settings: {207 outputSelection: {208 '*': {209 '*': ['*'],210 },211 },212 },213 }))).contracts[`${name}.sol`][name];214215 return {216 abi: out.abi,217 object: '0x' + out.evm.bytecode.object,218 };219}220221export async function deployFlipper(web3: Web3, deployer: string) {222 const compiled = compileContract('Flipper', `223 contract Flipper {224 bool value = false;225 function flip() public {226 value = !value;227 }228 function getValue() public view returns (bool) {229 return value;230 }231 }232 `);233 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {234 data: compiled.object,235 from: deployer,236 ...GAS_ARGS,237 });238 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});239240 return flipper;241}242243export async function deployCollector(web3: Web3, deployer: string) {244 const compiled = compileContract('Collector', `245 contract Collector {246 uint256 collected;247 fallback() external payable {248 giveMoney();249 }250 function giveMoney() public payable {251 collected += msg.value;252 }253 function getCollected() public view returns (uint256) {254 return collected;255 }256 function getUnaccounted() public view returns (uint256) {257 return address(this).balance - collected;258 }259260 function withdraw(address payable target) public {261 target.transfer(collected);262 collected = 0;263 }264 }265 `);266 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {267 data: compiled.object,268 from: deployer,269 ...GAS_ARGS,270 });271 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});272273 return collector;274}275276277278279280281282export function contractHelpers(web3: Web3, caller: string) {283 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});284}285286287288289290291292export function evmCollectionHelper(web3: Web3, caller: string) {293 return new web3.eth.Contract(collectionHelperAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});294}295296297298299300301302export function evmCollection(web3: Web3, caller: string, collection: string) {303 return new web3.eth.Contract(collectionAbi as any, collection, {from: caller, ...GAS_ARGS});304}305306307308309310311312313314315316317318export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {319 const tx = api.tx.evm.call(320 subToEth(from.address),321 to.options.address,322 mkTx(to.methods).encodeABI(),323 value,324 GAS_ARGS.gas,325 await web3.eth.getGasPrice(),326 null,327 null,328 [],329 );330 const events = await submitTransactionAsync(from, tx);331 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;332}333334export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {335 return (await getBalance(api, [evmToAddress(address)]))[0];336}337338339340341342343export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {344 const before = await ethBalanceViaSub(api, user);345346 await call();347348 349 await waitNewBlocks(api, 1);350 const after = await ethBalanceViaSub(api, user);351352 353 expect(after < before).to.be.true;354355 return before - after;356}357358type ElementOf<A> = A extends readonly (infer T)[] ? T : never;359360export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {361 if(args.length === 0) {362 yield internalRest as any;363 return;364 }365 for(const value of args[0]) {366 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;367 }368}