difftreelog
test SilentConsole cls instead of multiple decorations
in: master
4 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
@@ -6,7 +6,7 @@
import config from '../../../config';
import {EthUniqueHelper} from './unique.dev';
-import {SilentLogger} from '../../../util/playgrounds/unique.dev';
+import {SilentLogger, SilentConsole} from '../../../util/playgrounds/unique.dev';
export {EthUniqueHelper} from './unique.dev';
@@ -16,25 +16,9 @@
export const expect = chai.expect;
export const usingEthPlaygrounds = async (code: (helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
- // TODO: Remove, this is temporary: Filter unneeded API output
- // (Jaco promised it will be removed in the next version)
- const consoleErr = console.error;
- const consoleLog = console.log;
- const consoleWarn = console.warn;
-
- const outFn = (printer: any) => (...args: any[]) => {
- for (const arg of args) {
- if (typeof arg !== 'string')
- continue;
- if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis: UniqueApi/2, RmrkApi/1') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
- return;
- }
- printer(...args);
- };
+ const silentConsole = new SilentConsole();
+ silentConsole.enable();
- console.error = outFn(consoleErr.bind(console));
- console.log = outFn(consoleLog.bind(console));
- console.warn = outFn(consoleWarn.bind(console));
const helper = new EthUniqueHelper(new SilentLogger());
try {
@@ -47,9 +31,7 @@
finally {
await helper.disconnect();
await helper.disconnectWeb3();
- console.error = consoleErr;
- console.log = consoleLog;
- console.warn = consoleWarn;
+ silentConsole.disable();
}
}
tests/src/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';27282930function defaultApiOptions(): ApiOptions {31 const wsProvider = new WsProvider(config.substrateUrl);32 return {33 provider: wsProvider, signedExtensions: {34 ContractHelpers: {35 extrinsic: {},36 payload: {},37 },38 FakeTransactionFinalizer: {39 extrinsic: {},40 payload: {},41 },42 },43 rpc: {44 unique: defs.unique.rpc,45 rmrk: defs.rmrk.rpc,46 eth: {47 feeHistory: {48 description: 'Dummy',49 params: [],50 type: 'u8',51 },52 maxPriorityFeePerGas: {53 description: 'Dummy',54 params: [],55 type: 'u8',56 },57 },58 },59 };60}6162export async function getApiConnection(settings: ApiOptions | undefined = undefined): Promise<ApiPromise> {63 settings = settings || defaultApiOptions();64 const api = new ApiPromise(settings);6566 if (api) {67 await api.isReadyOrError;68 }6970 return api;71}7273export default async function usingApi<T = void>(action: (api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {74 settings = settings || defaultApiOptions();75 const api: ApiPromise = new ApiPromise(settings);76 let result: T = null as unknown as T;7778 // TODO: Remove, this is temporary: Filter unneeded API output79 // (Jaco promised it will be removed in the next version)80 const consoleErr = console.error;81 const consoleLog = console.log;82 const consoleWarn = console.warn;8384 const outFn = (printer: any) => (...args: any[]) => {85 for (const arg of args) {86 if (typeof arg !== 'string')87 continue;88 if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))89 return;90 }91 printer(...args);92 };9394 console.error = outFn(consoleErr.bind(console));95 console.log = outFn(consoleLog.bind(console));96 console.warn = outFn(consoleWarn.bind(console));9798 try {99 await promisifySubstrate(api, async () => {100 if (api) {101 await api.isReadyOrError;102 const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;103 const privateKeyWrapper = (account: string) => privateKey(account, Number(ss58Format));104 result = await action(api, privateKeyWrapper);105 }106 })();107 } finally {108 await api.disconnect();109 console.error = consoleErr;110 console.log = consoleLog;111 console.warn = consoleWarn;112 }113 return result as T;114}115116enum TransactionStatus {117 Success,118 Fail,119 NotReady120}121122function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {123 if (status.isReady) {124 return TransactionStatus.NotReady;125 }126 if (status.isBroadcast) {127 return TransactionStatus.NotReady;128 }129 if (status.isInBlock || status.isFinalized) {130 if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {131 return TransactionStatus.Fail;132 }133 if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {134 return TransactionStatus.Success;135 }136 }137138 return TransactionStatus.Fail;139}140141export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {142 return new Promise(async (res, rej) => {143 try {144 await transaction.signAndSend(sender, ({events, status}) => {145 if (!status.isInBlock && !status.isFinalized) return;146 for (const {event} of events) {147 if (api.events.system.ExtrinsicSuccess.is(event)) {148 res(events);149 } else if (api.events.system.ExtrinsicFailed.is(event)) {150 const {data: [error]} = event;151 if (error.isModule) {152 const decoded = api.registry.findMetaError(error.asModule);153 const {method, section} = decoded;154 rej(new Error(`${section}.${method}`));155 } else {156 rej(new Error(error.toString()));157 }158 }159 }160 });161 } catch (e) {162 rej(e);163 }164 });165}166167export function168submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {169 /* eslint no-async-promise-executor: "off" */170 return new Promise(async (resolve, reject) => {171 try {172 await transaction.signAndSend(sender, ({events = [], status}) => {173 const transactionStatus = getTransactionStatus(events, status);174175 if (transactionStatus === TransactionStatus.Success) {176 resolve(events);177 } else if (transactionStatus === TransactionStatus.Fail) {178 console.log(`Something went wrong with transaction. Status: ${status}`);179 reject(events);180 }181 });182 } catch (e) {183 console.log('Error: ', e);184 reject(e);185 }186 });187}188189export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {190 console.error = () => {};191 console.log = () => {};192193 /* eslint no-async-promise-executor: "off" */194 return new Promise<EventRecord[]>(async function(res, rej) {195 const resolve = (rec: EventRecord[]) => {196 setTimeout(() => {197 res(rec);198 });199 };200 const reject = (errror: any) => {201 setTimeout(() => {202 rej(errror);203 });204 };205 try {206 await transaction.signAndSend(sender, ({events = [], status}) => {207 const transactionStatus = getTransactionStatus(events, status);208209 // console.log('transactionStatus', transactionStatus, 'events', events);210211 if (transactionStatus === TransactionStatus.Success) {212 resolve(events);213 } else if (transactionStatus === TransactionStatus.Fail) {214 reject(events);215 }216 });217 } catch (e) {218 reject(e);219 }220 });221}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 FakeTransactionFinalizer: {41 extrinsic: {},42 payload: {},43 },44 },45 rpc: {46 unique: defs.unique.rpc,47 rmrk: defs.rmrk.rpc,48 eth: {49 feeHistory: {50 description: 'Dummy',51 params: [],52 type: 'u8',53 },54 maxPriorityFeePerGas: {55 description: 'Dummy',56 params: [],57 type: 'u8',58 },59 },60 },61 };62}6364export async function getApiConnection(settings: ApiOptions | undefined = undefined): Promise<ApiPromise> {65 settings = settings || defaultApiOptions();66 const api = new ApiPromise(settings);6768 if (api) {69 await api.isReadyOrError;70 }7172 return api;73}7475export default async function usingApi<T = void>(action: (api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {76 settings = settings || defaultApiOptions();77 const api: ApiPromise = new ApiPromise(settings);78 let result: T = null as unknown as T;7980 const silentConsole = new SilentConsole();81 silentConsole.enable();8283 try {84 await promisifySubstrate(api, async () => {85 if (api) {86 await api.isReadyOrError;87 const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;88 const privateKeyWrapper = (account: string) => privateKey(account, Number(ss58Format));89 result = await action(api, privateKeyWrapper);90 }91 })();92 } finally {93 await api.disconnect();94 silentConsole.disable();95 }96 return result as T;97}9899enum TransactionStatus {100 Success,101 Fail,102 NotReady103}104105function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {106 if (status.isReady) {107 return TransactionStatus.NotReady;108 }109 if (status.isBroadcast) {110 return TransactionStatus.NotReady;111 }112 if (status.isInBlock || status.isFinalized) {113 if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {114 return TransactionStatus.Fail;115 }116 if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {117 return TransactionStatus.Success;118 }119 }120121 return TransactionStatus.Fail;122}123124export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {125 return new Promise(async (res, rej) => {126 try {127 await transaction.signAndSend(sender, ({events, status}) => {128 if (!status.isInBlock && !status.isFinalized) return;129 for (const {event} of events) {130 if (api.events.system.ExtrinsicSuccess.is(event)) {131 res(events);132 } else if (api.events.system.ExtrinsicFailed.is(event)) {133 const {data: [error]} = event;134 if (error.isModule) {135 const decoded = api.registry.findMetaError(error.asModule);136 const {method, section} = decoded;137 rej(new Error(`${section}.${method}`));138 } else {139 rej(new Error(error.toString()));140 }141 }142 }143 });144 } catch (e) {145 rej(e);146 }147 });148}149150export function151submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {152 /* eslint no-async-promise-executor: "off" */153 return new Promise(async (resolve, reject) => {154 try {155 await transaction.signAndSend(sender, ({events = [], status}) => {156 const transactionStatus = getTransactionStatus(events, status);157158 if (transactionStatus === TransactionStatus.Success) {159 resolve(events);160 } else if (transactionStatus === TransactionStatus.Fail) {161 console.log(`Something went wrong with transaction. Status: ${status}`);162 reject(events);163 }164 });165 } catch (e) {166 console.log('Error: ', e);167 reject(e);168 }169 });170}171172export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {173 console.error = () => {};174 console.log = () => {};175176 /* eslint no-async-promise-executor: "off" */177 return new Promise<EventRecord[]>(async function(res, rej) {178 const resolve = (rec: EventRecord[]) => {179 setTimeout(() => {180 res(rec);181 });182 };183 const reject = (errror: any) => {184 setTimeout(() => {185 rej(errror);186 });187 };188 try {189 await transaction.signAndSend(sender, ({events = [], status}) => {190 const transactionStatus = getTransactionStatus(events, status);191192 // console.log('transactionStatus', transactionStatus, 'events', events);193194 if (transactionStatus === TransactionStatus.Success) {195 resolve(events);196 } else if (transactionStatus === TransactionStatus.Fail) {197 reject(events);198 }199 });200 } catch (e) {201 reject(e);202 }203 });204}tests/src/util/playgrounds/index.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -4,37 +4,13 @@
import {IKeyringPair} from '@polkadot/types/types';
import config from '../../config';
import '../../interfaces/augment-api-events';
-import {DevUniqueHelper} from './unique.dev';
+import {DevUniqueHelper, SilentLogger, SilentConsole} from './unique.dev';
-class SilentLogger {
- log(msg: any, level: any): void { }
- level = {
- ERROR: 'ERROR' as const,
- WARNING: 'WARNING' as const,
- INFO: 'INFO' as const,
- };
-}
export const usingPlaygrounds = async (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
- // TODO: Remove, this is temporary: Filter unneeded API output
- // (Jaco promised it will be removed in the next version)
- const consoleErr = console.error;
- const consoleLog = console.log;
- const consoleWarn = console.warn;
+ const silentConsole = new SilentConsole();
+ silentConsole.enable();
- const outFn = (printer: any) => (...args: any[]) => {
- for (const arg of args) {
- if (typeof arg !== 'string')
- continue;
- if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))
- return;
- }
- printer(...args);
- };
-
- console.error = outFn(consoleErr.bind(console));
- console.log = outFn(consoleLog.bind(console));
- console.warn = outFn(consoleWarn.bind(console));
const helper = new DevUniqueHelper(new SilentLogger());
try {
@@ -45,8 +21,6 @@
}
finally {
await helper.disconnect();
- console.error = consoleErr;
- console.log = consoleLog;
- console.warn = consoleWarn;
+ silentConsole.disable();
}
};
\ No newline at end of file
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -5,10 +5,58 @@
import {UniqueHelper} from './unique';
import {ApiPromise, WsProvider} from '@polkadot/api';
import * as defs from '../../interfaces/definitions';
-import {TSigner} from './types';
import {IKeyringPair} from '@polkadot/types/types';
+export class SilentLogger {
+ log(msg: any, level: any): void { }
+ level = {
+ ERROR: 'ERROR' as const,
+ WARNING: 'WARNING' as const,
+ INFO: 'INFO' as const,
+ };
+}
+
+
+export class SilentConsole {
+ // TODO: Remove, this is temporary: Filter unneeded API output
+ // (Jaco promised it will be removed in the next version)
+ consoleErr: any;
+ consoleLog: any;
+ consoleWarn: any;
+
+ constructor() {
+ this.consoleErr = console.error;
+ this.consoleLog = console.log;
+ this.consoleWarn = console.warn;
+ }
+
+ enable() {
+ const outFn = (printer: any) => (...args: any[]) => {
+ for (const arg of args) {
+ for (const arg of args) {
+ if (typeof arg !== 'string')
+ continue;
+ if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis: UniqueApi/2, RmrkApi/1') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
+ return;
+ }
+ }
+ printer(...args);
+ };
+
+ console.error = outFn(this.consoleErr.bind(console));
+ console.log = outFn(this.consoleLog.bind(console));
+ console.warn = outFn(this.consoleWarn.bind(console));
+ }
+
+ disable() {
+ console.error = this.consoleErr;
+ console.log = this.consoleLog;
+ console.warn = this.consoleWarn;
+ }
+}
+
+
export class DevUniqueHelper extends UniqueHelper {
/**
* Arrange methods for tests