difftreelog
test forbid creating ApiPromise without set endpoint
in: master
4 files changed
tests/src/.outdated/substrate/substrate-api.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/>.1617import {ApiPromise, WsProvider} from '@polkadot/api';18import {ApiOptions, ApiTypes, SubmittableExtrinsic} from '@polkadot/api/types';19import {ExtrinsicStatus} from '@polkadot/types/interfaces/author/types';20import {EventRecord} from '@polkadot/types/interfaces/system/types';21import {IKeyringPair} from '@polkadot/types/types';22import config from '../../config';23import '../../interfaces/augment-api-events';24import * as defs from '../../interfaces/definitions';25import privateKey from './privateKey';26import promisifySubstrate from './promisify-substrate';2728import {SilentConsole} from '../../util/playgrounds/unique.dev';29303132function defaultApiOptions(): ApiOptions {33 const wsProvider = new WsProvider(config.substrateUrl);34 return {35 provider: wsProvider, signedExtensions: {36 ContractHelpers: {37 extrinsic: {},38 payload: {},39 },40 CheckMaintenance: {41 extrinsic: {},42 payload: {},43 },44 DisableIdentityCalls: {45 extrinsic: {},46 payload: {},47 },48 FakeTransactionFinalizer: {49 extrinsic: {},50 payload: {},51 },52 },53 rpc: {54 unique: defs.unique.rpc,55 appPromotion: defs.appPromotion.rpc,56 eth: {57 feeHistory: {58 description: 'Dummy',59 params: [],60 type: 'u8',61 },62 maxPriorityFeePerGas: {63 description: 'Dummy',64 params: [],65 type: 'u8',66 },67 },68 },69 };70}7172export async function getApiConnection(settings: ApiOptions | undefined = undefined): Promise<ApiPromise> {73 settings = settings || defaultApiOptions();74 const api = new ApiPromise(settings);7576 if (api) {77 await api.isReadyOrError;78 }7980 return api;81}8283export default async function usingApi<T = void>(action: (api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {84 settings = settings || defaultApiOptions();85 const api: ApiPromise = new ApiPromise(settings);86 let result: T = null as unknown as T;8788 const silentConsole = new SilentConsole();89 silentConsole.enable();9091 try {92 await promisifySubstrate(api, async () => {93 if (api) {94 await api.isReadyOrError;95 const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;96 const privateKeyWrapper = (account: string) => privateKey(account, Number(ss58Format));97 result = await action(api, privateKeyWrapper);98 }99 })();100 } finally {101 await api.disconnect();102 silentConsole.disable();103 }104 return result as T;105}106107enum TransactionStatus {108 Success,109 Fail,110 NotReady111}112113function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {114 if (status.isReady) {115 return TransactionStatus.NotReady;116 }117 if (status.isBroadcast) {118 return TransactionStatus.NotReady;119 }120 if (status.isRetracted) {121 return TransactionStatus.NotReady;122 }123 if (status.isInBlock || status.isFinalized) {124 if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {125 return TransactionStatus.Fail;126 }127 if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {128 return TransactionStatus.Success;129 }130 }131132 return TransactionStatus.Fail;133}134135export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {136 return new Promise(async (res, rej) => {137 try {138 await transaction.signAndSend(sender, ({events, status}) => {139 if (!status.isInBlock && !status.isFinalized) return;140 for (const {event} of events) {141 if (api.events.system.ExtrinsicSuccess.is(event)) {142 res(events);143 } else if (api.events.system.ExtrinsicFailed.is(event)) {144 const {data: [error]} = event;145 if (error.isModule) {146 const decoded = api.registry.findMetaError(error.asModule);147 const {method, section} = decoded;148 rej(new Error(`${section}.${method}`));149 } else {150 rej(new Error(error.toString()));151 }152 }153 }154 });155 } catch (e) {156 rej(e);157 }158 });159}160161/**162 * @deprecated use `executeTransaction` instead163 */164export function165submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {166 /* eslint no-async-promise-executor: "off" */167 return new Promise(async (resolve, reject) => {168 try {169 await transaction.signAndSend(sender, ({events = [], status, dispatchError}) => {170 const transactionStatus = getTransactionStatus(events, status);171172 if (transactionStatus === TransactionStatus.Success) {173 resolve(events);174 } else if (transactionStatus === TransactionStatus.Fail) {175 let moduleError = null;176177 if (dispatchError) {178 if (dispatchError.isModule) {179 const modErr = dispatchError.asModule;180 const errorMeta = dispatchError.registry.findMetaError(modErr);181182 moduleError = JSON.stringify(errorMeta, null, 4);183 }184 }185186 console.log(`Something went wrong with transaction. Status: ${status}\nModule error: ${moduleError}`);187 reject(events);188 }189 });190 } catch (e) {191 console.log('Error: ', e);192 reject(e);193 }194 });195}196197export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {198 console.error = () => {};199 console.log = () => {};200201 /* eslint no-async-promise-executor: "off" */202 return new Promise<EventRecord[]>(async function(res, rej) {203 const resolve = (rec: EventRecord[]) => {204 setTimeout(() => {205 res(rec);206 });207 };208 const reject = (errror: any) => {209 setTimeout(() => {210 rej(errror);211 });212 };213 try {214 await transaction.signAndSend(sender, ({events = [], status}) => {215 const transactionStatus = getTransactionStatus(events, status);216217 // console.log('transactionStatus', transactionStatus, 'events', events);218219 if (transactionStatus === TransactionStatus.Success) {220 resolve(events);221 } else if (transactionStatus === TransactionStatus.Fail) {222 reject(events);223 }224 });225 } catch (e) {226 reject(e);227 }228 });229}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/>.1617import {ApiPromise, WsProvider} from '@polkadot/api';18import {ApiOptions, ApiTypes, SubmittableExtrinsic} from '@polkadot/api/types';19import {ExtrinsicStatus} from '@polkadot/types/interfaces/author/types';20import {EventRecord} from '@polkadot/types/interfaces/system/types';21import {IKeyringPair} from '@polkadot/types/types';22import config from '../../config';23import '../../interfaces/augment-api-events';24import * as defs from '../../interfaces/definitions';25import privateKey from './privateKey';26import promisifySubstrate from './promisify-substrate';2728import {SilentConsole} from '../../util/playgrounds/unique.dev';29303132function defaultApiOptions(): ApiOptions {33 const wsProvider = new WsProvider(config.substrateUrl);34 return {35 provider: wsProvider, signedExtensions: {36 ContractHelpers: {37 extrinsic: {},38 payload: {},39 },40 CheckMaintenance: {41 extrinsic: {},42 payload: {},43 },44 DisableIdentityCalls: {45 extrinsic: {},46 payload: {},47 },48 FakeTransactionFinalizer: {49 extrinsic: {},50 payload: {},51 },52 },53 rpc: {54 unique: defs.unique.rpc,55 appPromotion: defs.appPromotion.rpc,56 eth: {57 feeHistory: {58 description: 'Dummy',59 params: [],60 type: 'u8',61 },62 maxPriorityFeePerGas: {63 description: 'Dummy',64 params: [],65 type: 'u8',66 },67 },68 },69 };70}7172export async function getApiConnection(settings: ApiOptions | undefined = undefined): Promise<ApiPromise> {73 settings = settings || defaultApiOptions();74 if(!settings.provider) throw new Error('provider was not set');75 const api = new ApiPromise(settings);7677 if (api) {78 await api.isReadyOrError;79 }8081 return api;82}8384export default async function usingApi<T = void>(action: (api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {85 settings = settings || defaultApiOptions();86 const api: ApiPromise = new ApiPromise(settings);87 let result: T = null as unknown as T;8889 const silentConsole = new SilentConsole();90 silentConsole.enable();9192 try {93 await promisifySubstrate(api, async () => {94 if (api) {95 await api.isReadyOrError;96 const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;97 const privateKeyWrapper = (account: string) => privateKey(account, Number(ss58Format));98 result = await action(api, privateKeyWrapper);99 }100 })();101 } finally {102 await api.disconnect();103 silentConsole.disable();104 }105 return result as T;106}107108enum TransactionStatus {109 Success,110 Fail,111 NotReady112}113114function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {115 if (status.isReady) {116 return TransactionStatus.NotReady;117 }118 if (status.isBroadcast) {119 return TransactionStatus.NotReady;120 }121 if (status.isRetracted) {122 return TransactionStatus.NotReady;123 }124 if (status.isInBlock || status.isFinalized) {125 if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {126 return TransactionStatus.Fail;127 }128 if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {129 return TransactionStatus.Success;130 }131 }132133 return TransactionStatus.Fail;134}135136export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {137 return new Promise(async (res, rej) => {138 try {139 await transaction.signAndSend(sender, ({events, status}) => {140 if (!status.isInBlock && !status.isFinalized) return;141 for (const {event} of events) {142 if (api.events.system.ExtrinsicSuccess.is(event)) {143 res(events);144 } else if (api.events.system.ExtrinsicFailed.is(event)) {145 const {data: [error]} = event;146 if (error.isModule) {147 const decoded = api.registry.findMetaError(error.asModule);148 const {method, section} = decoded;149 rej(new Error(`${section}.${method}`));150 } else {151 rej(new Error(error.toString()));152 }153 }154 }155 });156 } catch (e) {157 rej(e);158 }159 });160}161162/**163 * @deprecated use `executeTransaction` instead164 */165export function166submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {167 /* eslint no-async-promise-executor: "off" */168 return new Promise(async (resolve, reject) => {169 try {170 await transaction.signAndSend(sender, ({events = [], status, dispatchError}) => {171 const transactionStatus = getTransactionStatus(events, status);172173 if (transactionStatus === TransactionStatus.Success) {174 resolve(events);175 } else if (transactionStatus === TransactionStatus.Fail) {176 let moduleError = null;177178 if (dispatchError) {179 if (dispatchError.isModule) {180 const modErr = dispatchError.asModule;181 const errorMeta = dispatchError.registry.findMetaError(modErr);182183 moduleError = JSON.stringify(errorMeta, null, 4);184 }185 }186187 console.log(`Something went wrong with transaction. Status: ${status}\nModule error: ${moduleError}`);188 reject(events);189 }190 });191 } catch (e) {192 console.log('Error: ', e);193 reject(e);194 }195 });196}197198export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {199 console.error = () => {};200 console.log = () => {};201202 /* eslint no-async-promise-executor: "off" */203 return new Promise<EventRecord[]>(async function(res, rej) {204 const resolve = (rec: EventRecord[]) => {205 setTimeout(() => {206 res(rec);207 });208 };209 const reject = (errror: any) => {210 setTimeout(() => {211 rej(errror);212 });213 };214 try {215 await transaction.signAndSend(sender, ({events = [], status}) => {216 const transactionStatus = getTransactionStatus(events, status);217218 // console.log('transactionStatus', transactionStatus, 'events', events);219220 if (transactionStatus === TransactionStatus.Success) {221 resolve(events);222 } else if (transactionStatus === TransactionStatus.Fail) {223 reject(events);224 }225 });226 } catch (e) {227 reject(e);228 }229 });230}tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -217,7 +217,8 @@
const collection = helper.nft.getCollectionObject(collectionId);
const data = (await collection.getData())!;
- expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);
+ // Parallel test safety
+ expect(collectionCountAfter - collectionCountBefore).to.be.gte(1);
expect(collectionId).to.be.eq(collectionCountAfter);
expect(data.name).to.be.eq(name);
expect(data.description).to.be.eq(description);
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -278,6 +278,7 @@
}
async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
+ if(!wsEndpoint) throw new Error('wsEndpoint was not set');
const wsProvider = new WsProvider(wsEndpoint);
this.api = new ApiPromise({
provider: wsProvider,
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -492,6 +492,7 @@
}
static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {
+ if(!wsEndpoint) throw new Error('wsEndpoint was not set');
const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});
await api.isReady;
@@ -507,6 +508,7 @@
network: TNetworks;
}> {
if(typeof network === 'undefined' || network === null) network = 'opal';
+ if(!wsEndpoint) throw new Error('wsEndpoint was not set');
const supportedRPC = {
opal: {
unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,