@polkadot/types/interfaces#DispatchError TypeScript Examples

The following examples show how to use @polkadot/types/interfaces#DispatchError. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: block.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
export function mapExtrinsics(
  extrinsics: Extrinsic[] | any,
  records: FrameSystemEventRecord[] | any,
  fees?: RuntimeDispatchInfo[] | any
): TxWithEventAndFee[] {
  return extrinsics.map((extrinsic, index): TxWithEventAndFee => {
    let dispatchError: DispatchError | undefined;
    let dispatchInfo: DispatchInfo | undefined;

    const events = records
      .filter(({ phase }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(index))
      .map(({ event }) => {
        if (event.section === "system") {
          if (event.method === "ExtrinsicSuccess") {
            dispatchInfo = event.data[0] as any as DispatchInfo;
          } else if (event.method === "ExtrinsicFailed") {
            dispatchError = event.data[0] as any as DispatchError;
            dispatchInfo = event.data[1] as any as DispatchInfo;
          }
        }

        return event as any;
      });

    return { dispatchError, dispatchInfo, events, extrinsic, fee: fees ? fees[index] : undefined };
  });
}
Example #2
Source File: Queue.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function extractEvents (result?: SubmittableResult): ActionStatus[] {
  return mergeStatus(
    ((result && result.events) || [])
      // filter events handled globally, or those we are not interested in, these are
      // handled by the global overview, so don't add them here
      .filter((record): boolean => !!record.event && record.event.section !== 'democracy')
      .map(({ event: { data, method, section } }): ActionStatusPartial => {
        if (section === 'system' && method === 'ExtrinsicFailed') {
          const [dispatchError] = data as unknown as ITuple<[DispatchError]>;
          let message = dispatchError.type;

          if (dispatchError.isModule) {
            try {
              const mod = dispatchError.asModule;
              const error = dispatchError.registry.findMetaError(mod);

              message = `${error.section}.${error.name}`;
            } catch (error) {
              // swallow
            }
          }

          return {
            action: `${section}.${method}`,
            message,
            status: 'error'
          };
        } else if (section === 'contracts') {
          if (method === 'ContractExecution' && data.length === 2) {
            // see if we have info for this contract
            const [accountId, encoded] = data;

            try {
              const abi = getContractAbi(accountId.toString());

              if (abi) {
                const decoded = abi.decodeEvent(encoded as Bytes);

                return {
                  action: decoded.event.identifier,
                  message: 'contract event',
                  status: 'event'
                };
              }
            } catch (error) {
              // ABI mismatch?
              console.error(error);
            }
          } else if (method === 'Evicted') {
            return {
              action: `${section}.${method}`,
              message: 'contract evicted',
              status: 'error'
            };
          }
        }

        return {
          action: `${section}.${method}`,
          message: EVENT_MESSAGE,
          status: 'event'
        };
      })
  );
}
Example #3
Source File: DispatchError.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function isModuleError (value?: ModuleErrorDefault): value is DispatchError {
  return !!value?.isModule;
}
Example #4
Source File: DispatchError.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function ErrorDisplay (props: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const [{ details, type }, setDetails] = useState<Details>({});

  useEffect((): void => {
    const { value } = props.defaultValue || {};

    if (isModuleError(value as ModuleErrorDefault)) {
      try {
        const mod = (value as DispatchError).asModule;
        const { documentation, name, section } = mod.registry.findMetaError(mod);

        return setDetails({
          details: documentation.join(', '),
          type: `${section}.${name}`
        });
      } catch (error) {
        // Errors may not actually be exposed, in this case, just return the default representation
        console.error(error);
      }
    }

    setDetails({ details: null });
  }, [props.defaultValue]);

  if (!props.isDisabled || !details) {
    return <Unknown {...props} />;
  }

  return (
    <Static {...props}>
      <Input
        className='full'
        isDisabled
        label={t<string>('type')}
        value={type}
      />
      {details && (
        <Input
          className='full'
          isDisabled
          label={t<string>('details')}
          value={details}
        />
      )}
    </Static>
  );
}
Example #5
Source File: keyring.ts    From sdk with Apache License 2.0 5 votes vote down vote up
function _extractEvents(api: ApiPromise, result: SubmittableResult) {
  if (!result || !result.events) {
    return {};
  }

  let success = false;
  let error: DispatchError["type"] = "";
  result.events
    .filter((event) => !!event.event)
    .map(({ event: { data, method, section } }) => {
      if (section === "system" && method === "ExtrinsicFailed") {
        const [dispatchError] = (data as unknown) as ITuple<[DispatchError]>;
        let message = dispatchError.type;

        if (dispatchError.isModule) {
          try {
            const mod = dispatchError.asModule;
            const err = api.registry.findMetaError(new Uint8Array([mod.index.toNumber(), mod.error.toNumber()]));

            message = `${err.section}.${err.name}`;
          } catch (error) {
            // swallow error
          }
        }
        (<any>window).send("txUpdateEvent", {
          title: `${section}.${method}`,
          message,
        });
        error = message;
      } else {
        (<any>window).send("txUpdateEvent", {
          title: `${section}.${method}`,
          message: "ok",
        });
        if (section == "system" && method == "ExtrinsicSuccess") {
          success = true;
        }
      }
    });
  return { success, error };
}
Example #6
Source File: Queue.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function extractEvents(result?: SubmittableResult): ActionStatus[] {
  return mergeStatus(
    ((result && result.events) || [])
      // filter events handled globally, or those we are not interested in, these are
      // handled by the global overview, so don't add them here
      .filter((record): boolean => !!record.event && record.event.section !== 'democracy')
      // eslint-disable-next-line complexity
      .map(({ event: { data, method, section } }): ActionStatusPartial => {
        if (section === 'system' && method === 'ExtrinsicFailed') {
          const [dispatchError] = data as unknown as ITuple<[DispatchError]>;
          let message: string = dispatchError.type;

          if (dispatchError.isModule) {
            try {
              const mod = dispatchError.asModule;
              const error = dispatchError.registry.findMetaError(mod);

              message = `${error.section}.${error.name}`;
            } catch (error) {
              // swallow
            }
          } else if (dispatchError.isToken) {
            message = `${dispatchError.type}.${dispatchError.asToken.type}`;
          }

          return {
            action: `${section}.${method}`,
            message,
            status: 'error',
          };
        } else if (section === 'contracts') {
          // eslint-disable-next-line no-magic-numbers
          if (method === 'ContractExecution' && data.length === 2) {
            // see if we have info for this contract
            const [accountId, encoded] = data;

            try {
              const abi = getContractAbi(accountId.toString());

              if (abi) {
                const decoded = abi.decodeEvent(encoded as Bytes);

                return {
                  action: decoded.event.identifier,
                  message: 'contract event',
                  status: 'event',
                };
              }
            } catch (error) {
              // ABI mismatch?
              console.error(error);
            }
          } else if (method === 'Evicted') {
            return {
              action: `${section}.${method}`,
              message: 'contract evicted',
              status: 'error',
            };
          }
        }

        return {
          action: `${section}.${method}`,
          message: EVENT_MESSAGE,
          status: 'event',
        };
      })
  );
}
Example #7
Source File: DispatchError.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function isDispatchError(value?: unknown): value is DispatchError {
  return !!(value && ((value as DispatchError).isModule || (value as DispatchError).isToken));
}
Example #8
Source File: shared.ts    From commonwealth with GNU General Public License v3.0 4 votes vote down vote up
public createTXModalData(
    author: SubstrateAccount,
    txFunc: (api: ApiPromise) => SubmittableExtrinsic<'promise'>,
    txName: string,
    objName: string,
    cb?: (success: boolean) => void, // TODO: remove this argument
  ): ITXModalData {
    // TODO: check if author has funds for tx fee
    const events = new EventEmitter();
    return {
      author,
      txType: txName,
      cb,
      txData: {
        events,
        unsignedData: async (): Promise<ISubstrateTXData> => {
          const txHex = txFunc(this.api).method.toHex();
          const nonce = this.api.query.system.accountNonce
            ? await this.api.query.system.accountNonce(author.address)
            : (await this.api.query.system.account(author.address)).nonce;
          const genesisHash = this.api.genesisHash.toHex();
          return {
            call: txHex,
            nonce: (+nonce).toString(),
            blockHash: genesisHash,
            isEd25519: author.isEd25519,
          };
        },
        transact: (hexTxOrAddress?: string, signer?: Signer): void => {
          let unsubscribe: Promise<VoidFn>;
          const txResultHandler = (result: SubmittableResult) => {
            const status = result.status;
            if (status.isReady) {
              console.log(`Pending ${txName}: "${objName}"`);
              events.emit(TransactionStatus.Ready.toString(), {});
            } else if (status.isFinalized || status.isInBlock) {
              for (const e of result.events) {
                if (this.api.events.system.ExtrinsicSuccess.is(e.event)) {
                  notifySuccess(`Confirmed ${txName}`);
                  events.emit(TransactionStatus.Success.toString(), {
                    hash: status.isFinalized ? status.asFinalized.toHex() : status.asInBlock.toHex(),
                    blocknum: this.app.chain.block.height,
                    timestamp: this.app.chain.block.lastTime,
                  });
                  if (unsubscribe) unsubscribe.then((u) => u());
                } else if (this.api.events.system.ExtrinsicFailed.is(e.event)) {
                  const errorData = e.event.data[0] as unknown as DispatchError;
                  let errorInfo;
                  if (errorData.isModule) {
                    const decoded = this.registry.findMetaError(errorData.asModule);
                    const { docs, method, section } = decoded;
                    errorInfo = `${section}.${method}: ${docs.join(' ')}`;
                  } else if (errorData.isBadOrigin) {
                    errorInfo = 'TX Error: invalid sender origin';
                  } else if (errorData.isCannotLookup) {
                    errorInfo = 'TX Error: cannot lookup call';
                  } else {
                    errorInfo = 'TX Error: unknown';
                  }
                  console.error(errorInfo);
                  notifyError(`Failed ${txName}: "${objName}"`);
                  events.emit(TransactionStatus.Failed.toString(), {
                    hash: status.isFinalized ? status.asFinalized.toHex() : status.asInBlock.toHex(),
                    blocknum: this.app.chain.block.height,
                    timestamp: this.app.chain.block.lastTime,
                    err: errorInfo,
                  });
                  if (unsubscribe) unsubscribe.then((u) => u());
                }
              }
            }
          };
          try {
            if (signer) {
              this.api.setSigner(signer);
              unsubscribe = txFunc(this.api).signAndSend(hexTxOrAddress, txResultHandler);
            } else if (hexTxOrAddress) {
              unsubscribe = this.api.tx(hexTxOrAddress).send(txResultHandler);
            } else {
              throw new Error('no signer found');
            }
          } catch (err) {
            if (err.message.indexOf('1014: Priority is too low') !== -1) {
              notifyError('Another transaction is already queued for processing');
            } else {
              notifyError(err.toString());
            }
            m.redraw();
            events.emit(TransactionStatus.Error.toString(), { err: err.toString() });
          }
        },
      }
    };
  }