difftreelog
fix relay 3sec/parachain 6sec
in: master
1 file changed
tests/src/eth/util/helpers.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56// eslint-disable-next-line @typescript-eslint/triple-slash-reference7/// <reference path="helpers.d.ts" />89import { ApiPromise } from '@polkadot/api';10import { addressToEvm, evmToAddress } from '@polkadot/util-crypto';11import Web3 from 'web3';12import usingApi, { submitTransactionAsync } from '../../substrate/substrate-api';13import { IKeyringPair } from '@polkadot/types/types';14import { expect } from 'chai';15import { getGenericResult } from '../../util/helpers';16import * as solc from 'solc';17import config from '../../config';18import privateKey from '../../substrate/privateKey';19import contractHelpersAbi from './contractHelpersAbi.json';20import getBalance from '../../substrate/get-balance';2122export const GAS_ARGS = { gas: 0x1000000, gasPrice: '0x01' };2324let web3Connected = false;25export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {26 if (web3Connected) throw new Error('do not nest usingWeb3 calls');27 web3Connected = true;2829 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);30 const web3 = new Web3(provider);3132 try {33 return await cb(web3);34 } finally {35 // provider.disconnect(3000, 'normal disconnect');36 provider.connection.close();37 web3Connected = false;38 }39}4041/**42 * @deprecated Web3 update solved issue with deployment over ws provider43 */44export async function usingWeb3Http<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {45 const provider = new Web3.providers.HttpProvider(config.frontierUrl);46 const web3: Web3 = new Web3(provider);4748 return await cb(web3);49}5051export function collectionIdToAddress(address: number): string {52 if (address >= 0xffffffff || address < 0) throw new Error('id overflow');53 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,54 address >> 24,55 (address >> 16) & 0xff,56 (address >> 8) & 0xff,57 address & 0xff,58 ]);59 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));60}6162export function createEthAccount(web3: Web3) {63 const account = web3.eth.accounts.create();64 web3.eth.accounts.wallet.add(account.privateKey);65 return account.address;66}6768export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {69 const alice = privateKey('//Alice');70 const account = createEthAccount(web3);71 await transferBalanceToEth(api, alice, account);7273 return account;74}7576export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 999999999999999) {77 const tx = api.tx.balances.transfer(evmToAddress(target), amount);78 const events = await submitTransactionAsync(source, tx);79 const result = getGenericResult(events);80 expect(result.success).to.be.true;81}8283export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {84 let i: any = it;85 if (opts.only) i = i.only;86 else if (opts.skip) i = i.skip;87 i(name, async () => {88 await usingApi(async api => {89 await usingWeb3(async web3 => {90 await cb({ api, web3 });91 });92 });93 });94}95itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { only: true });96itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { skip: true });9798export async function generateSubstrateEthPair(web3: Web3) {99 const account = web3.eth.accounts.create();100 evmToAddress(account.address);101}102103type NormalizedEvent = {104 address: string,105 event: string,106 args: { [key: string]: string }107};108109export function normalizeEvents(events: any): NormalizedEvent[] {110 const output = [];111 for (const key of Object.keys(events)) {112 if (key.match(/^[0-9]+$/)) {113 output.push(events[key]);114 } else if (Array.isArray(events[key])) {115 output.push(...events[key]);116 } else {117 output.push(events[key]);118 }119 }120 output.sort((a, b) => a.logIndex - b.logIndex);121 return output.map(({ address, event, returnValues }) => {122 const args: { [key: string]: string } = {};123 for (const key of Object.keys(returnValues)) {124 if (!key.match(/^[0-9]+$/)) {125 args[key] = returnValues[key];126 }127 }128 return {129 address,130 event,131 args,132 };133 });134}135136export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {137 const out: any = [];138 contract.events.allEvents((_: any, event: any) => {139 out.push(event);140 });141 await action();142 return normalizeEvents(out);143}144145export function subToEth(eth: string): string {146 const bytes = addressToEvm(eth);147 const string = '0x' + Buffer.from(bytes).toString('hex');148 return Web3.utils.toChecksumAddress(string);149}150151export function compileContract(name: string, src: string) {152 const out = JSON.parse(solc.compile(JSON.stringify({153 language: 'Solidity',154 sources: {155 [`${name}.sol`]: {156 content: `157 // SPDX-License-Identifier: UNLICENSED158 pragma solidity ^0.8.6;159160 ${src}161 `,162 },163 },164 settings: {165 outputSelection: {166 '*': {167 '*': ['*'],168 },169 },170 },171 }))).contracts[`${name}.sol`][name];172173 return {174 abi: out.abi,175 object: '0x' + out.evm.bytecode.object,176 };177}178179export async function deployFlipper(web3: Web3, deployer: string) {180 const compiled = compileContract('Flipper', `181 contract Flipper {182 bool value = false;183 function flip() public {184 value = !value;185 }186 function getValue() public view returns (bool) {187 return value;188 }189 }190 `);191 const Flipper = new web3.eth.Contract(compiled.abi, undefined, {192 data: compiled.object,193 from: deployer,194 ...GAS_ARGS,195 });196 const flipper = await Flipper.deploy({ data: compiled.object }).send({from: deployer});197198 return flipper;199}200201export async function deployCollector(web3: Web3, deployer: string) {202 const compiled = compileContract('Collector', `203 contract Collector {204 uint256 collected;205 function giveMoney() public payable {206 collected += msg.value;207 }208 function getCollected() public view returns (uint256) {209 return collected;210 }211 }212 `);213 const Collector = new web3.eth.Contract(compiled.abi, undefined, {214 data: compiled.object,215 from: deployer,216 ...GAS_ARGS,217 });218 const collector = await Collector.deploy({ data: compiled.object }).send({ from: deployer });219220 return collector;221}222223export function contractHelpers(web3: Web3, caller: string) {224 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});225}226227export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {228 return (await getBalance(api, [evmToAddress(address)]))[0];229}230231export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {232 const before = await ethBalanceViaSub(api, user);233234 await call();235236 const after = await ethBalanceViaSub(api, user);237238 // Can't use .to.be.less, because chai doesn't supports bigint239 expect(after < before).to.be.true;240241 return before - after;242}1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56// eslint-disable-next-line @typescript-eslint/triple-slash-reference7/// <reference path="helpers.d.ts" />89import { ApiPromise } from '@polkadot/api';10import { addressToEvm, evmToAddress } from '@polkadot/util-crypto';11import Web3 from 'web3';12import usingApi, { submitTransactionAsync } from '../../substrate/substrate-api';13import { IKeyringPair } from '@polkadot/types/types';14import { expect } from 'chai';15import { getGenericResult } from '../../util/helpers';16import * as solc from 'solc';17import config from '../../config';18import privateKey from '../../substrate/privateKey';19import contractHelpersAbi from './contractHelpersAbi.json';20import getBalance from '../../substrate/get-balance';21import waitNewBlocks from '../../substrate/wait-new-blocks';2223export const GAS_ARGS = { gas: 0x1000000, gasPrice: '0x01' };2425let web3Connected = false;26export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {27 if (web3Connected) throw new Error('do not nest usingWeb3 calls');28 web3Connected = true;2930 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);31 const web3 = new Web3(provider);3233 try {34 return await cb(web3);35 } finally {36 // provider.disconnect(3000, 'normal disconnect');37 provider.connection.close();38 web3Connected = false;39 }40}4142/**43 * @deprecated Web3 update solved issue with deployment over ws provider44 */45export async function usingWeb3Http<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {46 const provider = new Web3.providers.HttpProvider(config.frontierUrl);47 const web3: Web3 = new Web3(provider);4849 return await cb(web3);50}5152export function collectionIdToAddress(address: number): string {53 if (address >= 0xffffffff || address < 0) throw new Error('id overflow');54 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,55 address >> 24,56 (address >> 16) & 0xff,57 (address >> 8) & 0xff,58 address & 0xff,59 ]);60 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));61}6263export function createEthAccount(web3: Web3) {64 const account = web3.eth.accounts.create();65 web3.eth.accounts.wallet.add(account.privateKey);66 return account.address;67}6869export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {70 const alice = privateKey('//Alice');71 const account = createEthAccount(web3);72 await transferBalanceToEth(api, alice, account);7374 return account;75}7677export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 999999999999999) {78 const tx = api.tx.balances.transfer(evmToAddress(target), amount);79 const events = await submitTransactionAsync(source, tx);80 const result = getGenericResult(events);81 expect(result.success).to.be.true;82}8384export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {85 let i: any = it;86 if (opts.only) i = i.only;87 else if (opts.skip) i = i.skip;88 i(name, async () => {89 await usingApi(async api => {90 await usingWeb3(async web3 => {91 await cb({ api, web3 });92 });93 });94 });95}96itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { only: true });97itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { skip: true });9899export async function generateSubstrateEthPair(web3: Web3) {100 const account = web3.eth.accounts.create();101 evmToAddress(account.address);102}103104type NormalizedEvent = {105 address: string,106 event: string,107 args: { [key: string]: string }108};109110export function normalizeEvents(events: any): NormalizedEvent[] {111 const output = [];112 for (const key of Object.keys(events)) {113 if (key.match(/^[0-9]+$/)) {114 output.push(events[key]);115 } else if (Array.isArray(events[key])) {116 output.push(...events[key]);117 } else {118 output.push(events[key]);119 }120 }121 output.sort((a, b) => a.logIndex - b.logIndex);122 return output.map(({ address, event, returnValues }) => {123 const args: { [key: string]: string } = {};124 for (const key of Object.keys(returnValues)) {125 if (!key.match(/^[0-9]+$/)) {126 args[key] = returnValues[key];127 }128 }129 return {130 address,131 event,132 args,133 };134 });135}136137export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {138 const out: any = [];139 contract.events.allEvents((_: any, event: any) => {140 out.push(event);141 });142 await action();143 return normalizeEvents(out);144}145146export function subToEth(eth: string): string {147 const bytes = addressToEvm(eth);148 const string = '0x' + Buffer.from(bytes).toString('hex');149 return Web3.utils.toChecksumAddress(string);150}151152export function compileContract(name: string, src: string) {153 const out = JSON.parse(solc.compile(JSON.stringify({154 language: 'Solidity',155 sources: {156 [`${name}.sol`]: {157 content: `158 // SPDX-License-Identifier: UNLICENSED159 pragma solidity ^0.8.6;160161 ${src}162 `,163 },164 },165 settings: {166 outputSelection: {167 '*': {168 '*': ['*'],169 },170 },171 },172 }))).contracts[`${name}.sol`][name];173174 return {175 abi: out.abi,176 object: '0x' + out.evm.bytecode.object,177 };178}179180export async function deployFlipper(web3: Web3, deployer: string) {181 const compiled = compileContract('Flipper', `182 contract Flipper {183 bool value = false;184 function flip() public {185 value = !value;186 }187 function getValue() public view returns (bool) {188 return value;189 }190 }191 `);192 const Flipper = new web3.eth.Contract(compiled.abi, undefined, {193 data: compiled.object,194 from: deployer,195 ...GAS_ARGS,196 });197 const flipper = await Flipper.deploy({ data: compiled.object }).send({from: deployer});198199 return flipper;200}201202export async function deployCollector(web3: Web3, deployer: string) {203 const compiled = compileContract('Collector', `204 contract Collector {205 uint256 collected;206 function giveMoney() public payable {207 collected += msg.value;208 }209 function getCollected() public view returns (uint256) {210 return collected;211 }212 }213 `);214 const Collector = new web3.eth.Contract(compiled.abi, undefined, {215 data: compiled.object,216 from: deployer,217 ...GAS_ARGS,218 });219 const collector = await Collector.deploy({ data: compiled.object }).send({ from: deployer });220221 return collector;222}223224export function contractHelpers(web3: Web3, caller: string) {225 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});226}227228export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {229 return (await getBalance(api, [evmToAddress(address)]))[0];230}231232export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {233 const before = await ethBalanceViaSub(api, user);234235 await call();236 await waitNewBlocks(api, 1);237238 const after = await ethBalanceViaSub(api, user);239240 // Can't use .to.be.less, because chai doesn't supports bigint241 expect(after < before).to.be.true;242243 return before - after;244}