git.delta.rocks / unique-network / refs/commits / 343d804c01f9

difftreelog

fix review

Max Andreev2022-09-15parent: #1a380ae.patch.diff
in: master

3 files changed

modifiedtests/src/app-promotion.test.tsdiffbeforeafterboth
--- a/tests/src/app-promotion.test.ts
+++ b/tests/src/app-promotion.test.ts
@@ -414,8 +414,8 @@
     const collection = await helper.nft.mintCollection(collectionOwner, {name: 'New', description: 'New Collection', tokenPrefix: 'Promotion'});
       
     await collection.burn(collectionOwner);
-    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(collection.collectionId))).to.be.rejected;
-    await expect(helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.stopSponsoringCollection(999999999))).to.be.rejected;
+    await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [collection.collectionId], true)).to.be.rejectedWith('common.CollectionNotFound');
+    await expect(helper.executeExtrinsic(palletAdmin, 'api.tx.appPromotion.stopSponsoringCollection', [999_999_999], true)).to.be.rejectedWith('common.CollectionNotFound');
   });
 });
 
@@ -459,8 +459,8 @@
 
     // new sponsor is pallet address
     expect(await contractHelper.methods.hasSponsor(flipper.options.address).call()).to.be.true;  
-    expect((await helper.api!.query.evmContractHelpers.owner(flipper.options.address)).toJSON()).to.be.equal(contractOwner);  
-    expect((await helper.api!.query.evmContractHelpers.sponsoring(flipper.options.address)).toJSON()).to.deep.equal({
+    expect((await helper.callRpc('api.query.evmContractHelpers.owner', [flipper.options.address])).toJSON()).to.be.equal(contractOwner);  
+    expect((await helper.callRpc('api.query.evmContractHelpers.sponsoring', [flipper.options.address])).toJSON()).to.deep.equal({
       confirmed: {
         substrate: palletAddress,
       },
@@ -602,7 +602,7 @@
 
   itSub('can not be called by non admin', async ({helper}) => {
     const nonAdmin = accounts.pop()!;
-    await expect(helper.signTransaction(nonAdmin, helper.api!.tx.appPromotion.payoutStakers(100))).to.be.rejected;
+    await expect(helper.admin.payoutStakers(nonAdmin, 100)).to.be.rejectedWith('appPromotion.NoPermission');
   });
 
   itSub('should increase total staked', async ({helper}) => {
@@ -613,7 +613,7 @@
     // Wait for rewards and pay
     const [stakedInBlock] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
     await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stakedInBlock.block));
-    const totalPayout = (await helper.sudo.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);
+    const totalPayout = (await helper.admin.payoutStakers(palletAdmin, 100)).reduce((prev, payout) => prev + payout.payout, 0n);
 
     const totalStakedAfter = await helper.staking.getTotalStaked();
     expect(totalStakedAfter).to.equal(totalStakedBefore + (100n * nominal) + totalPayout);
@@ -634,7 +634,7 @@
     const [_, stake2] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
     await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake2.block));
 
-    const payoutToStaker = (await helper.sudo.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)?.payout;
+    const payoutToStaker = (await helper.admin.payoutStakers(palletAdmin, 100)).find((payout) => payout.staker === staker.address)?.payout;
     expect(payoutToStaker + 300n * nominal).to.equal(calculateIncome(300n * nominal, 10n));
 
     const totalStakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
@@ -650,7 +650,7 @@
     let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
     await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
 
-    await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
+    await helper.admin.payoutStakers(palletAdmin, 100);
     [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
     const frozenBalanceShouldBe = calculateIncome(100n * nominal, 10n, 2);
     expect(stake.amount).to.be.equal(frozenBalanceShouldBe);
@@ -670,7 +670,7 @@
       
     // so he did not receive any rewards
     const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);
-    await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
+    await helper.admin.payoutStakers(palletAdmin, 100);
     const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);
 
     expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);
@@ -684,12 +684,12 @@
     let [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
     await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block));
       
-    await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
+    await helper.admin.payoutStakers(palletAdmin, 100);
     [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
     expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n));
       
     await helper.wait.forRelayBlockNumber(rewardAvailableInBlock(stake.block) + LOCKING_PERIOD);
-    await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
+    await helper.admin.payoutStakers(palletAdmin, 100);
     [stake] = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
     expect(stake.amount).to.equal(calculateIncome(100n * nominal, 10n, 2));
   });
@@ -703,7 +703,7 @@
       await Promise.all(oneHundredStakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
     }
     await helper.wait.newBlocks(40);
-    const result = await helper.signTransaction(palletAdmin, helper.api!.tx.appPromotion.payoutStakers(100));
+    await helper.admin.payoutStakers(palletAdmin, 100);
   });
 
   itSub.skip('can handle 40.000 rewards', async ({helper}) => {
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/eth/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable function-call-argument-newline */5// eslint-disable-next-line @typescript-eslint/triple-slash-reference6/// <reference path="unique.dev.d.ts" />78import {readFile} from 'fs/promises';910import Web3 from 'web3';11import {WebsocketProvider} from 'web3-core';12import {Contract} from 'web3-eth-contract';1314import * as solc from 'solc';1516import {evmToAddress} from '@polkadot/util-crypto';17import {IKeyringPair} from '@polkadot/types/types';1819import {DevUniqueHelper} from '../../../util/playgrounds/unique.dev';2021import {ContractImports, CompiledContract} from './types';2223// Native contracts ABI24import collectionHelpersAbi from '../../collectionHelpersAbi.json';25import fungibleAbi from '../../fungibleAbi.json';26import nonFungibleAbi from '../../nonFungibleAbi.json';27import refungibleAbi from '../../reFungibleAbi.json';28import refungibleTokenAbi from '../../reFungibleTokenAbi.json';29import contractHelpersAbi from './../contractHelpersAbi.json';3031class EthGroupBase {32  helper: EthUniqueHelper;3334  constructor(helper: EthUniqueHelper) {35    this.helper = helper;36  }37}383940class ContractGroup extends EthGroupBase {41  async findImports(imports?: ContractImports[]){42    if(!imports) return function(path: string) {43      return {error: `File not found: ${path}`};44    };45  46    const knownImports = {} as any;47    for(const imp of imports) {48      knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();49    }50  51    return function(path: string) {52      if(knownImports.hasOwnPropertyDescriptor(path)) return {contents: knownImports[path]};53      return {error: `File not found: ${path}`};54    };55  }5657  async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {58    const out = JSON.parse(solc.compile(JSON.stringify({59      language: 'Solidity',60      sources: {61        [`${name}.sol`]: {62          content: src,63        },64      },65      settings: {66        outputSelection: {67          '*': {68            '*': ['*'],69          },70        },71      },72    }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];73  74    return {75      abi: out.abi,76      object: '0x' + out.evm.bytecode.object,77    };78  }7980  async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {81    const compiledContract = await this.compile(name, src, imports);82    return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);83  }8485  async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {86    const web3 = this.helper.getWeb3();87    const contract = new web3.eth.Contract(abi, undefined, {88      data: object,89      from: signer,90      gas: this.helper.eth.DEFAULT_GAS,91    });92    return await contract.deploy({data: object}).send({from: signer});93  }9495}96  97class NativeContractGroup extends EthGroupBase {9899  contractHelpers(caller: string): Contract {100    const web3 = this.helper.getWeb3();101    return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});102  }103104  collectionHelpers(caller: string) {105    const web3 = this.helper.getWeb3();106    return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});107  }108109  collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {110    const abi = {111      'nft': nonFungibleAbi,112      'rft': refungibleAbi,113      'ft': fungibleAbi,114    }[mode];115    const web3 = this.helper.getWeb3();116    return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});117  }118119  rftTokenByAddress(address: string, caller?: string): Contract {120    const web3 = this.helper.getWeb3();121    return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});122  }123124  rftToken(collectionId: number, tokenId: number, caller?: string): Contract {125    return this.rftTokenByAddress(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);126  }127}128129  130class EthGroup extends EthGroupBase {131  DEFAULT_GAS = 2_500_000;132133  createAccount() {134    const web3 = this.helper.getWeb3();135    const account = web3.eth.accounts.create();136    web3.eth.accounts.wallet.add(account.privateKey);137    return account.address;138  }139140  async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {141    const account = this.createAccount();142    await this.transferBalanceFromSubstrate(donor, account, amount);143  144    return account;145  }146147  async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {148    return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));149  }150151  async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {152    if(!gasLimit) gasLimit = this.DEFAULT_GAS;153    const web3 = this.helper.getWeb3();154    const gasPrice = await web3.eth.getGasPrice();155    // TODO: check execution status156    await this.helper.executeExtrinsic(157      signer,158      'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],159      true,160    );161  }162163  async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {164    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);165        166    const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send();167168    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);169    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);170171    return {collectionId, collectionAddress};172  }173174  async deployCollectorContract(signer: string): Promise<Contract> {175    return await this.helper.ethContract.deployByCode(signer, 'Collector', `176    // SPDX-License-Identifier: UNLICENSED177    pragma solidity ^0.8.6;178179    contract Collector {180      uint256 collected;181      fallback() external payable {182        giveMoney();183      }184      function giveMoney() public payable {185        collected += msg.value;186      }187      function getCollected() public view returns (uint256) {188        return collected;189      }190      function getUnaccounted() public view returns (uint256) {191        return address(this).balance - collected;192      }193194      function withdraw(address payable target) public {195        target.transfer(collected);196        collected = 0;197      }198    }199  `);200  }201202  async deployFlipper(signer: string): Promise<Contract> {203    return await this.helper.ethContract.deployByCode(signer, 'Flipper', `204    contract Flipper {205      bool value = false;206      function flip() public {207        value = !value;208      }209      function getValue() public view returns (bool) {210        return value;211      }212    }213  `);214  }215}  216  217class EthAddressGroup extends EthGroupBase {218  extractCollectionId(address: string): number {219    if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');220    return parseInt(address.substr(address.length - 8), 16);221  }222223  fromCollectionId(collectionId: number): string {224    if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');225    return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8, '0')}`);226  }227228  extractTokenId(address: string): {collectionId: number, tokenId: number} {229    if (!address.startsWith('0x'))230      throw 'address not starts with "0x"';231    if (address.length > 42)232      throw 'address length is more than 20 bytes';233    return {234      collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),235      tokenId: Number('0x' + address.substring(address.length - 8)),236    };237  }238239  fromTokenId(collectionId: number, tokenId: number): string  {240    return this.helper.util.getNestingTokenAddress(collectionId, tokenId);241  }242243  normalizeAddress(address: string): string {244    return '0x' + address.substring(address.length - 40);245  }246}  247 248249export class EthUniqueHelper extends DevUniqueHelper {250  web3: Web3 | null = null;251  web3Provider: WebsocketProvider | null = null;252253  eth: EthGroup;254  ethAddress: EthAddressGroup;255  ethNativeContract: NativeContractGroup;256  ethContract: ContractGroup;257258  constructor(logger: { log: (msg: any, level: any) => void, level: any }) {259    super(logger);260    this.eth = new EthGroup(this);261    this.ethAddress = new EthAddressGroup(this);262    this.ethNativeContract = new NativeContractGroup(this);263    this.ethContract = new ContractGroup(this);264  }265266  getWeb3(): Web3 {267    if(this.web3 === null) throw Error('Web3 not connected');268    return this.web3;269  }270271  async connectWeb3(wsEndpoint: string) {272    if(this.web3 !== null) return;273    this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);274    this.web3 = new Web3(this.web3Provider);275  }276277  async disconnectWeb3() {278    if(this.web3 === null) return;279    this.web3Provider?.connection.close();280    this.web3 = null;281  }282}283  
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -60,13 +60,13 @@
    */
   arrange: ArrangeGroup;
   wait: WaitGroup;
-  sudo: SudoGroup;
+  admin: AdminGroup;
 
   constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
     super(logger);
     this.arrange = new ArrangeGroup(this);
     this.wait = new WaitGroup(this);
-    this.sudo = new SudoGroup(this);
+    this.admin = new AdminGroup(this);
   }
 
   async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
@@ -284,7 +284,7 @@
   }
 }
 
-class SudoGroup {
+class AdminGroup {
   helper: UniqueHelper;
 
   constructor(helper: UniqueHelper) {
@@ -301,4 +301,4 @@
       };
     });
   }
-}
\ No newline at end of file
+}