difftreelog
feat add nested ops - scheduled and sudo
in: master
5 files changed
tests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/index.ts
+++ b/tests/src/eth/util/playgrounds/index.ts
@@ -39,7 +39,6 @@
}
finally {
await helper.disconnect();
- await helper.disconnectWeb3();
silentConsole.disable();
}
};
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth1// 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, NormalizedEvent} 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';30import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';3132class EthGroupBase {33 helper: EthUniqueHelper;3435 constructor(helper: EthUniqueHelper) {36 this.helper = helper;37 }38}394041class ContractGroup extends EthGroupBase {42 async findImports(imports?: ContractImports[]){43 if(!imports) return function(path: string) {44 return {error: `File not found: ${path}`};45 };46 47 const knownImports = {} as {[key: string]: string};48 for(const imp of imports) {49 knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();50 }51 52 return function(path: string) {53 if(path in knownImports) return {contents: knownImports[path]};54 return {error: `File not found: ${path}`};55 };56 }5758 async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {59 const out = JSON.parse(solc.compile(JSON.stringify({60 language: 'Solidity',61 sources: {62 [`${name}.sol`]: {63 content: src,64 },65 },66 settings: {67 outputSelection: {68 '*': {69 '*': ['*'],70 },71 },72 },73 }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];74 75 return {76 abi: out.abi,77 object: '0x' + out.evm.bytecode.object,78 };79 }8081 async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {82 const compiledContract = await this.compile(name, src, imports);83 return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);84 }8586 async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {87 const web3 = this.helper.getWeb3();88 const contract = new web3.eth.Contract(abi, undefined, {89 data: object,90 from: signer,91 gas: this.helper.eth.DEFAULT_GAS,92 });93 return await contract.deploy({data: object}).send({from: signer});94 }9596}97 98class NativeContractGroup extends EthGroupBase {99100 contractHelpers(caller: string): Contract {101 const web3 = this.helper.getWeb3();102 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});103 }104105 collectionHelpers(caller: string) {106 const web3 = this.helper.getWeb3();107 return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});108 }109110 collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {111 const abi = {112 'nft': nonFungibleAbi,113 'rft': refungibleAbi,114 'ft': fungibleAbi,115 }[mode];116 const web3 = this.helper.getWeb3();117 return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});118 }119120 collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {121 return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);122 }123124 rftToken(address: string, caller?: string): Contract {125 const web3 = this.helper.getWeb3();126 return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});127 }128129 rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {130 return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);131 }132}133134135class EthGroup extends EthGroupBase {136 DEFAULT_GAS = 2_500_000;137138 createAccount() {139 const web3 = this.helper.getWeb3();140 const account = web3.eth.accounts.create();141 web3.eth.accounts.wallet.add(account.privateKey);142 return account.address;143 }144145 async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {146 const account = this.createAccount();147 await this.transferBalanceFromSubstrate(donor, account, amount);148 149 return account;150 }151152 async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {153 return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));154 }155 156 async getCollectionCreationFee(signer: string) {157 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);158 return await collectionHelper.methods.collectionCreationFee().call();159 }160161 async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {162 if(!gasLimit) gasLimit = this.DEFAULT_GAS;163 const web3 = this.helper.getWeb3();164 const gasPrice = await web3.eth.getGasPrice();165 // TODO: check execution status166 await this.helper.executeExtrinsic(167 signer,168 'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],169 true,170 );171 }172173 async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {174 return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);175 }176177 async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {178 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();179 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);180 181 const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});182183 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);184 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);185186 return {collectionId, collectionAddress};187 }188189 async createRefungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {190 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();191 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);192 193 const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});194195 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);196 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);197198 return {collectionId, collectionAddress};199 }200201 async deployCollectorContract(signer: string): Promise<Contract> {202 return await this.helper.ethContract.deployByCode(signer, 'Collector', `203 // SPDX-License-Identifier: UNLICENSED204 pragma solidity ^0.8.6;205206 contract Collector {207 uint256 collected;208 fallback() external payable {209 giveMoney();210 }211 function giveMoney() public payable {212 collected += msg.value;213 }214 function getCollected() public view returns (uint256) {215 return collected;216 }217 function getUnaccounted() public view returns (uint256) {218 return address(this).balance - collected;219 }220221 function withdraw(address payable target) public {222 target.transfer(collected);223 collected = 0;224 }225 }226 `);227 }228229 async deployFlipper(signer: string): Promise<Contract> {230 return await this.helper.ethContract.deployByCode(signer, 'Flipper', `231 // SPDX-License-Identifier: UNLICENSED232 pragma solidity ^0.8.6;233234 contract Flipper {235 bool value = false;236 function flip() public {237 value = !value;238 }239 function getValue() public view returns (bool) {240 return value;241 }242 }243 `);244 }245246 async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {247 const before = await this.helper.balance.getEthereum(user);248 await call();249 // In dev mode, the transaction might not finish processing in time250 await this.helper.wait.newBlocks(1);251 const after = await this.helper.balance.getEthereum(user);252253 return before - after;254 }255256 normalizeEvents(events: any): NormalizedEvent[] {257 const output = [];258 for (const key of Object.keys(events)) {259 if (key.match(/^[0-9]+$/)) {260 output.push(events[key]);261 } else if (Array.isArray(events[key])) {262 output.push(...events[key]);263 } else {264 output.push(events[key]);265 }266 }267 output.sort((a, b) => a.logIndex - b.logIndex);268 return output.map(({address, event, returnValues}) => {269 const args: { [key: string]: string } = {};270 for (const key of Object.keys(returnValues)) {271 if (!key.match(/^[0-9]+$/)) {272 args[key] = returnValues[key];273 }274 }275 return {276 address,277 event,278 args,279 };280 });281 }282283 async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {284 const wrappedCode = async () => {285 await code();286 // In dev mode, the transaction might not finish processing in time287 await this.helper.wait.newBlocks(1);288 };289 return await this.helper.arrange.calculcateFee(address, wrappedCode);290 }291} 292293class EthAddressGroup extends EthGroupBase {294 extractCollectionId(address: string): number {295 if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');296 return parseInt(address.substr(address.length - 8), 16);297 }298299 fromCollectionId(collectionId: number): string {300 if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');301 return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8,'0')}`);302 }303304 extractTokenId(address: string): {collectionId: number, tokenId: number} {305 if (!address.startsWith('0x'))306 throw 'address not starts with "0x"';307 if (address.length > 42)308 throw 'address length is more than 20 bytes';309 return {310 collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),311 tokenId: Number('0x' + address.substring(address.length - 8)),312 };313 }314315 fromTokenId(collectionId: number, tokenId: number): string {316 return this.helper.util.getTokenAddress({collectionId, tokenId});317 }318319 normalizeAddress(address: string): string {320 return '0x' + address.substring(address.length - 40);321 }322} 323 324325export class EthUniqueHelper extends DevUniqueHelper {326 web3: Web3 | null = null;327 web3Provider: WebsocketProvider | null = null;328329 eth: EthGroup;330 ethAddress: EthAddressGroup;331 ethNativeContract: NativeContractGroup;332 ethContract: ContractGroup;333334 constructor(logger: { log: (msg: any, level: any) => void, level: any }) {335 super(logger);336 this.eth = new EthGroup(this);337 this.ethAddress = new EthAddressGroup(this);338 this.ethNativeContract = new NativeContractGroup(this);339 this.ethContract = new ContractGroup(this);340 }341342 getWeb3(): Web3 {343 if(this.web3 === null) throw Error('Web3 not connected');344 return this.web3;345 }346347 async connectWeb3(wsEndpoint: string) {348 if(this.web3 !== null) return;349 this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);350 this.web3 = new Web3(this.web3Provider);351 }352353 async disconnectWeb3() {354 if(this.web3 === null) return;355 this.web3Provider?.connection.close();356 this.web3 = null;357 }358}359 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, NormalizedEvent} 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';30import {ICrossAccountId, TEthereumAccount} from '../../../util/playgrounds/types';3132class EthGroupBase {33 helper: EthUniqueHelper;3435 constructor(helper: EthUniqueHelper) {36 this.helper = helper;37 }38}394041class ContractGroup extends EthGroupBase {42 async findImports(imports?: ContractImports[]){43 if(!imports) return function(path: string) {44 return {error: `File not found: ${path}`};45 };46 47 const knownImports = {} as {[key: string]: string};48 for(const imp of imports) {49 knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();50 }51 52 return function(path: string) {53 if(path in knownImports) return {contents: knownImports[path]};54 return {error: `File not found: ${path}`};55 };56 }5758 async compile(name: string, src: string, imports?: ContractImports[]): Promise<CompiledContract> {59 const out = JSON.parse(solc.compile(JSON.stringify({60 language: 'Solidity',61 sources: {62 [`${name}.sol`]: {63 content: src,64 },65 },66 settings: {67 outputSelection: {68 '*': {69 '*': ['*'],70 },71 },72 },73 }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];74 75 return {76 abi: out.abi,77 object: '0x' + out.evm.bytecode.object,78 };79 }8081 async deployByCode(signer: string, name: string, src: string, imports?: ContractImports[]): Promise<Contract> {82 const compiledContract = await this.compile(name, src, imports);83 return this.deployByAbi(signer, compiledContract.abi, compiledContract.object);84 }8586 async deployByAbi(signer: string, abi: any, object: string): Promise<Contract> {87 const web3 = this.helper.getWeb3();88 const contract = new web3.eth.Contract(abi, undefined, {89 data: object,90 from: signer,91 gas: this.helper.eth.DEFAULT_GAS,92 });93 return await contract.deploy({data: object}).send({from: signer});94 }9596}97 98class NativeContractGroup extends EthGroupBase {99100 contractHelpers(caller: string): Contract {101 const web3 = this.helper.getWeb3();102 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, gas: this.helper.eth.DEFAULT_GAS});103 }104105 collectionHelpers(caller: string) {106 const web3 = this.helper.getWeb3();107 return new web3.eth.Contract(collectionHelpersAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, gas: this.helper.eth.DEFAULT_GAS});108 }109110 collection(address: string, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {111 const abi = {112 'nft': nonFungibleAbi,113 'rft': refungibleAbi,114 'ft': fungibleAbi,115 }[mode];116 const web3 = this.helper.getWeb3();117 return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});118 }119120 collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {121 return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);122 }123124 rftToken(address: string, caller?: string): Contract {125 const web3 = this.helper.getWeb3();126 return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});127 }128129 rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {130 return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);131 }132}133134135class EthGroup extends EthGroupBase {136 DEFAULT_GAS = 2_500_000;137138 createAccount() {139 const web3 = this.helper.getWeb3();140 const account = web3.eth.accounts.create();141 web3.eth.accounts.wallet.add(account.privateKey);142 return account.address;143 }144145 async createAccountWithBalance(donor: IKeyringPair, amount=1000n) {146 const account = this.createAccount();147 await this.transferBalanceFromSubstrate(donor, account, amount);148 149 return account;150 }151152 async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=1000n, inTokens=true) {153 return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));154 }155 156 async getCollectionCreationFee(signer: string) {157 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);158 return await collectionHelper.methods.collectionCreationFee().call();159 }160161 async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {162 if(!gasLimit) gasLimit = this.DEFAULT_GAS;163 const web3 = this.helper.getWeb3();164 const gasPrice = await web3.eth.getGasPrice();165 // TODO: check execution status166 await this.helper.executeExtrinsic(167 signer,168 'api.tx.evm.call', [this.helper.address.substrateToEth(signer.address), contractAddress, abi, value, gasLimit, gasPrice, null, null, []],169 true,170 );171 }172173 async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {174 return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);175 }176177 async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {178 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();179 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);180 181 const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});182183 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);184 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);185186 return {collectionId, collectionAddress};187 }188189 async createRefungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {190 const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();191 const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);192 193 const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});194195 const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);196 const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);197198 return {collectionId, collectionAddress};199 }200201 async deployCollectorContract(signer: string): Promise<Contract> {202 return await this.helper.ethContract.deployByCode(signer, 'Collector', `203 // SPDX-License-Identifier: UNLICENSED204 pragma solidity ^0.8.6;205206 contract Collector {207 uint256 collected;208 fallback() external payable {209 giveMoney();210 }211 function giveMoney() public payable {212 collected += msg.value;213 }214 function getCollected() public view returns (uint256) {215 return collected;216 }217 function getUnaccounted() public view returns (uint256) {218 return address(this).balance - collected;219 }220221 function withdraw(address payable target) public {222 target.transfer(collected);223 collected = 0;224 }225 }226 `);227 }228229 async deployFlipper(signer: string): Promise<Contract> {230 return await this.helper.ethContract.deployByCode(signer, 'Flipper', `231 // SPDX-License-Identifier: UNLICENSED232 pragma solidity ^0.8.6;233234 contract Flipper {235 bool value = false;236 function flip() public {237 value = !value;238 }239 function getValue() public view returns (bool) {240 return value;241 }242 }243 `);244 }245246 async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {247 const before = await this.helper.balance.getEthereum(user);248 await call();249 // In dev mode, the transaction might not finish processing in time250 await this.helper.wait.newBlocks(1);251 const after = await this.helper.balance.getEthereum(user);252253 return before - after;254 }255256 normalizeEvents(events: any): NormalizedEvent[] {257 const output = [];258 for (const key of Object.keys(events)) {259 if (key.match(/^[0-9]+$/)) {260 output.push(events[key]);261 } else if (Array.isArray(events[key])) {262 output.push(...events[key]);263 } else {264 output.push(events[key]);265 }266 }267 output.sort((a, b) => a.logIndex - b.logIndex);268 return output.map(({address, event, returnValues}) => {269 const args: { [key: string]: string } = {};270 for (const key of Object.keys(returnValues)) {271 if (!key.match(/^[0-9]+$/)) {272 args[key] = returnValues[key];273 }274 }275 return {276 address,277 event,278 args,279 };280 });281 }282283 async calculateFee(address: ICrossAccountId, code: () => Promise<any>): Promise<bigint> {284 const wrappedCode = async () => {285 await code();286 // In dev mode, the transaction might not finish processing in time287 await this.helper.wait.newBlocks(1);288 };289 return await this.helper.arrange.calculcateFee(address, wrappedCode);290 }291} 292293class EthAddressGroup extends EthGroupBase {294 extractCollectionId(address: string): number {295 if (!(address.length === 42 || address.length === 40)) throw new Error('address wrong format');296 return parseInt(address.substr(address.length - 8), 16);297 }298299 fromCollectionId(collectionId: number): string {300 if (collectionId >= 0xffffffff || collectionId < 0) throw new Error('collectionId overflow');301 return Web3.utils.toChecksumAddress(`0x17c4e6453cc49aaaaeaca894e6d9683e${collectionId.toString(16).padStart(8,'0')}`);302 }303304 extractTokenId(address: string): {collectionId: number, tokenId: number} {305 if (!address.startsWith('0x'))306 throw 'address not starts with "0x"';307 if (address.length > 42)308 throw 'address length is more than 20 bytes';309 return {310 collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),311 tokenId: Number('0x' + address.substring(address.length - 8)),312 };313 }314315 fromTokenId(collectionId: number, tokenId: number): string {316 return this.helper.util.getTokenAddress({collectionId, tokenId});317 }318319 normalizeAddress(address: string): string {320 return '0x' + address.substring(address.length - 40);321 }322} 323 324export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;325326export class EthUniqueHelper extends DevUniqueHelper {327 web3: Web3 | null = null;328 web3Provider: WebsocketProvider | null = null;329330 eth: EthGroup;331 ethAddress: EthAddressGroup;332 ethNativeContract: NativeContractGroup;333 ethContract: ContractGroup;334335 constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {336 options.helperBase = options.helperBase ?? EthUniqueHelper;337338 super(logger, options);339 this.eth = new EthGroup(this);340 this.ethAddress = new EthAddressGroup(this);341 this.ethNativeContract = new NativeContractGroup(this);342 this.ethContract = new ContractGroup(this);343 }344345 getWeb3(): Web3 {346 if(this.web3 === null) throw Error('Web3 not connected');347 return this.web3;348 }349350 async connectWeb3(wsEndpoint: string) {351 if(this.web3 !== null) return;352 this.web3Provider = new Web3.providers.WebsocketProvider(wsEndpoint);353 this.web3 = new Web3(this.web3Provider);354 }355356 async disconnect() {357 if(this.web3 === null) return;358 this.web3Provider?.connection.close();359360 await super.disconnect();361 }362363 clearApi() {364 this.web3 = null;365 }366367 clone(helperCls: EthUniqueHelperConstructor, options?: { [key: string]: any; }): EthUniqueHelper {368 const newHelper = super.clone(helperCls, options) as EthUniqueHelper;369 newHelper.web3 = this.web3;370 newHelper.web3Provider = this.web3Provider;371372 return newHelper;373 }374}375 tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -164,6 +164,14 @@
amount: bigint,
}
+export interface ISchedulerOptions {
+ priority?: number,
+ periodic?: {
+ period: number,
+ repetitions: number,
+ },
+}
+
export type TSubstrateAccount = string;
export type TEthereumAccount = string;
export type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -7,6 +7,9 @@
import * as defs from '../../interfaces/definitions';
import {IKeyringPair} from '@polkadot/types/types';
import {ICrossAccountId} from './types';
+import type {EventRecord} from '@polkadot/types/interfaces';
+import {VoidFn} from '@polkadot/api/types';
+import {FrameSystemEventRecord} from '@polkadot/types/lookup';
export class SilentLogger {
@@ -63,8 +66,10 @@
wait: WaitGroup;
admin: AdminGroup;
- constructor(logger: { log: (msg: any, level: any) => void, level: any }) {
- super(logger);
+ constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {
+ options.helperBase = options.helperBase ?? DevUniqueHelper;
+
+ super(logger, options);
this.arrange = new ArrangeGroup(this);
this.wait = new WaitGroup(this);
this.admin = new AdminGroup(this);
@@ -108,9 +113,9 @@
}
class ArrangeGroup {
- helper: UniqueHelper;
+ helper: DevUniqueHelper;
- constructor(helper: UniqueHelper) {
+ constructor(helper: DevUniqueHelper) {
this.helper = helper;
}
@@ -245,14 +250,14 @@
}
class WaitGroup {
- helper: UniqueHelper;
+ helper: DevUniqueHelper;
- constructor(helper: UniqueHelper) {
+ constructor(helper: DevUniqueHelper) {
this.helper = helper;
}
/**
- * Wait for specified bnumber of blocks
+ * Wait for specified number of blocks
* @param blocksCount number of blocks to wait
* @returns
*/
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -9,7 +9,8 @@
import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';
import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';
import {IKeyringPair} from '@polkadot/types/types';
-import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
+import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';
+import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';
export class CrossAccountId implements ICrossAccountId {
Substrate?: TSubstrateAccount;
@@ -318,6 +319,7 @@
forcedNetwork: TUniqueNetworks | null;
network: TUniqueNetworks | null;
chainLog: IUniqueHelperLog[];
+ children: ChainHelperBase[];
constructor(logger?: ILogger) {
this.util = UniqueUtil;
@@ -328,6 +330,7 @@
this.forcedNetwork = null;
this.network = null;
this.chainLog = [];
+ this.children = [];
}
getApi(): ApiPromise {
@@ -351,8 +354,16 @@
}
async disconnect() {
+ for (const child of this.children) {
+ child.clearApi();
+ }
+
if (this.api === null) return;
await this.api.disconnect();
+ this.clearApi();
+ }
+
+ clearApi() {
this.api = null;
this.network = null;
}
@@ -479,7 +490,7 @@
constructApiCall(apiCall: string, params: any[]) {
if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);
- let call = this.api as any;
+ let call = this.getApi() as any;
for(const part of apiCall.slice(4).split('.')) {
call = call[part];
}
@@ -2248,7 +2259,67 @@
}
}
+class SchedulerGroup extends HelperGroup {
+ constructor(helper: UniqueHelper) {
+ super(helper);
+ }
+
+ async cancelScheduled(signer: TSigner, scheduledId: string) {
+ return this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.scheduler.cancelNamed',
+ [scheduledId],
+ true,
+ );
+ }
+
+ async changePriority(signer: TSigner, scheduledId: string, priority: number) {
+ return this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.scheduler.changeNamedPriority',
+ [scheduledId, priority],
+ true,
+ );
+ }
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);
+ }
+
+ schedule<T extends UniqueHelper>(
+ scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',
+ scheduledId: string,
+ blocksNum: number,
+ options: ISchedulerOptions = {},
+ ) {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);
+ return this.helper.clone(ScheduledHelperType, {
+ scheduleFn,
+ scheduledId,
+ blocksNum,
+ options,
+ }) as T;
+ }
+}
+
+export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;
+
export class UniqueHelper extends ChainHelperBase {
+ helperBase: any;
+
chain: ChainGroup;
balance: BalanceGroup;
address: AddressGroup;
@@ -2257,9 +2328,13 @@
rft: RFTGroup;
ft: FTGroup;
staking: StakingGroup;
+ scheduler: SchedulerGroup;
- constructor(logger?: ILogger) {
+ constructor(logger?: ILogger, options: {[key: string]: any} = {}) {
super(logger);
+
+ this.helperBase = options.helperBase ?? UniqueHelper;
+
this.chain = new ChainGroup(this);
this.balance = new BalanceGroup(this);
this.address = new AddressGroup(this);
@@ -2268,9 +2343,98 @@
this.rft = new RFTGroup(this);
this.ft = new FTGroup(this);
this.staking = new StakingGroup(this);
+ this.scheduler = new SchedulerGroup(this);
}
+
+ clone(helperCls: UniqueHelperConstructor, options: {[key: string]: any} = {}) {
+ Object.setPrototypeOf(helperCls.prototype, this);
+ const newHelper = new helperCls(this.logger, options);
+
+ newHelper.api = this.api;
+ newHelper.network = this.network;
+ newHelper.forceNetwork = this.forceNetwork;
+
+ this.children.push(newHelper);
+
+ return newHelper;
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ const SudoHelperType = SudoUniqueHelper(this.helperBase);
+ return this.clone(SudoHelperType) as T;
+ }
}
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {
+ return class extends Base {
+ scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';
+ scheduledId: string;
+ blocksNum: number;
+ options: ISchedulerOptions;
+
+ constructor(...args: any[]) {
+ const logger = args[0] as ILogger;
+ const options = args[1] as {
+ scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',
+ scheduledId: string,
+ blocksNum: number,
+ options: ISchedulerOptions
+ };
+
+ super(logger);
+
+ this.scheduleFn = options.scheduleFn;
+ this.scheduledId = options.scheduledId;
+ this.blocksNum = options.blocksNum;
+ this.options = options.options;
+ }
+
+ executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {
+ const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);
+ const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;
+
+ return super.executeExtrinsic(
+ sender,
+ extrinsic,
+ [
+ this.scheduledId,
+ this.blocksNum,
+ this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,
+ this.options.priority ?? null,
+ {Value: scheduledTx},
+ ],
+ expectSuccess,
+ );
+ }
+ };
+}
+
+// eslint-disable-next-line @typescript-eslint/naming-convention
+function SudoUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {
+ return class extends Base {
+ constructor(...args: any[]) {
+ super(...args);
+ }
+
+ executeExtrinsic (
+ sender: IKeyringPair,
+ extrinsic: string,
+ params: any[],
+ expectSuccess?: boolean,
+ ): Promise<ITransactionResult> {
+ const call = this.constructApiCall(extrinsic, params);
+
+ return super.executeExtrinsic(
+ sender,
+ 'api.tx.sudo.sudo',
+ [call],
+ expectSuccess,
+ );
+ }
+ };
+}
export class UniqueBaseCollection {
helper: UniqueHelper;
@@ -2372,6 +2536,28 @@
async burn(signer: TSigner) {
return await this.helper.collection.burn(signer, this.collectionId);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueBaseCollection(this.collectionId, scheduledHelper);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueBaseCollection(this.collectionId, scheduledHelper);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());
+ }
}
@@ -2459,6 +2645,28 @@
async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {
return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueNFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueNFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());
+ }
}
@@ -2542,6 +2750,28 @@
async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {
return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueRFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueRFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());
+ }
}
@@ -2589,6 +2819,28 @@
async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {
return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueFTCollection(this.collectionId, scheduledHelper);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());
+ }
}
@@ -2626,6 +2878,28 @@
nestingAccount() {
return this.collection.helper.util.getTokenAccount(this);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueBaseToken(this.tokenId, scheduledCollection);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueBaseToken(this.tokenId, scheduledCollection);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());
+ }
}
@@ -2684,6 +2958,28 @@
async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {
return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueNFToken(this.tokenId, scheduledCollection);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueNFToken(this.tokenId, scheduledCollection);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());
+ }
}
export class UniqueRFToken extends UniqueBaseToken {
@@ -2737,4 +3033,26 @@
async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {
return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);
}
+
+ scheduleAt<T extends UniqueHelper>(
+ scheduledId: string,
+ executionBlockNumber: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+ return new UniqueRFToken(this.tokenId, scheduledCollection);
+ }
+
+ scheduleAfter<T extends UniqueHelper>(
+ scheduledId: string,
+ blocksBeforeExecution: number,
+ options: ISchedulerOptions = {},
+ ) {
+ const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+ return new UniqueRFToken(this.tokenId, scheduledCollection);
+ }
+
+ getSudo<T extends UniqueHelper>() {
+ return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());
+ }
}