---
eip: 838
label: ERC-838
title: ABI specification for REVERT reason string
status: Draft
type: Standards Track
category: ERC
created: 2020-08-20
official: https://eips.ethereum.org/EIPS/eip-838
source: https://github.com/ethereum/ERCs/blob/master/ERCS/erc-838.md
canonical: https://eips.huatuo.xyz/zh/eip-838/
lang: zh
tldr: 一项 Draft 提案：在合约的 JSON ABI 中声明带类型的错误，并以选择器的形式编码到 REVERT 数据中，使客户端能够解码交易失败的原因。
tags: [abi, errors, revert, solidity, draft]
---

# ERC-838: ABI specification for REVERT reason string

> A proposal to extend the ABI specification to include typed errors in the REVERT reason string.

**TL;DR:** 一项 Draft 提案：在合约的 JSON ABI 中声明带类型的错误，并以选择器的形式编码到 REVERT 数据中，使客户端能够解码交易失败的原因。

## 它解决什么问题？

`REVERT` 操作码（[EIP-140](/eip-140/)）让合约可以停止执行、撤销更改，并返回一些解释原因的字节。起初，这些字节唯一的约定是自由格式的字符串。字符串对人来说没问题，但软件无法可靠地据此分支，它无法携带结构化的值，而且较长的消息会消耗 gas。

ERC-838 提议像对待函数和事件一样对待错误：在 ABI 中用名称和带类型的参数声明它们，并在回滚数据中编码**选择器**加参数。这样钱包和库就可以查找该选择器，显示精确的、已解码的错误。

## 它如何运作

- 生成 JSON ABI 的编译器**应当**在函数和事件之外包含错误条目，带有 `"type": "error"`、`name` 和带类型的参数。
- 选择器根据错误的签名计算，方式与公共函数相同。
- 该选择器**必须**出现在回滚数据中，以便客户端查找，后面跟着编码后的参数。
- 这样，高级语言就可以提供用于声明和抛出错误的语法。

规范中提到的可能扩展包括：在错误上使用 NatSpec 的 `@notice` 来提供人类可读的消息，以及在函数的 ABI 条目中列出该函数可能抛出的错误。

该 Draft 将确切的字节格式、设计理由和安全考量留作"待定义"或"需要讨论"。

## 示例代码

提案中的 ABI 条目形式：

```json
{ "type": "error", "name": "InsufficientBalance",
  "arguments": [ { "name": "amount", "type": "uint256" } ] }
```

遵循相同思路的 Solidity 自定义错误在实践中是这样的：

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Vault {
    /// @notice You don't have enough funds to withdraw `amount`.
    error InsufficientBalance(uint256 available, uint256 amount);

    mapping(address => uint256) public balance;

    function withdraw(uint256 amount) external {
        uint256 bal = balance[msg.sender];
        if (bal < amount) revert InsufficientBalance(bal, amount);
        balance[msg.sender] = bal - amount;
        payable(msg.sender).transfer(amount);
    }
}
```

用 ethers v6 在链下解码错误：

```ts
import { Interface } from "ethers";

const iface = new Interface(["error InsufficientBalance(uint256 available, uint256 amount)"]);
const parsed = iface.parseError(revertData);   // revertData: hex string from the failed call
console.log(parsed?.name, parsed?.args);       // "InsufficientBalance", [10n, 25n]
```

## 需要注意

- **该提案仍处于 Draft 状态，从未最终确定。** 它没有具有约束力的字节格式。
- 实际上，生态系统采用了 Solidity 所发布的做法：自定义错误编码为 4 字节选择器加标准 ABI 编码的参数，ABI 条目为 `"type": "error"`，带有 `inputs` 数组（而不是 Draft 中的 `arguments`）。
- 普通的 `require(cond, "msg")` 字符串会被编码为内置的 `Error(string)` 错误，选择器为 `0x08c379a0`。
- [ERC-6093](/eip-6093/) 标准化了代币合约常用的自定义错误名称。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-838
