Skip to content

Instantly share code, notes, and snippets.

@mariano-aguero
Forked from spalladino/revert.ts
Created September 30, 2020 17:01
Show Gist options
  • Save mariano-aguero/19ef71e4dddb4a9c7b2d2a5489529264 to your computer and use it in GitHub Desktop.
Save mariano-aguero/19ef71e4dddb4a9c7b2d2a5489529264 to your computer and use it in GitHub Desktop.
Get the revert reason before sending an Ethereum transaction if the transaction would fail
export async function tryGetRevertReason(to: string, from: string, data: string): Promise<string | undefined> {
const provider = ethers.getDefaultProvider();
const tx = { to, from, data };
try {
await provider.estimateGas(tx);
} catch {
const value = await provider.call(tx);
return hexDataLength(value) % 32 === 4 && hexDataSlice(value, 0, 4) === '0x08c379a0'
? defaultAbiCoder.decode(['string'], hexDataSlice(value, 4))
: undefined;
}
return undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment