Skip to content

Instantly share code, notes, and snippets.

@spalladino
Created September 11, 2020 22:38
Show Gist options
  • Save spalladino/7bce4a27626fc3327731f3ddb9f7587f to your computer and use it in GitHub Desktop.
Save spalladino/7bce4a27626fc3327731f3ddb9f7587f 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