difftreelog
fix playgrounds should know about CheckMaintenance
in: master
1 file changed
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';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 appPromotion: defs.appPromotion.rpc,48 rmrk: defs.rmrk.rpc,49 eth: {50 feeHistory: {51 description: 'Dummy',52 params: [],53 type: 'u8',54 },55 maxPriorityFeePerGas: {56 description: 'Dummy',57 params: [],58 type: 'u8',59 },60 },61 },62 };63}6465export async function getApiConnection(settings: ApiOptions | undefined = undefined): Promise<ApiPromise> {66 settings = settings || defaultApiOptions();67 const api = new ApiPromise(settings);6869 if (api) {70 await api.isReadyOrError;71 }7273 return api;74}7576export default async function usingApi<T = void>(action: (api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {77 settings = settings || defaultApiOptions();78 const api: ApiPromise = new ApiPromise(settings);79 let result: T = null as unknown as T;8081 const silentConsole = new SilentConsole();82 silentConsole.enable();8384 try {85 await promisifySubstrate(api, async () => {86 if (api) {87 await api.isReadyOrError;88 const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;89 const privateKeyWrapper = (account: string) => privateKey(account, Number(ss58Format));90 result = await action(api, privateKeyWrapper);91 }92 })();93 } finally {94 await api.disconnect();95 silentConsole.disable();96 }97 return result as T;98}99100enum TransactionStatus {101 Success,102 Fail,103 NotReady104}105106function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {107 if (status.isReady) {108 return TransactionStatus.NotReady;109 }110 if (status.isBroadcast) {111 return TransactionStatus.NotReady;112 }113 if (status.isRetracted) {114 return TransactionStatus.NotReady;115 }116 if (status.isInBlock || status.isFinalized) {117 if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {118 return TransactionStatus.Fail;119 }120 if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {121 return TransactionStatus.Success;122 }123 }124125 return TransactionStatus.Fail;126}127128export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {129 return new Promise(async (res, rej) => {130 try {131 await transaction.signAndSend(sender, ({events, status}) => {132 if (!status.isInBlock && !status.isFinalized) return;133 for (const {event} of events) {134 if (api.events.system.ExtrinsicSuccess.is(event)) {135 res(events);136 } else if (api.events.system.ExtrinsicFailed.is(event)) {137 const {data: [error]} = event;138 if (error.isModule) {139 const decoded = api.registry.findMetaError(error.asModule);140 const {method, section} = decoded;141 rej(new Error(`${section}.${method}`));142 } else {143 rej(new Error(error.toString()));144 }145 }146 }147 });148 } catch (e) {149 rej(e);150 }151 });152}153154/**155 * @deprecated use `executeTransaction` instead156 */157export function158submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {159 /* eslint no-async-promise-executor: "off" */160 return new Promise(async (resolve, reject) => {161 try {162 await transaction.signAndSend(sender, ({events = [], status, dispatchError}) => {163 const transactionStatus = getTransactionStatus(events, status);164165 if (transactionStatus === TransactionStatus.Success) {166 resolve(events);167 } else if (transactionStatus === TransactionStatus.Fail) {168 let moduleError = null;169170 if (dispatchError) {171 if (dispatchError.isModule) {172 const modErr = dispatchError.asModule;173 const errorMeta = dispatchError.registry.findMetaError(modErr);174175 moduleError = JSON.stringify(errorMeta, null, 4);176 }177 }178179 console.log(`Something went wrong with transaction. Status: ${status}\nModule error: ${moduleError}`);180 reject(events);181 }182 });183 } catch (e) {184 console.log('Error: ', e);185 reject(e);186 }187 });188}189190export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {191 console.error = () => {};192 console.log = () => {};193194 /* eslint no-async-promise-executor: "off" */195 return new Promise<EventRecord[]>(async function(res, rej) {196 const resolve = (rec: EventRecord[]) => {197 setTimeout(() => {198 res(rec);199 });200 };201 const reject = (errror: any) => {202 setTimeout(() => {203 rej(errror);204 });205 };206 try {207 await transaction.signAndSend(sender, ({events = [], status}) => {208 const transactionStatus = getTransactionStatus(events, status);209210 // console.log('transactionStatus', transactionStatus, 'events', events);211212 if (transactionStatus === TransactionStatus.Success) {213 resolve(events);214 } else if (transactionStatus === TransactionStatus.Fail) {215 reject(events);216 }217 });218 } catch (e) {219 reject(e);220 }221 });222}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 FakeTransactionFinalizer: {45 extrinsic: {},46 payload: {},47 },48 },49 rpc: {50 unique: defs.unique.rpc,51 appPromotion: defs.appPromotion.rpc,52 rmrk: defs.rmrk.rpc,53 eth: {54 feeHistory: {55 description: 'Dummy',56 params: [],57 type: 'u8',58 },59 maxPriorityFeePerGas: {60 description: 'Dummy',61 params: [],62 type: 'u8',63 },64 },65 },66 };67}6869export async function getApiConnection(settings: ApiOptions | undefined = undefined): Promise<ApiPromise> {70 settings = settings || defaultApiOptions();71 const api = new ApiPromise(settings);7273 if (api) {74 await api.isReadyOrError;75 }7677 return api;78}7980export default async function usingApi<T = void>(action: (api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {81 settings = settings || defaultApiOptions();82 const api: ApiPromise = new ApiPromise(settings);83 let result: T = null as unknown as T;8485 const silentConsole = new SilentConsole();86 silentConsole.enable();8788 try {89 await promisifySubstrate(api, async () => {90 if (api) {91 await api.isReadyOrError;92 const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;93 const privateKeyWrapper = (account: string) => privateKey(account, Number(ss58Format));94 result = await action(api, privateKeyWrapper);95 }96 })();97 } finally {98 await api.disconnect();99 silentConsole.disable();100 }101 return result as T;102}103104enum TransactionStatus {105 Success,106 Fail,107 NotReady108}109110function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {111 if (status.isReady) {112 return TransactionStatus.NotReady;113 }114 if (status.isBroadcast) {115 return TransactionStatus.NotReady;116 }117 if (status.isRetracted) {118 return TransactionStatus.NotReady;119 }120 if (status.isInBlock || status.isFinalized) {121 if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {122 return TransactionStatus.Fail;123 }124 if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {125 return TransactionStatus.Success;126 }127 }128129 return TransactionStatus.Fail;130}131132export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {133 return new Promise(async (res, rej) => {134 try {135 await transaction.signAndSend(sender, ({events, status}) => {136 if (!status.isInBlock && !status.isFinalized) return;137 for (const {event} of events) {138 if (api.events.system.ExtrinsicSuccess.is(event)) {139 res(events);140 } else if (api.events.system.ExtrinsicFailed.is(event)) {141 const {data: [error]} = event;142 if (error.isModule) {143 const decoded = api.registry.findMetaError(error.asModule);144 const {method, section} = decoded;145 rej(new Error(`${section}.${method}`));146 } else {147 rej(new Error(error.toString()));148 }149 }150 }151 });152 } catch (e) {153 rej(e);154 }155 });156}157158/**159 * @deprecated use `executeTransaction` instead160 */161export function162submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {163 /* eslint no-async-promise-executor: "off" */164 return new Promise(async (resolve, reject) => {165 try {166 await transaction.signAndSend(sender, ({events = [], status, dispatchError}) => {167 const transactionStatus = getTransactionStatus(events, status);168169 if (transactionStatus === TransactionStatus.Success) {170 resolve(events);171 } else if (transactionStatus === TransactionStatus.Fail) {172 let moduleError = null;173174 if (dispatchError) {175 if (dispatchError.isModule) {176 const modErr = dispatchError.asModule;177 const errorMeta = dispatchError.registry.findMetaError(modErr);178179 moduleError = JSON.stringify(errorMeta, null, 4);180 }181 }182183 console.log(`Something went wrong with transaction. Status: ${status}\nModule error: ${moduleError}`);184 reject(events);185 }186 });187 } catch (e) {188 console.log('Error: ', e);189 reject(e);190 }191 });192}193194export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {195 console.error = () => {};196 console.log = () => {};197198 /* eslint no-async-promise-executor: "off" */199 return new Promise<EventRecord[]>(async function(res, rej) {200 const resolve = (rec: EventRecord[]) => {201 setTimeout(() => {202 res(rec);203 });204 };205 const reject = (errror: any) => {206 setTimeout(() => {207 rej(errror);208 });209 };210 try {211 await transaction.signAndSend(sender, ({events = [], status}) => {212 const transactionStatus = getTransactionStatus(events, status);213214 // console.log('transactionStatus', transactionStatus, 'events', events);215216 if (transactionStatus === TransactionStatus.Success) {217 resolve(events);218 } else if (transactionStatus === TransactionStatus.Fail) {219 reject(events);220 }221 });222 } catch (e) {223 reject(e);224 }225 });226}