git.delta.rocks / unique-network / refs/commits / 05870fcbad39

difftreelog

feat(ss58Format) Added ss58Format for usingApi() and wrapp keyring into function

h3lpkey2022-06-01parent: #fb4beb0.patch.diff
in: master

3 files changed

modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -127,14 +127,14 @@
   expect(result.success).to.be.true;
 }
 
-export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
+export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper?: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
   let i: any = it;
   if (opts.only) i = i.only;
   else if (opts.skip) i = i.skip;
   i(name, async () => {
-    await usingApi(async api => {
+    await usingApi(async (api, privateKeyWrapper) => {
       await usingWeb3(async web3 => {
-        await cb({api, web3});
+        await cb({api, web3, privateKeyWrapper});
       });
     });
   });
modifiedtests/src/substrate/privateKey.tsdiffbeforeafterboth
--- a/tests/src/substrate/privateKey.ts
+++ b/tests/src/substrate/privateKey.ts
@@ -19,8 +19,8 @@
 
 // WARNING: the WASM interface must be initialized before this function is called. 
 // Use either `usingApi`, or `cryptoWaitReady` for consistency.
-export default function privateKey(account: string): IKeyringPair {
-  const keyring = new Keyring({type: 'sr25519'});
+export default function privateKey(account: string, ss58Format?: number): IKeyringPair {
+  const keyring = new Keyring({ss58Format, type: 'sr25519'});
 
   return keyring.addFromUri(account);
 }
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
before · tests/src/substrate/substrate-api.ts
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 '../interfaces/augment-api-events';18import {WsProvider, ApiPromise} from '@polkadot/api';19import {EventRecord} from '@polkadot/types/interfaces/system/types';20import {ExtrinsicStatus} from '@polkadot/types/interfaces/author/types';21import {IKeyringPair} from '@polkadot/types/types';2223import config from '../config';24import promisifySubstrate from './promisify-substrate';25import {ApiOptions, SubmittableExtrinsic, ApiTypes} from '@polkadot/api/types';26import * as defs from '../interfaces/definitions';272829function defaultApiOptions(): ApiOptions {30  const wsProvider = new WsProvider(config.substrateUrl);31  return {32    provider: wsProvider, signedExtensions: {33      ContractHelpers: {34        extrinsic: {},35        payload: {},36      },37      FakeTransactionFinalizer: {38        extrinsic: {},39        payload: {},40      },41    },42    rpc: {43      unique: defs.unique.rpc,44      // TODO free RMRK! rmrk: defs.rmrk.rpc,45      eth: {46        feeHistory: {47          description: 'Dummy',48          params: [],49          type: 'u8',50        },51        maxPriorityFeePerGas: {52          description: 'Dummy',53          params: [],54          type: 'u8',55        },56      },57    },58  };59}6061export default async function usingApi<T = void>(action: (api: ApiPromise) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {62  settings = settings || defaultApiOptions();63  const api: ApiPromise = new ApiPromise(settings);64  let result: T = null as unknown as T;6566  // TODO: Remove, this is temporary: Filter unneeded API output67  // (Jaco promised it will be removed in the next version)68  const consoleErr = console.error;69  const consoleLog = console.log;70  const consoleWarn = console.warn;7172  const outFn = (printer: any) => (...args: any[]) => {73    for (const arg of args) {74      if (typeof arg !== 'string')75        continue;76      if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))77        return;78    }79    printer(...args);80  };8182  console.error = outFn(consoleErr.bind(console));83  console.log = outFn(consoleLog.bind(console));84  console.warn = outFn(consoleWarn.bind(console));8586  try {87    await promisifySubstrate(api, async () => {88      if (api) {89        await api.isReadyOrError;90        result = await action(api);91      }92    })();93  } finally {94    await api.disconnect();95    console.error = consoleErr;96    console.log = consoleLog;97    console.warn = consoleWarn;98  }99  return result as T;100}101102enum TransactionStatus {103  Success,104  Fail,105  NotReady106}107108function getTransactionStatus(events: EventRecord[], status: ExtrinsicStatus): TransactionStatus {109  if (status.isReady) {110    return TransactionStatus.NotReady;111  }112  if (status.isBroadcast) {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}) => {159        const transactionStatus = getTransactionStatus(events, status);160161        if (transactionStatus === TransactionStatus.Success) {162          resolve(events);163        } else if (transactionStatus === TransactionStatus.Fail) {164          console.log(`Something went wrong with transaction. Status: ${status}`);165          reject(events);166        }167      });168    } catch (e) {169      console.log('Error: ', e);170      reject(e);171    }172  });173}174175export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {176  console.error = () => {};177  console.log = () => {};178179  /* eslint no-async-promise-executor: "off" */180  return new Promise<EventRecord[]>(async function(res, rej) {181    const resolve = (rec: EventRecord[]) => {182      setTimeout(() => {183        res(rec);184      });185    };186    const reject = (errror: any) => {187      setTimeout(() => {188        rej(errror);189      });190    };191    try {192      await transaction.signAndSend(sender, ({events = [], status}) => {193        const transactionStatus = getTransactionStatus(events, status);194195        // console.log('transactionStatus', transactionStatus, 'events', events);196197        if (transactionStatus === TransactionStatus.Success) {198          resolve(events);199        } else if (transactionStatus === TransactionStatus.Fail) {200          reject(events);201        }202      });203    } catch (e) {204      reject(e);205    }206  });207}
after · tests/src/substrate/substrate-api.ts
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 '../interfaces/augment-api-events';18import {WsProvider, ApiPromise} from '@polkadot/api';19import {EventRecord} from '@polkadot/types/interfaces/system/types';20import {ExtrinsicStatus} from '@polkadot/types/interfaces/author/types';21import {IKeyringPair} from '@polkadot/types/types';2223import config from '../config';24import promisifySubstrate from './promisify-substrate';25import {ApiOptions, SubmittableExtrinsic, ApiTypes} from '@polkadot/api/types';26import * as defs from '../interfaces/definitions';27import privateKey from './privateKey';282930function 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      // TODO free RMRK! 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 default async function usingApi<T = void>(action: (api: ApiPromise, privateKeyWrapper?: (account: string) => IKeyringPair) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {63  settings = settings || defaultApiOptions();64  const api: ApiPromise = new ApiPromise(settings);65  let result: T = null as unknown as T;6667  // TODO: Remove, this is temporary: Filter unneeded API output68  // (Jaco promised it will be removed in the next version)69  const consoleErr = console.error;70  const consoleLog = console.log;71  const consoleWarn = console.warn;7273  const outFn = (printer: any) => (...args: any[]) => {74    for (const arg of args) {75      if (typeof arg !== 'string')76        continue;77      if (arg.includes('1000:: Normal connection closure' || arg === 'Normal connection closure'))78        return;79    }80    printer(...args);81  };8283  console.error = outFn(consoleErr.bind(console));84  console.log = outFn(consoleLog.bind(console));85  console.warn = outFn(consoleWarn.bind(console));8687  try {88    await promisifySubstrate(api, async () => {89      if (api) {90        await api.isReadyOrError;91        const chainProperties = api.registry.getChainProperties();92        if (chainProperties) {93          const ss58Format = (chainProperties).toHuman().ss58Format;94          const privateKeyWrapper = (account: string) => privateKey(account, Number(ss58Format));95          result = await action(api, privateKeyWrapper);96        } 97      }98    })();99  } finally {100    await api.disconnect();101    console.error = consoleErr;102    console.log = consoleLog;103    console.warn = consoleWarn;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.isInBlock || status.isFinalized) {122    if(events.filter(e => e.event.data.method === 'ExtrinsicFailed').length > 0) {123      return TransactionStatus.Fail;124    }125    if(events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {126      return TransactionStatus.Success;127    }128  }129130  return TransactionStatus.Fail;131}132133export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {134  return new Promise(async (res, rej) => {135    try {136      await transaction.signAndSend(sender, ({events, status}) => {137        if (!status.isInBlock && !status.isFinalized) return;138        for (const {event} of events) {139          if (api.events.system.ExtrinsicSuccess.is(event)) {140            res(events);141          } else if (api.events.system.ExtrinsicFailed.is(event)) {142            const {data: [error]} = event;143            if (error.isModule) {144              const decoded = api.registry.findMetaError(error.asModule);145              const {method, section} = decoded;146              rej(new Error(`${section}.${method}`));147            } else {148              rej(new Error(error.toString()));149            }150          }151        }152      });153    } catch (e) {154      rej(e);155    }156  });157}158159export function160submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {161  /* eslint no-async-promise-executor: "off" */162  return new Promise(async (resolve, reject) => {163    try {164      await transaction.signAndSend(sender, ({events = [], status}) => {165        const transactionStatus = getTransactionStatus(events, status);166167        if (transactionStatus === TransactionStatus.Success) {168          resolve(events);169        } else if (transactionStatus === TransactionStatus.Fail) {170          console.log(`Something went wrong with transaction. Status: ${status}`);171          reject(events);172        }173      });174    } catch (e) {175      console.log('Error: ', e);176      reject(e);177    }178  });179}180181export function submitTransactionExpectFailAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {182  console.error = () => {};183  console.log = () => {};184185  /* eslint no-async-promise-executor: "off" */186  return new Promise<EventRecord[]>(async function(res, rej) {187    const resolve = (rec: EventRecord[]) => {188      setTimeout(() => {189        res(rec);190      });191    };192    const reject = (errror: any) => {193      setTimeout(() => {194        rej(errror);195      });196    };197    try {198      await transaction.signAndSend(sender, ({events = [], status}) => {199        const transactionStatus = getTransactionStatus(events, status);200201        // console.log('transactionStatus', transactionStatus, 'events', events);202203        if (transactionStatus === TransactionStatus.Success) {204          resolve(events);205        } else if (transactionStatus === TransactionStatus.Fail) {206          reject(events);207        }208      });209    } catch (e) {210      reject(e);211    }212  });213}