git.delta.rocks / unique-network / refs/commits / 2df3f6b6e145

difftreelog

source

tests/src/.outdated/substrate/substrate-api.ts7.1 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      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}