difftreelog
Sponsoring tests
in: master
3 files changed
tests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -5,92 +5,166 @@
import privateKey from '../substrate/privateKey';
import { expect } from 'chai';
-import { createCollectionExpectSuccess,
- createFungibleItemExpectSuccess,
- transferExpectSuccess,
- transferFromExpectSuccess,
- createItemExpectSuccess,
- setContractSponsoringRateLimitExpectSuccess,
- enableContractSponsoringExpectSuccess,
- setCollectionSponsorExpectSuccess,
- confirmSponsorshipExpectSuccess,
- enableContractSponsoringExpectFailure} from '../util/helpers';
-import { collectionIdToAddress,
+import {
contractHelpers,
createEthAccountWithBalance,
createEthAccount,
transferBalanceToEth,
- subToEth,
deployFlipper,
usingWeb3Http,
- deployFungibleContract,
- GAS_ARGS, itWeb3 } from './util/helpers';
+ itWeb3 } from './util/helpers';
import waitNewBlocks from '../substrate/wait-new-blocks';
-import fungibleAbi from './fungibleAbi.json';
-import nonFungibleAbi from './nonFungibleAbi.json';
describe.only('Sponsoring EVM contracts', () => {
- itWeb3.skip('Sponsoring can be set by the address that has deployed the contract', async ({api, web3}) => {
+ itWeb3('Sponsoring can be set by the address that has deployed the contract', async ({api}) => {
await usingWeb3Http(async web3Http => {
const owner = await createEthAccountWithBalance(api, web3Http);
- const fungible = await deployFungibleContract(web3Http, owner);
+ const flipper = await deployFlipper(web3Http, owner);
await waitNewBlocks(api, 1);
const helpers = contractHelpers(web3Http, owner);
await waitNewBlocks(api, 1);
- expect(await helpers.methods.sponsoringEnabled(fungible.options.address).call()).to.be.false;
+ expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
await waitNewBlocks(api, 1);
- await helpers.methods.toggleSponsoring(fungible.options.address, true).send({from: owner});
+ await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
await waitNewBlocks(api, 1);
- expect(await helpers.methods.sponsoringEnabled(fungible.options.address).call()).to.be.true;
+ expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
});
});
- itWeb3.skip('Sponsoring cannot be set by the address that did not deployed the contract', async ({api, web3}) => {
+ itWeb3('Sponsoring cannot be set by the address that did not deployed the contract', async ({api}) => {
await usingWeb3Http(async web3Http => {
const owner = await createEthAccountWithBalance(api, web3Http);
const notOwner = await createEthAccountWithBalance(api, web3Http);
- const fungible = await deployFungibleContract(web3Http, owner);
+ const flipper = await deployFlipper(web3Http, owner);
await waitNewBlocks(api, 1);
const helpers = contractHelpers(web3Http, owner);
await waitNewBlocks(api, 1);
- expect(await helpers.methods.sponsoringEnabled(fungible.options.address).call()).to.be.false;
+ expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
await waitNewBlocks(api, 1);
await expect(helpers.methods.toggleSponsoring(notOwner, true).send({from: notOwner})).to.rejected;
await waitNewBlocks(api, 1);
- expect(await helpers.methods.sponsoringEnabled(fungible.options.address).call()).to.be.false;
+ expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
+ });
+ });
+
+ itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works. Sponsor balance should decrease', async ({api, web3}) => {
+ await usingWeb3Http(async web3Http => {
+ const alice = privateKey('//Alice');
+
+ const owner = await createEthAccountWithBalance(api, web3Http);
+ const caller = createEthAccount(web3Http);
+ const originalCallerBalance = await web3.eth.getBalance(caller);
+ expect(originalCallerBalance).to.be.equal('0');
+
+ const flipper = await deployFlipper(web3Http, owner);
+ await waitNewBlocks(api, 1);
+
+ const helpers = contractHelpers(web3Http, owner);
+ await helpers.methods.toggleAllowlist(flipper.options.address, true).send({ from: owner });
+ await waitNewBlocks(api, 1);
+ await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({ from: owner });
+ await waitNewBlocks(api, 1);
+
+ expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
+ await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
+ await waitNewBlocks(api, 1);
+ await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
+ await waitNewBlocks(api, 1);
+ expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
+
+ await transferBalanceToEth(api, alice, flipper.options.address);
+ await waitNewBlocks(api, 2);
+
+ const originalFlipperBalance = await web3.eth.getBalance(flipper.options.address);
+ expect(originalFlipperBalance).to.be.not.equal('0');
+
+ await flipper.methods.flip().send({ from: caller });
+ await waitNewBlocks(api, 1);
+ expect(await flipper.methods.getValue().call()).to.be.true;
+
+ // Balance should be taken from flipper instead of caller
+ const balanceAfter = await web3.eth.getBalance(flipper.options.address);
+ expect(+balanceAfter).to.be.lessThan(+originalFlipperBalance);
});
});
- itWeb3('Sponsoring is set, an address that has no UNQ can send a transaction and it works', async ({api, web3}) => {
+ itWeb3('Sponsoring is set, an address that has UNQ can send a transaction and it works. User balance should not change', async ({api, web3}) => {
await usingWeb3Http(async web3Http => {
const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
- const collection = await createCollectionExpectSuccess({
- mode: { type: 'Fungible', decimalPoints: 0 },
- });
- await createFungibleItemExpectSuccess(alice, collection, { Value: 200n }, alice.address);
+
const owner = await createEthAccountWithBalance(api, web3Http);
- const notOwner = await createEthAccountWithBalance(api, web3Http);
- await transferExpectSuccess(collection, 0, alice, { ethereum: notOwner } , 200, 'Fungible');
- const address = collectionIdToAddress(collection);
- const fungible = await deployFungibleContract(web3Http, address);
- await transferBalanceToEth(api, alice, fungible.options.address);
+ const caller = createEthAccount(web3Http);
+ const originalCallerBalance = await web3.eth.getBalance(caller);
+ expect(originalCallerBalance).to.be.equal('0');
+
+ const flipper = await deployFlipper(web3Http, owner);
+ await waitNewBlocks(api, 1);
+
+ const helpers = contractHelpers(web3Http, owner);
+ await helpers.methods.toggleAllowlist(flipper.options.address, true).send({ from: owner });
await waitNewBlocks(api, 1);
- const balanceBefore = await web3.eth.getBalance(fungible.options.address);
+ await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({ from: owner });
+ await waitNewBlocks(api, 1);
- const helpers = contractHelpers(web3Http, address);
+ expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
+ await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
await waitNewBlocks(api, 1);
- expect(await helpers.methods.sponsoringEnabled(fungible.options.address).call()).to.be.false;
+ await helpers.methods.setSponsoringRateLimit(flipper.options.address, 0).send({from: owner});
await waitNewBlocks(api, 1);
- await helpers.methods.toggleSponsoring(fungible.options.address, true).send({from: owner});
+ expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
+
+ await transferBalanceToEth(api, alice, flipper.options.address);
+ await waitNewBlocks(api, 2);
+
+ const originalFlipperBalance = await web3.eth.getBalance(flipper.options.address);
+ expect(originalFlipperBalance).to.be.not.equal('0');
+
+ await flipper.methods.flip().send({ from: caller });
await waitNewBlocks(api, 1);
- expect(await helpers.methods.sponsoringEnabled(fungible.options.address).call()).to.be.true;
+ expect(await flipper.methods.getValue().call()).to.be.true;
-// await fungible.methods.approve(owner, 50).send({ from: owner });
- await fungible.methods.transferFrom(notOwner, owner, 50).send({ from: notOwner });
- const balanceAfter = await web3.eth.getBalance(fungible.options.address);
- expect(+balanceAfter).to.lessThan(+balanceBefore);
+ expect(await web3.eth.getBalance(caller)).to.be.equals(originalCallerBalance);
});
});
+ itWeb3('Sponsoring is limited, with setContractRateLimit. The limitation is working if transactions are sent more often, the sender pays the commission.', async ({api, web3}) => {
+ await usingWeb3Http(async web3Http => {
+ const alice = privateKey('//Alice');
+
+ const owner = await createEthAccountWithBalance(api, web3Http);
+ const caller = await createEthAccountWithBalance(api, web3Http);
+ const originalCallerBalance = await web3.eth.getBalance(caller);
+
+ const flipper = await deployFlipper(web3Http, owner);
+ await waitNewBlocks(api, 1);
+
+ const helpers = contractHelpers(web3Http, owner);
+ await helpers.methods.toggleAllowlist(flipper.options.address, true).send({ from: owner });
+ await waitNewBlocks(api, 1);
+ await helpers.methods.toggleAllowed(flipper.options.address, caller, true).send({ from: owner });
+ await waitNewBlocks(api, 1);
+
+ expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.false;
+ await helpers.methods.toggleSponsoring(flipper.options.address, true).send({from: owner});
+ await waitNewBlocks(api, 1);
+ await helpers.methods.setSponsoringRateLimit(flipper.options.address, 10).send({from: owner});
+ await waitNewBlocks(api, 1);
+ expect(await helpers.methods.sponsoringEnabled(flipper.options.address).call()).to.be.true;
+
+ await transferBalanceToEth(api, alice, flipper.options.address);
+ await waitNewBlocks(api, 2);
+
+ const originalFlipperBalance = await web3.eth.getBalance(flipper.options.address);
+ expect(originalFlipperBalance).to.be.not.equal('0');
+
+ await flipper.methods.flip().send({ from: caller });
+ await waitNewBlocks(api, 1);
+ expect(await flipper.methods.getValue().call()).to.be.true;
+ expect(await web3.eth.getBalance(caller)).to.be.equals(originalCallerBalance);
+
+ await flipper.methods.flip().send({ from: caller });
+ await waitNewBlocks(api, 1);
+ expect(await web3.eth.getBalance(caller)).to.be.not.equals(originalCallerBalance);
+ });
+ });
});
tests/src/eth/util/ERC721.soldiffbeforeafterboth--- a/tests/src/eth/util/ERC721.sol
+++ /dev/null
@@ -1,159 +0,0 @@
-contract ERC721 {
- uint8 _dummy = 0;
- address _dummy_addr = 0x0000000000000000000000000000000000000000;
- string _dummy_string = "";
- string stub_error =
- "this contract does not exists, code for collections is implemented at pallet side";
-
- event Transfer(
- address indexed from,
- address indexed to,
- uint256 indexed tokenId
- );
-
- event Approval(
- address indexed owner,
- address indexed approved,
- uint256 indexed tokenId
- );
-
- event ApprovalForAll(
- address indexed owner,
- address indexed operator,
- bool approved
- );
-
- // 0x18160ddd
- function totalSupply() external view returns (uint256) {
- require(false, stub_error);
- return 0;
- }
-
- function name() external view returns (string memory res_name) {
- require(false, stub_error);
- res_name = _dummy_string;
- }
-
- function symbol() external view returns (string memory res_symbol) {
- require(false, stub_error);
- res_symbol = _dummy_string;
- }
-
- function tokenURI(uint256 tokenId) external view returns (string memory) {
- require(false, stub_error);
- tokenId;
- return _dummy_string;
- }
-
- function tokenByIndex(uint256 index) external view returns (uint256) {
- require(false, stub_error);
- index;
- return 0;
- }
-
- function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256) {
- require(false, stub_error);
- owner;
- index;
- return 0;
- }
-
- // 0x70a08231
- function balanceOf(address owner) external view returns (uint256) {
- require(false, stub_error);
- owner;
- return 0;
- }
-
- // 0x6352211e
- function ownerOf(uint256 tokenId) external view returns (address) {
- require(false, stub_error);
- tokenId;
- return _dummy_addr;
- }
-
- // 0xb88d4fde
- function safeTransferFrom(
- address from,
- address to,
- uint256 tokenId,
- bytes calldata data
- ) external payable {
- require(false, stub_error);
- from;
- to;
- tokenId;
- data;
- }
-
- // 0x42842e0e
- function safeTransferFrom(
- address from,
- address to,
- uint256 tokenId
- ) external payable {
- require(false, stub_error);
- from;
- to;
- tokenId;
- }
-
- // 0x23b872dd
- function transferFrom(
- address from,
- address to,
- uint256 tokenId
- ) external payable {
- require(false, stub_error);
- from;
- to;
- tokenId;
- }
-
- // 0x095ea7b3
- function approve(address approved, uint256 tokenId) external payable {
- require(false, stub_error);
- approved;
- tokenId;
- }
-
- // 0xa22cb465
- function setApprovalForAll(address operator, bool approved) external {
- require(false, stub_error);
- operator;
- approved;
- _dummy = 0;
- }
-
- // 0x081812fc
- function getApproved(uint256 tokenId) external view returns (address) {
- require(false, stub_error);
- tokenId;
- return _dummy_addr;
- }
-
- // 0xe985e9c5
- function isApprovedForAll(address owner, address operator)
- external
- view
- returns (bool)
- {
- require(false, stub_error);
- owner;
- operator;
- return false;
- }
-
- // 0x01ffc9a7
- function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
- return
- // ERC721
- interfaceID == 0x80ac58cd ||
- // ERC721Metadata
- interfaceID == 0x5b5e139f ||
- // ERC721Enumerable
- interfaceID == 0x780e9d63 ||
- // ERC165
- interfaceID == 0x01ffc9a7;
- }
-}
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 fs from 'fs';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}4041type Web3HttpMarker = {web3Http: true};4243export async function usingWeb3Http<T>(cb: (web3: Web3 & Web3HttpMarker) => Promise<T> | T): Promise<T> {44 const provider = new Web3.providers.HttpProvider(config.frontierUrl);45 const web3: Web3 & Web3HttpMarker = new Web3(provider) as any;46 web3.web3Http = true;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 deployFungibleContract(web3: Web3 & Web3HttpMarker, deployer: string) {180181 const sol = fs.readFileSync(__dirname + '/ERC721.sol').toString();182183 const compiled = compileContract('ERC721', sol);184 const ERC721 = new web3.eth.Contract(compiled.abi, undefined, {185 data: compiled.object,186 from: deployer,187 ...GAS_ARGS,188 });189 const fungible = await ERC721.deploy({ data: compiled.object }).send({from: deployer});190191 return fungible;192}193194export async function deployFlipper(web3: Web3 & Web3HttpMarker, deployer: string) {195 const compiled = compileContract('Flipper', `196 contract Flipper {197 bool value = false;198 function flip() public {199 value = !value;200 }201 function getValue() public view returns (bool) {202 return value;203 }204 }205 `);206 const Flipper = new web3.eth.Contract(compiled.abi, undefined, {207 data: compiled.object,208 from: deployer,209 ...GAS_ARGS,210 });211 const flipper = await Flipper.deploy({ data: compiled.object }).send({from: deployer});212213 return flipper;214}215216export async function deployCollector(web3: Web3 & Web3HttpMarker, deployer: string) {217 const compiled = compileContract('Collector', `218 contract Collector {219 uint256 collected;220 function giveMoney() public payable {221 collected += msg.value;222 }223 function getCollected() public view returns (uint256) {224 return collected;225 }226 }227 `);228 const Collector = new web3.eth.Contract(compiled.abi, undefined, {229 data: compiled.object,230 from: deployer,231 ...GAS_ARGS,232 });233 const collector = await Collector.deploy({ data: compiled.object }).send({ from: deployer });234235 return collector;236}237238export function contractHelpers(web3: Web3, caller: string) {239 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});240}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';2021export const GAS_ARGS = { gas: 0x1000000, gasPrice: '0x01' };2223let web3Connected = false;24export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {25 if (web3Connected) throw new Error('do not nest usingWeb3 calls');26 web3Connected = true;2728 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);29 const web3 = new Web3(provider);3031 try {32 return await cb(web3);33 } finally {34 // provider.disconnect(3000, 'normal disconnect');35 provider.connection.close();36 web3Connected = false;37 }38}3940type Web3HttpMarker = {web3Http: true};4142export async function usingWeb3Http<T>(cb: (web3: Web3 & Web3HttpMarker) => Promise<T> | T): Promise<T> {43 const provider = new Web3.providers.HttpProvider(config.frontierUrl);44 const web3: Web3 & Web3HttpMarker = new Web3(provider) as any;45 web3.web3Http = true;4647 return await cb(web3);48}4950export function collectionIdToAddress(address: number): string {51 if (address >= 0xffffffff || address < 0) throw new Error('id overflow');52 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,53 address >> 24,54 (address >> 16) & 0xff,55 (address >> 8) & 0xff,56 address & 0xff,57 ]);58 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));59}6061export function createEthAccount(web3: Web3) {62 const account = web3.eth.accounts.create();63 web3.eth.accounts.wallet.add(account.privateKey);64 return account.address;65}6667export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {68 const alice = privateKey('//Alice');69 const account = createEthAccount(web3);70 await transferBalanceToEth(api, alice, account);7172 return account;73}7475export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 999999999999999) {76 const tx = api.tx.balances.transfer(evmToAddress(target), amount);77 const events = await submitTransactionAsync(source, tx);78 const result = getGenericResult(events);79 expect(result.success).to.be.true;80}8182export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {83 let i: any = it;84 if (opts.only) i = i.only;85 else if (opts.skip) i = i.skip;86 i(name, async () => {87 await usingApi(async api => {88 await usingWeb3(async web3 => {89 await cb({ api, web3 });90 });91 });92 });93}94itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { only: true });95itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { skip: true });9697export async function generateSubstrateEthPair(web3: Web3) {98 const account = web3.eth.accounts.create();99 evmToAddress(account.address);100}101102type NormalizedEvent = {103 address: string,104 event: string,105 args: { [key: string]: string }106};107108export function normalizeEvents(events: any): NormalizedEvent[] {109 const output = [];110 for (const key of Object.keys(events)) {111 if (key.match(/^[0-9]+$/)) {112 output.push(events[key]);113 } else if (Array.isArray(events[key])) {114 output.push(...events[key]);115 } else {116 output.push(events[key]);117 }118 }119 output.sort((a, b) => a.logIndex - b.logIndex);120 return output.map(({ address, event, returnValues }) => {121 const args: { [key: string]: string } = {};122 for (const key of Object.keys(returnValues)) {123 if (!key.match(/^[0-9]+$/)) {124 args[key] = returnValues[key];125 }126 }127 return {128 address,129 event,130 args,131 };132 });133}134135export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {136 const out: any = [];137 contract.events.allEvents((_: any, event: any) => {138 out.push(event);139 });140 await action();141 return normalizeEvents(out);142}143144export function subToEth(eth: string): string {145 const bytes = addressToEvm(eth);146 const string = '0x' + Buffer.from(bytes).toString('hex');147 return Web3.utils.toChecksumAddress(string);148}149150export function compileContract(name: string, src: string) {151 const out = JSON.parse(solc.compile(JSON.stringify({152 language: 'Solidity',153 sources: {154 [`${name}.sol`]: {155 content: `156 // SPDX-License-Identifier: UNLICENSED157 pragma solidity ^0.8.6;158159 ${src}160 `,161 },162 },163 settings: {164 outputSelection: {165 '*': {166 '*': ['*'],167 },168 },169 },170 }))).contracts[`${name}.sol`][name];171172 return {173 abi: out.abi,174 object: '0x' + out.evm.bytecode.object,175 };176}177178// export async function deployFungibleContract(web3: Web3 & Web3HttpMarker, deployer: string) {179180// const sol = fs.readFileSync(__dirname + '/ERC721.sol').toString();181182// const compiled = compileContract('ERC721', sol);183// const ERC721 = new web3.eth.Contract(compiled.abi, undefined, {184// data: compiled.object,185// from: deployer,186// ...GAS_ARGS,187// });188// const fungible = await ERC721.deploy({ data: compiled.object }).send({from: deployer});189190// return fungible;191// }192193export async function deployFlipper(web3: Web3 & Web3HttpMarker, deployer: string) {194 const compiled = compileContract('Flipper', `195 contract Flipper {196 bool value = false;197 function flip() public {198 value = !value;199 }200 function getValue() public view returns (bool) {201 return value;202 }203 }204 `);205 const Flipper = new web3.eth.Contract(compiled.abi, undefined, {206 data: compiled.object,207 from: deployer,208 ...GAS_ARGS,209 });210 const flipper = await Flipper.deploy({ data: compiled.object }).send({from: deployer});211212 return flipper;213}214215export async function deployCollector(web3: Web3 & Web3HttpMarker, deployer: string) {216 const compiled = compileContract('Collector', `217 contract Collector {218 uint256 collected;219 function giveMoney() public payable {220 collected += msg.value;221 }222 function getCollected() public view returns (uint256) {223 return collected;224 }225 }226 `);227 const Collector = new web3.eth.Contract(compiled.abi, undefined, {228 data: compiled.object,229 from: deployer,230 ...GAS_ARGS,231 });232 const collector = await Collector.deploy({ data: compiled.object }).send({ from: deployer });233234 return collector;235}236237export function contractHelpers(web3: Web3, caller: string) {238 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});239}