Skip to content

Instantly share code, notes, and snippets.

@Yuripetusko
Last active May 15, 2024 22:54
Show Gist options
  • Save Yuripetusko/84f75b07adf743b73b6a75763c4bfb59 to your computer and use it in GitHub Desktop.
Save Yuripetusko/84f75b07adf743b73b6a75763c4bfb59 to your computer and use it in GitHub Desktop.
Test
import { mapTxErrorNameToErrorMessage } from './map-tx-error-name-to-error-message';
import { Abi } from 'abitype';
import {
AbiErrorSignatureNotFoundError,
BaseError,
ContractFunctionExecutionError,
ContractFunctionExecutionErrorType,
ContractFunctionRevertedError,
SimulateContractErrorType,
WaitForTransactionReceiptErrorType,
WriteContractErrorType,
decodeErrorResult,
} from 'viem';
export interface ParseEvmTransactionLogArgs<TAbi extends Abi | readonly unknown[]> {
abi: TAbi;
error:
| unknown
| ContractFunctionExecutionErrorType
| SimulateContractErrorType
| WriteContractErrorType
| WaitForTransactionReceiptErrorType
| null;
}
/**
* Tries to find decoded error in the error object, or decodes it with the supplied ABI.
* @param error
* @param abi
*/
export const decodeEvmTransactionErrorResult = <TAbi extends Abi | readonly unknown[]>({
error,
abi,
}: ParseEvmTransactionLogArgs<TAbi>) => {
try {
if (error instanceof BaseError || error instanceof ContractFunctionExecutionError) {
const revertError = error.walk((err) => err instanceof ContractFunctionRevertedError);
if (revertError instanceof ContractFunctionRevertedError) {
const errorName = revertError.data?.errorName ?? '';
if (errorName) {
// This error is already decoded
const decodedError = revertError.data;
return {
error,
decodedError,
message: mapTxErrorNameToErrorMessage(errorName) ?? error.shortMessage ?? error.message,
};
}
}
}
// If error could not be decoded with original abi, let's try to decode it with the supplied ABI
const noSignatureError = (error as BaseError).walk((err) => err instanceof AbiErrorSignatureNotFoundError);
if (noSignatureError instanceof AbiErrorSignatureNotFoundError && noSignatureError?.signature) {
const decodedError = decodeErrorResult({
abi,
data: noSignatureError.signature,
});
return {
decodedError,
error,
message:
mapTxErrorNameToErrorMessage(decodedError.errorName) ??
(error as ContractFunctionRevertedError).shortMessage ??
(error as Error).message,
};
}
return {
error,
decodedError: undefined,
message: (error as ContractFunctionRevertedError).shortMessage ?? (error as Error).message ?? 'Unknown error',
};
} catch (_) {
return {
error,
decodedError: undefined,
message: (error as ContractFunctionRevertedError).shortMessage ?? (error as Error).message ?? 'Unknown error',
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment