difftreelog
test evm token properties
in: master
3 files changed
tests/src/eth/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -49,7 +49,6 @@
const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
const value = await contract.methods.collectionProperty('testKey').call();
-
expect(value).to.equal(web3.utils.toHex('testValue'));
});
});
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -0,0 +1,95 @@
+import privateKey from '../substrate/privateKey';
+import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess} from '../util/helpers';
+import {cartesian, collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3} from './util/helpers';
+import nonFungibleAbi from './nonFungibleAbi.json';
+import {expect} from 'chai';
+import {executeTransaction} from '../substrate/substrate-api';
+
+describe('EVM token properties', () => {
+ itWeb3('Can be reconfigured', async({web3, api}) => {
+ const alice = privateKey('//Alice');
+ const caller = await createEthAccountWithBalance(api, web3);
+ for(const [mutable,collectionAdmin, tokenOwner] of cartesian([], [false, true], [false, true], [false, true])) {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await addCollectionAdminExpectSuccess(alice, collection, {Ethereum: caller});
+
+ const address = collectionIdToAddress(collection);
+ const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+
+ await contract.methods.setTokenPropertyPermission('testKey', mutable, collectionAdmin, tokenOwner).send({from: caller});
+
+ const state = (await api.query.common.collectionPropertyPermissions(collection)).toJSON();
+ expect(state).to.be.deep.equal({
+ [web3.utils.toHex('testKey')]: {mutable, collectionAdmin, tokenOwner},
+ });
+ }
+ });
+ itWeb3('Can be set', async({web3, api}) => {
+ const alice = privateKey('//Alice');
+ const caller = await createEthAccountWithBalance(api, web3);
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const token = await createItemExpectSuccess(alice, collection, 'NFT');
+
+ await executeTransaction(api, alice, api.tx.unique.setPropertyPermissions(collection, [{
+ key: 'testKey',
+ permission: {
+ collectionAdmin: true,
+ },
+ }]));
+
+ await addCollectionAdminExpectSuccess(alice, collection, {Ethereum: caller});
+
+ const address = collectionIdToAddress(collection);
+ const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+
+ await contract.methods.setProperty(token, 'testKey', Buffer.from('testValue')).send({from: caller});
+
+ const [{value}] = (await api.rpc.unique.tokenProperties(collection, token, ['testKey'])).toHuman()! as any;
+ expect(value).to.equal('testValue');
+ });
+ itWeb3('Can be deleted', async({web3, api}) => {
+ const alice = privateKey('//Alice');
+ const caller = await createEthAccountWithBalance(api, web3);
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const token = await createItemExpectSuccess(alice, collection, 'NFT');
+
+ await executeTransaction(api, alice, api.tx.unique.setPropertyPermissions(collection, [{
+ key: 'testKey',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ },
+ }]));
+ await executeTransaction(api, alice, api.tx.unique.setTokenProperties(collection, token, [{key: 'testKey', value: 'testValue'}]));
+
+ await addCollectionAdminExpectSuccess(alice, collection, {Ethereum: caller});
+
+ const address = collectionIdToAddress(collection);
+ const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+
+ await contract.methods.deleteProperty(token, 'testKey').send({from: caller});
+
+ const result = (await api.rpc.unique.tokenProperties(collection, token, ['testKey'])).toJSON()! as any;
+ expect(result.length).to.equal(0);
+ });
+ itWeb3('Can be read', async({web3, api}) => {
+ const alice = privateKey('//Alice');
+ const caller = createEthAccount(web3);
+ const collection = await createCollectionExpectSuccess({mode: {type:'NFT'}});
+ const token = await createItemExpectSuccess(alice, collection, 'NFT');
+
+ await executeTransaction(api, alice, api.tx.unique.setPropertyPermissions(collection, [{
+ key: 'testKey',
+ permission: {
+ collectionAdmin: true,
+ },
+ }]));
+ await executeTransaction(api, alice, api.tx.unique.setTokenProperties(collection, token, [{key: 'testKey', value: 'testValue'}]));
+
+ const address = collectionIdToAddress(collection);
+ const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+
+ const value = await contract.methods.property(token, 'testKey').call();
+ expect(value).to.equal(web3.utils.toHex('testValue'));
+ });
+});
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 {CrossAccountId, getGenericResult, UNIQUE} from '../../util/helpers';27import * as solc from 'solc';28import config from '../../config';29import privateKey from '../../substrate/privateKey';30import contractHelpersAbi from './contractHelpersAbi.json';31import 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}5859function encodeIntBE(v: number): number[] {60 if (v >= 0xffffffff || v < 0) throw new Error('id overflow');61 return [62 v >> 24,63 (v >> 16) & 0xff,64 (v >> 8) & 0xff,65 v & 0xff,66 ];67}6869export function collectionIdToAddress(collection: number): string {70 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,71 ...encodeIntBE(collection),72 ]);73 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));74}7576export function tokenIdToAddress(collection: number, token: number): string {77 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,78 ...encodeIntBE(collection),79 ...encodeIntBE(token),80 ]);81 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));82}83export function tokenIdToCross(collection: number, token: number): CrossAccountId {84 return {85 Ethereum: tokenIdToAddress(collection, token),86 };87}8889export function createEthAccount(web3: Web3) {90 const account = web3.eth.accounts.create();91 web3.eth.accounts.wallet.add(account.privateKey);92 return account.address;93}9495export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {96 const alice = privateKey('//Alice');97 const account = createEthAccount(web3);98 await transferBalanceToEth(api, alice, account);99100 return account;101}102103export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {104 const tx = api.tx.balances.transfer(evmToAddress(target), amount);105 const events = await submitTransactionAsync(source, tx);106 const result = getGenericResult(events);107 expect(result.success).to.be.true;108}109110export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {111 let i: any = it;112 if (opts.only) i = i.only;113 else if (opts.skip) i = i.skip;114 i(name, async () => {115 await usingApi(async api => {116 await usingWeb3(async web3 => {117 await cb({api, web3});118 });119 });120 });121}122itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});123itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});124125export async function generateSubstrateEthPair(web3: Web3) {126 const account = web3.eth.accounts.create();127 evmToAddress(account.address);128}129130type NormalizedEvent = {131 address: string,132 event: string,133 args: { [key: string]: string }134};135136export function normalizeEvents(events: any): NormalizedEvent[] {137 const output = [];138 for (const key of Object.keys(events)) {139 if (key.match(/^[0-9]+$/)) {140 output.push(events[key]);141 } else if (Array.isArray(events[key])) {142 output.push(...events[key]);143 } else {144 output.push(events[key]);145 }146 }147 output.sort((a, b) => a.logIndex - b.logIndex);148 return output.map(({address, event, returnValues}) => {149 const args: { [key: string]: string } = {};150 for (const key of Object.keys(returnValues)) {151 if (!key.match(/^[0-9]+$/)) {152 args[key] = returnValues[key];153 }154 }155 return {156 address,157 event,158 args,159 };160 });161}162163export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {164 const out: any = [];165 contract.events.allEvents((_: any, event: any) => {166 out.push(event);167 });168 await action();169 return normalizeEvents(out);170}171172export function subToEthLowercase(eth: string): string {173 const bytes = addressToEvm(eth);174 return '0x' + Buffer.from(bytes).toString('hex');175}176177export function subToEth(eth: string): string {178 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));179}180181export function compileContract(name: string, src: string) {182 const out = JSON.parse(solc.compile(JSON.stringify({183 language: 'Solidity',184 sources: {185 [`${name}.sol`]: {186 content: `187 // SPDX-License-Identifier: UNLICENSED188 pragma solidity ^0.8.6;189190 ${src}191 `,192 },193 },194 settings: {195 outputSelection: {196 '*': {197 '*': ['*'],198 },199 },200 },201 }))).contracts[`${name}.sol`][name];202203 return {204 abi: out.abi,205 object: '0x' + out.evm.bytecode.object,206 };207}208209export async function deployFlipper(web3: Web3, deployer: string) {210 const compiled = compileContract('Flipper', `211 contract Flipper {212 bool value = false;213 function flip() public {214 value = !value;215 }216 function getValue() public view returns (bool) {217 return value;218 }219 }220 `);221 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {222 data: compiled.object,223 from: deployer,224 ...GAS_ARGS,225 });226 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});227228 return flipper;229}230231export async function deployCollector(web3: Web3, deployer: string) {232 const compiled = compileContract('Collector', `233 contract Collector {234 uint256 collected;235 fallback() external payable {236 giveMoney();237 }238 function giveMoney() public payable {239 collected += msg.value;240 }241 function getCollected() public view returns (uint256) {242 return collected;243 }244 function getUnaccounted() public view returns (uint256) {245 return address(this).balance - collected;246 }247248 function withdraw(address payable target) public {249 target.transfer(collected);250 collected = 0;251 }252 }253 `);254 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {255 data: compiled.object,256 from: deployer,257 ...GAS_ARGS,258 });259 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});260261 return collector;262}263264/** 265 * pallet evm_contract_helpers266 * @param web3 267 * @param caller - eth address268 * @returns 269 */270export function contractHelpers(web3: Web3, caller: string) {271 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});272}273274/**275 * Execute ethereum method call using substrate account276 * @param to target contract277 * @param mkTx - closure, receiving `contract.methods`, and returning method call,278 * to be used as following (assuming `to` = erc20 contract):279 * `m => m.transfer(to, amount)`280 *281 * # Example282 * ```ts283 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));284 * ```285 */286export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {287 const tx = api.tx.evm.call(288 subToEth(from.address),289 to.options.address,290 mkTx(to.methods).encodeABI(),291 value,292 GAS_ARGS.gas,293 await web3.eth.getGasPrice(),294 null,295 null,296 [],297 );298 const events = await submitTransactionAsync(from, tx);299 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;300}301302export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {303 return (await getBalance(api, [evmToAddress(address)]))[0];304}305306/**307 * Measure how much gas given closure consumes308 *309 * @param user which user balance will be checked310 */311export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {312 const before = await ethBalanceViaSub(api, user);313314 await call();315316 // In dev mode, the transaction might not finish processing in time317 await waitNewBlocks(api, 1);318 const after = await ethBalanceViaSub(api, user);319320 // Can't use .to.be.less, because chai doesn't supports bigint321 expect(after < before).to.be.true;322323 return before - after;324}