difftreelog
tests(dev-mode): all fixed up
in: master
4 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -212,6 +212,16 @@
vec![
get_account_id_from_seed::<sr25519::Public>("Alice"),
get_account_id_from_seed::<sr25519::Public>("Bob"),
+ get_account_id_from_seed::<sr25519::Public>("Charlie"),
+ get_account_id_from_seed::<sr25519::Public>("Dave"),
+ get_account_id_from_seed::<sr25519::Public>("Eve"),
+ get_account_id_from_seed::<sr25519::Public>("Ferdie"),
+ get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
+ get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
+ get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
+ get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
+ get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
+ get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
],
1000
)
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -34,7 +34,8 @@
const userB = createEthAccount(web3);
const cost = await recordEthFee(api, userA, () => web3.eth.sendTransaction({from: userA, to: userB, value: '1000000', ...GAS_ARGS}));
- expect(cost - await ethBalanceViaSub(api, userB) < BigInt(0.2 * Number(UNIQUE))).to.be.true;
+ const balanceB = await ethBalanceViaSub(api, userB);
+ expect(cost - balanceB < BigInt(0.2 * Number(UNIQUE))).to.be.true;
});
itWeb3('NFT transfer is close to 0.15 UNQ', async ({web3, api}) => {
tests/src/eth/util/helpers.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// eslint-disable-next-line @typescript-eslint/triple-slash-reference18/// <reference path="helpers.d.ts" />1920import {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 {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 getBalance from '../../substrate/get-balance';32import waitNewBlocks from '../../substrate/wait-new-blocks';3334export const GAS_ARGS = {gas: 2500000};3536export enum SponsoringMode {37 Disabled = 0,38 Allowlisted = 1,39 Generous = 2,40}4142let web3Connected = false;43export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {44 if (web3Connected) throw new Error('do not nest usingWeb3 calls');45 web3Connected = true;4647 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);48 const web3 = new Web3(provider);4950 try {51 return await cb(web3);52 } finally {53 // provider.disconnect(3000, 'normal disconnect');54 provider.connection.close();55 web3Connected = false;56 }57}5859export function collectionIdToAddress(address: number): string {60 if (address >= 0xffffffff || address < 0) throw new Error('id overflow');61 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,62 address >> 24,63 (address >> 16) & 0xff,64 (address >> 8) & 0xff,65 address & 0xff,66 ]);67 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));68}6970export function createEthAccount(web3: Web3) {71 const account = web3.eth.accounts.create();72 web3.eth.accounts.wallet.add(account.privateKey);73 return account.address;74}7576export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {77 const alice = privateKey('//Alice');78 const account = createEthAccount(web3);79 await transferBalanceToEth(api, alice, account);8081 return account;82}8384export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {85 const tx = api.tx.balances.transfer(evmToAddress(target), amount);86 const events = await submitTransactionAsync(source, tx);87 const result = getGenericResult(events);88 expect(result.success).to.be.true;89}9091export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {92 let i: any = it;93 if (opts.only) i = i.only;94 else if (opts.skip) i = i.skip;95 i(name, async () => {96 await usingApi(async api => {97 await usingWeb3(async web3 => {98 await cb({api, web3});99 });100 });101 });102}103itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});104itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});105106export async function generateSubstrateEthPair(web3: Web3) {107 const account = web3.eth.accounts.create();108 evmToAddress(account.address);109}110111type NormalizedEvent = {112 address: string,113 event: string,114 args: { [key: string]: string }115};116117export function normalizeEvents(events: any): NormalizedEvent[] {118 const output = [];119 for (const key of Object.keys(events)) {120 if (key.match(/^[0-9]+$/)) {121 output.push(events[key]);122 } else if (Array.isArray(events[key])) {123 output.push(...events[key]);124 } else {125 output.push(events[key]);126 }127 }128 output.sort((a, b) => a.logIndex - b.logIndex);129 return output.map(({address, event, returnValues}) => {130 const args: { [key: string]: string } = {};131 for (const key of Object.keys(returnValues)) {132 if (!key.match(/^[0-9]+$/)) {133 args[key] = returnValues[key];134 }135 }136 return {137 address,138 event,139 args,140 };141 });142}143144export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {145 const out: any = [];146 contract.events.allEvents((_: any, event: any) => {147 out.push(event);148 });149 await action();150 return normalizeEvents(out);151}152153export function subToEthLowercase(eth: string): string {154 const bytes = addressToEvm(eth);155 return '0x' + Buffer.from(bytes).toString('hex');156}157158export function subToEth(eth: string): string {159 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));160}161162export function compileContract(name: string, src: string) {163 const out = JSON.parse(solc.compile(JSON.stringify({164 language: 'Solidity',165 sources: {166 [`${name}.sol`]: {167 content: `168 // SPDX-License-Identifier: UNLICENSED169 pragma solidity ^0.8.6;170171 ${src}172 `,173 },174 },175 settings: {176 outputSelection: {177 '*': {178 '*': ['*'],179 },180 },181 },182 }))).contracts[`${name}.sol`][name];183184 return {185 abi: out.abi,186 object: '0x' + out.evm.bytecode.object,187 };188}189190export async function deployFlipper(web3: Web3, deployer: string) {191 const compiled = compileContract('Flipper', `192 contract Flipper {193 bool value = false;194 function flip() public {195 value = !value;196 }197 function getValue() public view returns (bool) {198 return value;199 }200 }201 `);202 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {203 data: compiled.object,204 from: deployer,205 ...GAS_ARGS,206 });207 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});208209 return flipper;210}211212export async function deployCollector(web3: Web3, deployer: string) {213 const compiled = compileContract('Collector', `214 contract Collector {215 uint256 collected;216 fallback() external payable {217 giveMoney();218 }219 function giveMoney() public payable {220 collected += msg.value;221 }222 function getCollected() public view returns (uint256) {223 return collected;224 }225 function getUnaccounted() public view returns (uint256) {226 return address(this).balance - collected;227 }228229 function withdraw(address payable target) public {230 target.transfer(collected);231 collected = 0;232 }233 }234 `);235 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {236 data: compiled.object,237 from: deployer,238 ...GAS_ARGS,239 });240 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});241242 return collector;243}244245export function contractHelpers(web3: Web3, caller: string) {246 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});247}248249/**250 * Execute ethereum method call using substrate account251 * @param to target contract252 * @param mkTx - closure, receiving `contract.methods`, and returning method call,253 * to be used as following (assuming `to` = erc20 contract):254 * `m => m.transfer(to, amount)`255 *256 * # Example257 * ```ts258 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));259 * ```260 */261export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {262 const tx = api.tx.evm.call(263 subToEth(from.address),264 to.options.address,265 mkTx(to.methods).encodeABI(),266 value,267 GAS_ARGS.gas,268 await web3.eth.getGasPrice(),269 null,270 null,271 [],272 );273 const events = await submitTransactionAsync(from, tx);274 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;275}276277export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {278 return (await getBalance(api, [evmToAddress(address)]))[0];279}280281/**282 * Measure how much gas given closure consumes283 *284 * @param user which user balance will be checked285 */286export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {287 const before = await ethBalanceViaSub(api, user);288289 await call();290291 // In dev mode, the transaction might not finish processing in time292 await waitNewBlocks(api, 1);293 const after = await ethBalanceViaSub(api, user);294295 // Can't use .to.be.less, because chai doesn't supports bigint296 expect(after < before).to.be.true;297298 return before - after;299}tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -344,15 +344,12 @@
// Run the CreateCollection transaction
const alicePrivateKey = privateKey('//Alice');
const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
- const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
- const result = getCreateCollectionResult(events);
+ await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
// Get number of collections after the transaction
const collectionCountAfter = await getCreatedCollectionCount(api);
// What to expect
- // tslint:disable-next-line:no-unused-expression
- expect(result.success).to.be.false;
expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');
});
}