difftreelog
chore refactor RFT token tests
in: master
3 files changed
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -15,8 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {createCollectionExpectSuccess, UNIQUE} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, tokenIdToAddress} from './util/helpers';
-import reFungibleTokenAbi from './reFungibleTokenAbi.json';
+import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, tokenIdToAddress, uniqueRefungibleToken} from './util/helpers';
import {expect} from 'chai';
describe('Refungible: Information getting', () => {
@@ -84,7 +83,7 @@
await contract.methods.mint(caller, tokenId).send();
const tokenAddress = tokenIdToAddress(collectionId, tokenId);
- const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+ const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
await tokenContract.methods.repartition(2).send();
await tokenContract.methods.transfer(receiver, 1).send();
@@ -108,7 +107,7 @@
await contract.methods.mint(caller, tokenId).send();
const tokenAddress = tokenIdToAddress(collectionId, tokenId);
- const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+ const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
await tokenContract.methods.repartition(2).send();
await tokenContract.methods.transfer(receiver, 1).send();
@@ -250,7 +249,7 @@
await contract.methods.mint(caller, tokenId).send();
const address = tokenIdToAddress(collectionId, tokenId);
- const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+ const tokenContract = uniqueRefungibleToken(web3, address, caller);
await tokenContract.methods.repartition(15).send();
{
@@ -345,7 +344,7 @@
await contract.methods.mint(caller, tokenId).send();
const tokenAddress = tokenIdToAddress(collectionId, tokenId);
- const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+ const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
await tokenContract.methods.repartition(2).send();
await tokenContract.methods.transfer(receiver, 1).send();
@@ -377,7 +376,7 @@
await contract.methods.mint(caller, tokenId).send();
const tokenAddress = tokenIdToAddress(collectionId, tokenId);
- const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+ const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
await tokenContract.methods.repartition(2).send();
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -15,8 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE} from '../util/helpers';
-import {collectionIdFromAddress, collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
-import reFungibleTokenAbi from './reFungibleTokenAbi.json';
+import {collectionIdFromAddress, collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
@@ -34,7 +33,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, caller);
const totalSupply = await contract.methods.totalSupply().call();
expect(totalSupply).to.equal('200');
@@ -50,7 +49,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, caller);
const balance = await contract.methods.balanceOf(caller).call();
expect(balance).to.equal('200');
@@ -66,7 +65,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, caller);
const decimals = await contract.methods.decimals().call();
expect(decimals).to.equal('0');
@@ -229,7 +228,7 @@
const spender = createEthAccount(web3);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, owner);
{
const result = await contract.methods.approve(spender, 100).send({from: owner});
@@ -270,7 +269,7 @@
const receiver = createEthAccount(web3);
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, owner);
await contract.methods.approve(spender, 100).send();
@@ -324,7 +323,7 @@
await transferBalanceToEth(api, alice, receiver);
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, owner);
{
const result = await contract.methods.transfer(receiver, 50).send({from: owner});
@@ -367,7 +366,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, owner);
await contract.methods.repartition(200).send({from: owner});
expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(200);
@@ -397,7 +396,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, owner);
const result = await contract.methods.repartition(200).send();
const events = normalizeEvents(result.events);
@@ -426,7 +425,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, owner);
const result = await contract.methods.repartition(50).send();
const events = normalizeEvents(result.events);
@@ -456,7 +455,7 @@
const address = tokenIdToAddress(collectionId, tokenId);
- const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+ const tokenContract = uniqueRefungibleToken(web3, address, caller);
await tokenContract.methods.repartition(2).send();
await tokenContract.methods.transfer(receiver, 1).send();
@@ -488,7 +487,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, owner);
const cost = await recordEthFee(api, owner, () => contract.methods.approve(spender, 100).send({from: owner}));
expect(cost < BigInt(0.2 * Number(UNIQUE)));
@@ -505,7 +504,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, owner);
await contract.methods.approve(spender, 100).send({from: owner});
@@ -524,7 +523,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+ const contract = uniqueRefungibleToken(web3, address, owner);
const cost = await recordEthFee(api, owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));
expect(cost < BigInt(0.2 * Number(UNIQUE)));
@@ -542,7 +541,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n)).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address);
+ const contract = uniqueRefungibleToken(web3, address);
const events = await recordEvents(contract, async () => {
expect(await approve(api, collectionId, tokenId, alice, {Ethereum: receiver}, 100n)).to.be.true;
@@ -573,7 +572,7 @@
expect(await approve(api, collectionId, tokenId, alice, bob.address, 100n)).to.be.true;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address);
+ const contract = uniqueRefungibleToken(web3, address);
const events = await recordEvents(contract, async () => {
expect(await transferFrom(api, collectionId, tokenId, bob, alice, {Ethereum: receiver}, 51n)).to.be.true;
@@ -611,7 +610,7 @@
const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n)).itemId;
const address = tokenIdToAddress(collectionId, tokenId);
- const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address);
+ const contract = uniqueRefungibleToken(web3, address);
const events = await recordEvents(contract, async () => {
expect(await transfer(api, collectionId, tokenId, alice, {Ethereum: receiver}, 51n)).to.be.true;
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 {IKeyringPair} from '@polkadot/types/types';22import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';23import {expect} from 'chai';24import * as solc from 'solc';25import Web3 from 'web3';26import config from '../../config';27import getBalance from '../../substrate/get-balance';28import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';29import waitNewBlocks from '../../substrate/wait-new-blocks';30import {CollectionMode, CrossAccountId, getDetailedCollectionInfo, getGenericResult, UNIQUE} from '../../util/helpers';31import collectionHelpersAbi from '../collectionHelpersAbi.json';32import fungibleAbi from '../fungibleAbi.json';33import nonFungibleAbi from '../nonFungibleAbi.json';34import refungibleAbi from '../reFungibleAbi.json';35import refungibleTokenAbi from '../reFungibleTokenAbi.json';36import contractHelpersAbi from './contractHelpersAbi.json';3738export const GAS_ARGS = {gas: 2500000};3940export enum SponsoringMode {41 Disabled = 0,42 Allowlisted = 1,43 Generous = 2,44}4546let web3Connected = false;47export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {48 if (web3Connected) throw new Error('do not nest usingWeb3 calls');49 web3Connected = true;5051 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);52 const web3 = new Web3(provider);5354 try {55 return await cb(web3);56 } finally {57 // provider.disconnect(3000, 'normal disconnect');58 provider.connection.close();59 web3Connected = false;60 }61}6263function encodeIntBE(v: number): number[] {64 if (v >= 0xffffffff || v < 0) throw new Error('id overflow');65 return [66 v >> 24,67 (v >> 16) & 0xff,68 (v >> 8) & 0xff,69 v & 0xff,70 ];71}7273export async function getCollectionAddressFromResult(api: ApiPromise, result: any) {74 const collectionIdAddress = normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);75 const collectionId = collectionIdFromAddress(collectionIdAddress); 76 const collection = (await getDetailedCollectionInfo(api, collectionId))!;77 return {collectionIdAddress, collectionId, collection};78}7980export function collectionIdToAddress(collection: number): string {81 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,82 ...encodeIntBE(collection),83 ]);84 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));85}86export function collectionIdFromAddress(address: string): number {87 if (!address.startsWith('0x'))88 throw 'address not starts with "0x"';89 if (address.length > 42)90 throw 'address length is more than 20 bytes';91 return Number('0x' + address.substring(address.length - 8));92}93 94export function normalizeAddress(address: string): string {95 return '0x' + address.substring(address.length - 40);96}9798export function tokenIdToAddress(collection: number, token: number): string {99 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,100 ...encodeIntBE(collection),101 ...encodeIntBE(token),102 ]);103 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));104}105106export function tokenIdFromAddress(address: string) {107 if (!address.startsWith('0x'))108 throw 'address not starts with "0x"';109 if (address.length > 42)110 throw 'address length is more than 20 bytes';111 return {112 collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),113 tokenId: Number('0x' + address.substring(address.length - 8)),114 };115}116117export function tokenIdToCross(collection: number, token: number): CrossAccountId {118 return {119 Ethereum: tokenIdToAddress(collection, token),120 };121}122123export function createEthAccount(web3: Web3) {124 const account = web3.eth.accounts.create();125 web3.eth.accounts.wallet.add(account.privateKey);126 return account.address;127}128129export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair) {130 const alice = privateKeyWrapper('//Alice');131 const account = createEthAccount(web3);132 await transferBalanceToEth(api, alice, account);133134 return account;135}136137export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {138 const tx = api.tx.balances.transfer(evmToAddress(target), amount);139 const events = await submitTransactionAsync(source, tx);140 const result = getGenericResult(events);141 expect(result.success).to.be.true;142}143144export async function createRefungibleCollection(api: ApiPromise, web3: Web3, owner: string) {145 const collectionHelper = evmCollectionHelpers(web3, owner);146 const result = await collectionHelper.methods147 .createRefungibleCollection('A', 'B', 'C')148 .send();149 return await getCollectionAddressFromResult(api, result);150}151152153export async function createNonfungibleCollection(api: ApiPromise, web3: Web3, owner: string) {154 const collectionHelper = evmCollectionHelpers(web3, owner);155 const result = await collectionHelper.methods156 .createNonfungibleCollection('A', 'B', 'C')157 .send();158 return await getCollectionAddressFromResult(api, result);159}160161export function uniqueNFT(web3: Web3, address: string, owner: string) {162 return new web3.eth.Contract(nonFungibleAbi as any, address, {163 from: owner,164 ...GAS_ARGS,165 });166}167168export function uniqueRefungible(web3: Web3, collectionAddress: string, owner: string) {169 return new web3.eth.Contract(refungibleAbi as any, collectionAddress, {170 from: owner,171 ...GAS_ARGS,172 });173}174175export function uniqueRefungibleToken(web3: Web3, tokenAddress: string, owner: string) {176 return new web3.eth.Contract(refungibleTokenAbi as any, tokenAddress, {177 from: owner,178 ...GAS_ARGS,179 });180}181182export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {183 let i: any = it;184 if (opts.only) i = i.only;185 else if (opts.skip) i = i.skip;186 i(name, async () => {187 await usingApi(async (api, privateKeyWrapper) => {188 await usingWeb3(async web3 => {189 await cb({api, web3, privateKeyWrapper});190 });191 });192 });193}194itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {only: true});195itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {skip: true});196197export async function generateSubstrateEthPair(web3: Web3) {198 const account = web3.eth.accounts.create();199 evmToAddress(account.address);200}201202type NormalizedEvent = {203 address: string,204 event: string,205 args: { [key: string]: string }206};207208export function normalizeEvents(events: any): NormalizedEvent[] {209 const output = [];210 for (const key of Object.keys(events)) {211 if (key.match(/^[0-9]+$/)) {212 output.push(events[key]);213 } else if (Array.isArray(events[key])) {214 output.push(...events[key]);215 } else {216 output.push(events[key]);217 }218 }219 output.sort((a, b) => a.logIndex - b.logIndex);220 return output.map(({address, event, returnValues}) => {221 const args: { [key: string]: string } = {};222 for (const key of Object.keys(returnValues)) {223 if (!key.match(/^[0-9]+$/)) {224 args[key] = returnValues[key];225 }226 }227 return {228 address,229 event,230 args,231 };232 });233}234235export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {236 const out: any = [];237 contract.events.allEvents((_: any, event: any) => {238 out.push(event);239 });240 await action();241 return normalizeEvents(out);242}243244export function subToEthLowercase(eth: string): string {245 const bytes = addressToEvm(eth);246 return '0x' + Buffer.from(bytes).toString('hex');247}248249export function subToEth(eth: string): string {250 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));251}252253export function compileContract(name: string, src: string) {254 const out = JSON.parse(solc.compile(JSON.stringify({255 language: 'Solidity',256 sources: {257 [`${name}.sol`]: {258 content: `259 // SPDX-License-Identifier: UNLICENSED260 pragma solidity ^0.8.6;261262 ${src}263 `,264 },265 },266 settings: {267 outputSelection: {268 '*': {269 '*': ['*'],270 },271 },272 },273 }))).contracts[`${name}.sol`][name];274275 return {276 abi: out.abi,277 object: '0x' + out.evm.bytecode.object,278 };279}280281export async function deployFlipper(web3: Web3, deployer: string) {282 const compiled = compileContract('Flipper', `283 contract Flipper {284 bool value = false;285 function flip() public {286 value = !value;287 }288 function getValue() public view returns (bool) {289 return value;290 }291 }292 `);293 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {294 data: compiled.object,295 from: deployer,296 ...GAS_ARGS,297 });298 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});299300 return flipper;301}302303export async function deployCollector(web3: Web3, deployer: string) {304 const compiled = compileContract('Collector', `305 contract Collector {306 uint256 collected;307 fallback() external payable {308 giveMoney();309 }310 function giveMoney() public payable {311 collected += msg.value;312 }313 function getCollected() public view returns (uint256) {314 return collected;315 }316 function getUnaccounted() public view returns (uint256) {317 return address(this).balance - collected;318 }319320 function withdraw(address payable target) public {321 target.transfer(collected);322 collected = 0;323 }324 }325 `);326 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {327 data: compiled.object,328 from: deployer,329 ...GAS_ARGS,330 });331 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});332333 return collector;334}335336/** 337 * pallet evm_contract_helpers338 * @param web3 339 * @param caller - eth address340 * @returns 341 */342export function contractHelpers(web3: Web3, caller: string) {343 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});344}345346/** 347 * evm collection helper348 * @param web3 349 * @param caller - eth address350 * @returns 351 */352export function evmCollectionHelpers(web3: Web3, caller: string) {353 return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});354}355356/** 357 * evm collection358 * @param web3 359 * @param caller - eth address360 * @returns 361 */362export function evmCollection(web3: Web3, caller: string, collection: string, mode: CollectionMode = {type: 'NFT'}) {363 let abi;364 switch (mode.type) {365 case 'Fungible':366 abi = fungibleAbi;367 break;368 369 case 'NFT':370 abi = nonFungibleAbi;371 break;372 373 case 'ReFungible':374 abi = refungibleAbi;375 break;376377 default:378 throw 'Bad collection mode';379 }380 const contract = new web3.eth.Contract(abi as any, collection, {from: caller, ...GAS_ARGS});381 return contract;382}383384/**385 * Execute ethereum method call using substrate account386 * @param to target contract387 * @param mkTx - closure, receiving `contract.methods`, and returning method call,388 * to be used as following (assuming `to` = erc20 contract):389 * `m => m.transfer(to, amount)`390 *391 * # Example392 * ```ts393 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));394 * ```395 */396export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {397 const tx = api.tx.evm.call(398 subToEth(from.address),399 to.options.address,400 mkTx(to.methods).encodeABI(),401 value,402 GAS_ARGS.gas,403 await web3.eth.getGasPrice(),404 null,405 null,406 [],407 );408 const events = await submitTransactionAsync(from, tx);409 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;410}411412export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {413 return (await getBalance(api, [evmToAddress(address)]))[0];414}415416/**417 * Measure how much gas given closure consumes418 *419 * @param user which user balance will be checked420 */421export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {422 const before = await ethBalanceViaSub(api, user);423424 await call();425426 // In dev mode, the transaction might not finish processing in time427 await waitNewBlocks(api, 1);428 const after = await ethBalanceViaSub(api, user);429430 // Can't use .to.be.less, because chai doesn't supports bigint431 expect(after < before).to.be.true;432433 return before - after;434}435436type ElementOf<A> = A extends readonly (infer T)[] ? T : never;437// I want a fancier api, not a memory efficiency438export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {439 if(args.length === 0) {440 yield internalRest as any;441 return;442 }443 for(const value of args[0]) {444 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;445 }446}1// 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 {IKeyringPair} from '@polkadot/types/types';22import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';23import {expect} from 'chai';24import * as solc from 'solc';25import Web3 from 'web3';26import config from '../../config';27import getBalance from '../../substrate/get-balance';28import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';29import waitNewBlocks from '../../substrate/wait-new-blocks';30import {CollectionMode, CrossAccountId, getDetailedCollectionInfo, getGenericResult, UNIQUE} from '../../util/helpers';31import collectionHelpersAbi from '../collectionHelpersAbi.json';32import fungibleAbi from '../fungibleAbi.json';33import nonFungibleAbi from '../nonFungibleAbi.json';34import refungibleAbi from '../reFungibleAbi.json';35import refungibleTokenAbi from '../reFungibleTokenAbi.json';36import contractHelpersAbi from './contractHelpersAbi.json';3738export const GAS_ARGS = {gas: 2500000};3940export enum SponsoringMode {41 Disabled = 0,42 Allowlisted = 1,43 Generous = 2,44}4546let web3Connected = false;47export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {48 if (web3Connected) throw new Error('do not nest usingWeb3 calls');49 web3Connected = true;5051 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);52 const web3 = new Web3(provider);5354 try {55 return await cb(web3);56 } finally {57 // provider.disconnect(3000, 'normal disconnect');58 provider.connection.close();59 web3Connected = false;60 }61}6263function encodeIntBE(v: number): number[] {64 if (v >= 0xffffffff || v < 0) throw new Error('id overflow');65 return [66 v >> 24,67 (v >> 16) & 0xff,68 (v >> 8) & 0xff,69 v & 0xff,70 ];71}7273export async function getCollectionAddressFromResult(api: ApiPromise, result: any) {74 const collectionIdAddress = normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);75 const collectionId = collectionIdFromAddress(collectionIdAddress); 76 const collection = (await getDetailedCollectionInfo(api, collectionId))!;77 return {collectionIdAddress, collectionId, collection};78}7980export function collectionIdToAddress(collection: number): string {81 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,82 ...encodeIntBE(collection),83 ]);84 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));85}86export function collectionIdFromAddress(address: string): number {87 if (!address.startsWith('0x'))88 throw 'address not starts with "0x"';89 if (address.length > 42)90 throw 'address length is more than 20 bytes';91 return Number('0x' + address.substring(address.length - 8));92}93 94export function normalizeAddress(address: string): string {95 return '0x' + address.substring(address.length - 40);96}9798export function tokenIdToAddress(collection: number, token: number): string {99 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,100 ...encodeIntBE(collection),101 ...encodeIntBE(token),102 ]);103 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));104}105106export function tokenIdFromAddress(address: string) {107 if (!address.startsWith('0x'))108 throw 'address not starts with "0x"';109 if (address.length > 42)110 throw 'address length is more than 20 bytes';111 return {112 collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),113 tokenId: Number('0x' + address.substring(address.length - 8)),114 };115}116117export function tokenIdToCross(collection: number, token: number): CrossAccountId {118 return {119 Ethereum: tokenIdToAddress(collection, token),120 };121}122123export function createEthAccount(web3: Web3) {124 const account = web3.eth.accounts.create();125 web3.eth.accounts.wallet.add(account.privateKey);126 return account.address;127}128129export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair) {130 const alice = privateKeyWrapper('//Alice');131 const account = createEthAccount(web3);132 await transferBalanceToEth(api, alice, account);133134 return account;135}136137export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {138 const tx = api.tx.balances.transfer(evmToAddress(target), amount);139 const events = await submitTransactionAsync(source, tx);140 const result = getGenericResult(events);141 expect(result.success).to.be.true;142}143144export async function createRefungibleCollection(api: ApiPromise, web3: Web3, owner: string) {145 const collectionHelper = evmCollectionHelpers(web3, owner);146 const result = await collectionHelper.methods147 .createRefungibleCollection('A', 'B', 'C')148 .send();149 return await getCollectionAddressFromResult(api, result);150}151152153export async function createNonfungibleCollection(api: ApiPromise, web3: Web3, owner: string) {154 const collectionHelper = evmCollectionHelpers(web3, owner);155 const result = await collectionHelper.methods156 .createNonfungibleCollection('A', 'B', 'C')157 .send();158 return await getCollectionAddressFromResult(api, result);159}160161export function uniqueNFT(web3: Web3, address: string, owner: string) {162 return new web3.eth.Contract(nonFungibleAbi as any, address, {163 from: owner,164 ...GAS_ARGS,165 });166}167168export function uniqueRefungible(web3: Web3, collectionAddress: string, owner: string) {169 return new web3.eth.Contract(refungibleAbi as any, collectionAddress, {170 from: owner,171 ...GAS_ARGS,172 });173}174175export function uniqueRefungibleToken(web3: Web3, tokenAddress: string, owner: string | undefined = undefined) {176 return new web3.eth.Contract(refungibleTokenAbi as any, tokenAddress, {177 from: owner,178 ...GAS_ARGS,179 });180}181182export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {183 let i: any = it;184 if (opts.only) i = i.only;185 else if (opts.skip) i = i.skip;186 i(name, async () => {187 await usingApi(async (api, privateKeyWrapper) => {188 await usingWeb3(async web3 => {189 await cb({api, web3, privateKeyWrapper});190 });191 });192 });193}194itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {only: true});195itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itWeb3(name, cb, {skip: true});196197export async function generateSubstrateEthPair(web3: Web3) {198 const account = web3.eth.accounts.create();199 evmToAddress(account.address);200}201202type NormalizedEvent = {203 address: string,204 event: string,205 args: { [key: string]: string }206};207208export function normalizeEvents(events: any): NormalizedEvent[] {209 const output = [];210 for (const key of Object.keys(events)) {211 if (key.match(/^[0-9]+$/)) {212 output.push(events[key]);213 } else if (Array.isArray(events[key])) {214 output.push(...events[key]);215 } else {216 output.push(events[key]);217 }218 }219 output.sort((a, b) => a.logIndex - b.logIndex);220 return output.map(({address, event, returnValues}) => {221 const args: { [key: string]: string } = {};222 for (const key of Object.keys(returnValues)) {223 if (!key.match(/^[0-9]+$/)) {224 args[key] = returnValues[key];225 }226 }227 return {228 address,229 event,230 args,231 };232 });233}234235export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {236 const out: any = [];237 contract.events.allEvents((_: any, event: any) => {238 out.push(event);239 });240 await action();241 return normalizeEvents(out);242}243244export function subToEthLowercase(eth: string): string {245 const bytes = addressToEvm(eth);246 return '0x' + Buffer.from(bytes).toString('hex');247}248249export function subToEth(eth: string): string {250 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));251}252253export function compileContract(name: string, src: string) {254 const out = JSON.parse(solc.compile(JSON.stringify({255 language: 'Solidity',256 sources: {257 [`${name}.sol`]: {258 content: `259 // SPDX-License-Identifier: UNLICENSED260 pragma solidity ^0.8.6;261262 ${src}263 `,264 },265 },266 settings: {267 outputSelection: {268 '*': {269 '*': ['*'],270 },271 },272 },273 }))).contracts[`${name}.sol`][name];274275 return {276 abi: out.abi,277 object: '0x' + out.evm.bytecode.object,278 };279}280281export async function deployFlipper(web3: Web3, deployer: string) {282 const compiled = compileContract('Flipper', `283 contract Flipper {284 bool value = false;285 function flip() public {286 value = !value;287 }288 function getValue() public view returns (bool) {289 return value;290 }291 }292 `);293 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {294 data: compiled.object,295 from: deployer,296 ...GAS_ARGS,297 });298 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});299300 return flipper;301}302303export async function deployCollector(web3: Web3, deployer: string) {304 const compiled = compileContract('Collector', `305 contract Collector {306 uint256 collected;307 fallback() external payable {308 giveMoney();309 }310 function giveMoney() public payable {311 collected += msg.value;312 }313 function getCollected() public view returns (uint256) {314 return collected;315 }316 function getUnaccounted() public view returns (uint256) {317 return address(this).balance - collected;318 }319320 function withdraw(address payable target) public {321 target.transfer(collected);322 collected = 0;323 }324 }325 `);326 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {327 data: compiled.object,328 from: deployer,329 ...GAS_ARGS,330 });331 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});332333 return collector;334}335336/** 337 * pallet evm_contract_helpers338 * @param web3 339 * @param caller - eth address340 * @returns 341 */342export function contractHelpers(web3: Web3, caller: string) {343 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});344}345346/** 347 * evm collection helper348 * @param web3 349 * @param caller - eth address350 * @returns 351 */352export function evmCollectionHelpers(web3: Web3, caller: string) {353 return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});354}355356/** 357 * evm collection358 * @param web3 359 * @param caller - eth address360 * @returns 361 */362export function evmCollection(web3: Web3, caller: string, collection: string, mode: CollectionMode = {type: 'NFT'}) {363 let abi;364 switch (mode.type) {365 case 'Fungible':366 abi = fungibleAbi;367 break;368 369 case 'NFT':370 abi = nonFungibleAbi;371 break;372 373 case 'ReFungible':374 abi = refungibleAbi;375 break;376377 default:378 throw 'Bad collection mode';379 }380 const contract = new web3.eth.Contract(abi as any, collection, {from: caller, ...GAS_ARGS});381 return contract;382}383384/**385 * Execute ethereum method call using substrate account386 * @param to target contract387 * @param mkTx - closure, receiving `contract.methods`, and returning method call,388 * to be used as following (assuming `to` = erc20 contract):389 * `m => m.transfer(to, amount)`390 *391 * # Example392 * ```ts393 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));394 * ```395 */396export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {397 const tx = api.tx.evm.call(398 subToEth(from.address),399 to.options.address,400 mkTx(to.methods).encodeABI(),401 value,402 GAS_ARGS.gas,403 await web3.eth.getGasPrice(),404 null,405 null,406 [],407 );408 const events = await submitTransactionAsync(from, tx);409 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;410}411412export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {413 return (await getBalance(api, [evmToAddress(address)]))[0];414}415416/**417 * Measure how much gas given closure consumes418 *419 * @param user which user balance will be checked420 */421export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {422 const before = await ethBalanceViaSub(api, user);423424 await call();425426 // In dev mode, the transaction might not finish processing in time427 await waitNewBlocks(api, 1);428 const after = await ethBalanceViaSub(api, user);429430 // Can't use .to.be.less, because chai doesn't supports bigint431 expect(after < before).to.be.true;432433 return before - after;434}435436type ElementOf<A> = A extends readonly (infer T)[] ? T : never;437// I want a fancier api, not a memory efficiency438export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {439 if(args.length === 0) {440 yield internalRest as any;441 return;442 }443 for(const value of args[0]) {444 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;445 }446}