git.delta.rocks / unique-network / refs/commits / 4bcecc1a2d37

difftreelog

source

tests/src/substrate/substrate-api.ts6.8 KiBsourcehistory
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.isRetracted) {113    return TransactionStatus.NotReady;114  }115  if (status.isInBlock || status.isFinalized) {116    if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {117      return TransactionStatus.Fail;118    }119    if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {120      return TransactionStatus.Success;121    }122  }123124  return TransactionStatus.Fail;125}126127export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {128  return new Promise(async (res, rej) => {129    try {130      await transaction.signAndSend(sender, ({events, status}) => {131        if (!status.isInBlock && !status.isFinalized) return;132        for (const {event} of events) {133          if (api.events.system.ExtrinsicSuccess.is(event)) {134            res(events);135          } else if (api.events.system.ExtrinsicFailed.is(event)) {136            const {data: [error]} = event;137            if (error.isModule) {138              const decoded = api.registry.findMetaError(error.asModule);139              const {method, section} = decoded;140              rej(new Error(`${section}.${method}`));141            } else {142              rej(new Error(error.toString()));143            }144          }145        }146      });147    } catch (e) {148      rej(e);149    }150  });151}152153export function154submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {155  /* eslint no-async-promise-executor: "off" */156  return new Promise(async (resolve, reject) => {157    try {158      await transaction.signAndSend(sender, ({events = [], status, dispatchError}) => {159        const transactionStatus = getTransactionStatus(events, status);160161        if (transactionStatus === TransactionStatus.Success) {162          resolve(events);163        } else if (transactionStatus === TransactionStatus.Fail) {164          let moduleError = null;165166          if (dispatchError) {167            if (dispatchError.isModule) {168              const modErr = dispatchError.asModule;169              const errorMeta = dispatchError.registry.findMetaError(modErr);170171              moduleError = JSON.stringify(errorMeta, null, 4);172            }173          }174175          console.log(`Something went wrong with transaction. Status: ${status}\nModule error: ${moduleError}`);176          reject(events);177        }178      });179    } catch (e) {180      console.log('Error: ', e);181      reject(e);182    }183  });184}185186export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {187  console.error = () => {};188  console.log = () => {};189190  /* eslint no-async-promise-executor: "off" */191  return new Promise<EventRecord[]>(async function(res, rej) {192    const resolve = (rec: EventRecord[]) => {193      setTimeout(() => {194        res(rec);195      });196    };197    const reject = (errror: any) => {198      setTimeout(() => {199        rej(errror);200      });201    };202    try {203      await transaction.signAndSend(sender, ({events = [], status}) => {204        const transactionStatus = getTransactionStatus(events, status);205206        // console.log('transactionStatus', transactionStatus, 'events', events);207208        if (transactionStatus === TransactionStatus.Success) {209          resolve(events);210        } else if (transactionStatus === TransactionStatus.Fail) {211          reject(events);212        }213      });214    } catch (e) {215      reject(e);216    }217  });218}