diff --git a/src/wallet/utils/TxError.ts b/src/wallet/utils/TxError.ts new file mode 100644 index 00000000..d1291497 --- /dev/null +++ b/src/wallet/utils/TxError.ts @@ -0,0 +1,31 @@ +// custom class to allow dApps to handle errors in a more user-friendly way +export class TxError extends Error { + private data: any; + + constructor(message: string, data: any = null) { + super(message); + this.data = data; + } + + public static async normalize(promise: Promise): Promise { + try { + return await promise; + } catch (err) { + if (typeof err === "string") { + throw new TxError(err); + } + if (err instanceof Error) { + throw err as TxError; + } + throw new TxError("Unknown error", err); + } + } + + public getMessage(): string { + return this.message; + } + + public getData(): any { + return this.data; + } +} \ No newline at end of file diff --git a/src/wallet/wallets/keplr/KeplrExtension.ts b/src/wallet/wallets/keplr/KeplrExtension.ts index 241f273e..dde4a3fb 100644 --- a/src/wallet/wallets/keplr/KeplrExtension.ts +++ b/src/wallet/wallets/keplr/KeplrExtension.ts @@ -20,6 +20,7 @@ import { SignArbitraryResponse, UnsignedTx, } from "../ConnectedWallet"; +import { TxError } from "cosmes/wallet/utils/TxError"; export class KeplrExtension extends ConnectedWallet { private readonly ext: Keplr; @@ -55,7 +56,7 @@ export class KeplrExtension extends ConnectedWallet { } public async signArbitrary(data: string): Promise { - const res = await this.normaliseError( + const res = await TxError.normalize( this.ext.signArbitrary(this.chainId, this.address, data) ); return { @@ -86,12 +87,12 @@ export class KeplrExtension extends ConnectedWallet { }; let txRaw: TxRaw; if (this.useAmino) { - const { signed, signature } = await this.normaliseError( + const { signed, signature } = await TxError.normalize( this.ext.signAmino(this.chainId, this.address, tx.toStdSignDoc(params)) ); txRaw = tx.toSignedAmino(signed, signature.signature); } else { - const { signed, signature } = await this.normaliseError( + const { signed, signature } = await TxError.normalize( this.ext.signDirect(this.chainId, this.address, tx.toSignDoc(params)) ); txRaw = tx.toSignedDirect(signed, signature.signature); @@ -99,25 +100,4 @@ export class KeplrExtension extends ConnectedWallet { return RpcClient.broadcastTx(this.rpc, txRaw); } - - /** - * Returns the result of the `promise` if it resolves successfully, normalising - * any errors thrown into a standard `Error` instance. - * - * It is best to wrap all wallet API calls with this function as some wallets - * throw raw strings instead of actual `Error` instances. - */ - private async normaliseError(promise: Promise): Promise { - try { - return await promise; - } catch (err) { - if (typeof err === "string") { - throw new Error(err); - } - if (err instanceof Error) { - throw err; - } - throw new Error("Unknown error: " + JSON.stringify(err)); - } - } -} +} \ No newline at end of file