---
eip: 140
label: EIP-140
title: REVERT instruction
status: Final
type: Standards Track
category: Core
created: 2017-02-06
official: https://eips.ethereum.org/EIPS/eip-140
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-140.md
canonical: https://eips.huatuo.xyz/zh/eip-140/
lang: zh
tldr: 新增 REVERT 操作码，它会中止执行并回滚状态，同时退还未使用的 gas，并向调用方返回错误信息。
tags: [evm, opcode, errors, byzantium, core]
---

# EIP-140: REVERT instruction

> The REVERT instruction provides a way to stop execution and revert state changes, without consuming all provided gas and with the ability to return a reason.

**TL;DR:** 新增 REVERT 操作码，它会中止执行并回滚状态，同时退还未使用的 gas，并向调用方返回错误信息。

## 它解决什么问题？

在 Byzantium 硬分叉（2017 年）之前，合约只有两种中止方式：耗尽 gas，或执行无效指令。即使合约只是检查了某个条件并发现为假，这两种方式也都会消耗**全部**剩余 gas，而且都无法说明原因，调用方只能看到"失败"。

EIP-140 增加了一种干净的失败方式：停止、撤销所有状态更改、保留未使用的 gas，并返回一条消息。

## 它如何运作

- 新操作码 `REVERT` 位于 `0xfd`，从栈中取两个值：`memory_offset` 和 `memory_length`。
- 执行停止，当前调用产生的所有状态更改（包括日志）都会被回滚。
- 该内存片段会作为**返回数据**返回给调用方，方式与 `RETURN` 返回数据相同。调用方可以用 [EIP-211](/eip-211/) 中的 `RETURNDATASIZE` / `RETURNDATACOPY` 读取它。
- gas 成本与 `RETURN` 相同：只需为内存付费。剩余的 gas 退还给调用方。
- 发起调用的 `CALL`（或 `CREATE` / `CREATE2`）与任何失败情况一样压入 `0`。对于合约创建，不会部署任何代码。
- 如果 `REVERT` 本身的 gas 不足，或发生栈下溢，则按普通的 out-of-gas 错误处理，消耗全部 gas。

该 EIP 并未定义返回字节的含义。Solidity 对 `require(cond, "msg")` 编码为 `Error(string)`（选择器 `0x08c379a0`），对断言和算术失败编码为 `Panic(uint256)`，对 `revert MyError(...)` 编码为 ABI 编码的自定义错误。

## 示例代码

高级 Solidity 会编译为 `REVERT`：

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

contract Vault {
    error InsufficientBalance(uint256 have, uint256 want);
    mapping(address => uint256) public balance;

    function withdraw(uint256 amount) external {
        uint256 b = balance[msg.sender];
        if (b < amount) revert InsufficientBalance(b, amount); // 以 ABI 编码的错误执行 REVERT
        balance[msg.sender] = b - amount;
        payable(msg.sender).transfer(amount);
    }
}
```

在内联汇编中使用原始操作码，返回 32 字节的数据：

```solidity
assembly {
    mstore(0, 0x2a)   // 把 42 放入内存
    revert(0, 32)     // REVERT(offset=0, length=32)
}
```

在链下解码原因（ethers v6）：

```ts
try {
  await vault.withdraw(10n ** 18n);
} catch (e: any) {
  console.log(e.revert?.name, e.revert?.args); // "InsufficientBalance", [have, want]
}
```

## 需要注意

- `REVERT` 并不免费。到那一刻为止已用掉的 gas 仍需支付。与旧的无效操作码方式不同，只有*剩余*的 gas 会被退还。
- 0.8.0 之前的 Solidity 中，`assert` 失败会编译为无效操作码 `0xfe` 并耗尽所有 gas。自 0.8.0 起，它们使用带有 `Panic(uint256)` 的 `REVERT`。
- 原因的返回数据格式曾在 [EIP-838](/eip-838/) 中单独提出，该提案至今仍是 Draft。`Error(string)` 这一约定由 Solidity 定义，而不是由某个 EIP 定义。
- 与 [EIP-211](/eip-211/) 一起在 Byzantium 中上线。完整的分叉列表见 [EIP-609](/eip-609/)。


---

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