From cb99ebf78aad869e61ec2ca7c48bb25178274ec5 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Thu, 27 Sep 2018 11:21:39 +0200 Subject: Throw revert reasons from contract wrappers --- packages/base-contract/CHANGELOG.json | 4 ++++ packages/base-contract/src/index.ts | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/packages/base-contract/CHANGELOG.json b/packages/base-contract/CHANGELOG.json index fba072011..b97bc00e0 100644 --- a/packages/base-contract/CHANGELOG.json +++ b/packages/base-contract/CHANGELOG.json @@ -5,6 +5,10 @@ { "note": "Change the way we detect BN to work with the newest ethers.js", "pr": 1069 + }, + { + "note": "Add baseContract._throwIfRevertWithReasonCallResult", + "pr": 1069 } ] }, diff --git a/packages/base-contract/src/index.ts b/packages/base-contract/src/index.ts index 90e576c24..538c87431 100644 --- a/packages/base-contract/src/index.ts +++ b/packages/base-contract/src/index.ts @@ -20,6 +20,10 @@ export interface EthersInterfaceByFunctionSignature { [key: string]: ethers.Interface; } +const REVERT_ERROR_SELECTOR = '08c379a0'; +const REVERT_ERROR_SELECTOR_OFFSET = 2; +const REVERT_ERROR_SELECTOR_END = 10; + export class BaseContract { protected _ethersInterfacesByFunctionSignature: EthersInterfaceByFunctionSignature; protected _web3Wrapper: Web3Wrapper; @@ -82,6 +86,15 @@ export class BaseContract { } return txDataWithDefaults; } + protected static _throwIfRevertWithReasonCallResult(rawCallResult: string): void { + if (rawCallResult.slice(REVERT_ERROR_SELECTOR_OFFSET, REVERT_ERROR_SELECTOR_END) === REVERT_ERROR_SELECTOR) { + const revertReason = ethers.utils.defaultAbiCoder.decode( + ['string'], + ethers.utils.hexDataSlice(rawCallResult, 4), + ); + throw new Error(revertReason); + } + } // Throws if the given arguments cannot be safely/correctly encoded based on // the given inputAbi. An argument may not be considered safely encodeable // if it overflows the corresponding Solidity type, there is a bug in the -- cgit