{"eip":140,"title":"REVERT instruction","description":"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.","authors":["Alex Beregszaszi (@axic)","Nikolai Mushegian \u003cnikolai@nexusdev.us\u003e"],"status":"Final","type":"Standards Track","category":"Core","created":"2017-02-06","repo":"EIPs","label":"EIP-140","officialUrl":"https://eips.ethereum.org/EIPS/eip-140","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-140.md","url":"https://eips.huatuo.xyz/eip-140/","tldr":{"en":"Adds the REVERT opcode, which aborts execution and rolls back state while refunding unused gas and returning an error message to the caller.","ja":"実行を中断して状態をロールバックしつつ、未使用のガスを返金し、エラーメッセージを呼び出し元に返す REVERT オペコードを追加する。","ko":"실행을 중단하고 상태를 롤백하면서 사용하지 않은 가스를 환불하고, 호출자에게 에러 메시지를 돌려주는 REVERT 오피코드를 추가한다.","zh":"新增 REVERT 操作码，它会中止执行并回滚状态，同时退还未使用的 gas，并向调用方返回错误信息。"},"tags":["evm","opcode","errors","byzantium","core"],"explainers":{"en":{"lang":"en","tldr":"Adds the REVERT opcode, which aborts execution and rolls back state while refunding unused gas and returning an error message to the caller.","tags":["evm","opcode","errors","byzantium","core"],"related":[211,838,609,6093],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-140/","markdown":"## What problem does it solve?\n\nBefore the Byzantium hard fork (2017), a contract had only two ways to abort: run out of gas, or hit an invalid instruction. Both consumed **all** the remaining gas, even when the contract had simply checked a condition and found it false. Neither could explain why. The caller saw only \"failed\".\n\nEIP-140 adds a clean way to fail: stop, undo every state change, keep the unused gas, and hand back a message.\n\n## How it works\n\n- New opcode `REVERT` at `0xfd`, taking two stack items: `memory_offset` and `memory_length`.\n- Execution stops and all state changes from the current call (including logs) are rolled back.\n- The memory slice is returned to the caller as **return data**, the same way `RETURN` returns data. The caller can read it with `RETURNDATASIZE` / `RETURNDATACOPY` from [EIP-211](/eip-211/).\n- Gas cost is the same as `RETURN`: you pay only for memory. The remaining gas goes back to the caller.\n- The calling `CALL` (or `CREATE` / `CREATE2`) pushes `0`, as it does for any failure. For a creation, no code is deployed.\n- If there is not enough gas for `REVERT` itself, or a stack underflow happens, it acts as a normal out-of-gas error and consumes all gas.\n\nThe EIP does not define what the returned bytes mean. Solidity encodes them as `Error(string)` for `require(cond, \"msg\")` (selector `0x08c379a0`), `Panic(uint256)` for assertion and arithmetic failures, and ABI-encoded custom errors for `revert MyError(...)`.\n\n## Sample code\n\nHigh-level Solidity compiles to `REVERT`:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Vault {\n    error InsufficientBalance(uint256 have, uint256 want);\n    mapping(address =\u003e uint256) public balance;\n\n    function withdraw(uint256 amount) external {\n        uint256 b = balance[msg.sender];\n        if (b \u003c amount) revert InsufficientBalance(b, amount); // REVERT with ABI-encoded error\n        balance[msg.sender] = b - amount;\n        payable(msg.sender).transfer(amount);\n    }\n}\n```\n\nThe raw opcode in inline assembly, returning a 32-byte payload:\n\n```solidity\nassembly {\n    mstore(0, 0x2a)   // put 42 in memory\n    revert(0, 32)     // REVERT(offset=0, length=32)\n}\n```\n\nDecoding the reason off-chain (ethers v6):\n\n```ts\ntry {\n  await vault.withdraw(10n ** 18n);\n} catch (e: any) {\n  console.log(e.revert?.name, e.revert?.args); // \"InsufficientBalance\", [have, want]\n}\n```\n\n## Things to know\n\n- `REVERT` is not free. You still pay for the gas used up to that point. Only the *remaining* gas is refunded, unlike the old invalid-opcode approach.\n- `assert` failures in Solidity before 0.8.0 compiled to the invalid opcode `0xfe` and used up all gas. Since 0.8.0 they use `REVERT` with `Panic(uint256)`.\n- The return-data format for reasons was proposed separately in [EIP-838](/eip-838/), which remains a Draft. The `Error(string)` convention is defined by Solidity, not by an EIP.\n- Shipped in Byzantium together with [EIP-211](/eip-211/). See [EIP-609](/eip-609/) for the full fork list.\n"},"ja":{"lang":"ja","tldr":"実行を中断して状態をロールバックしつつ、未使用のガスを返金し、エラーメッセージを呼び出し元に返す REVERT オペコードを追加する。","tags":["evm","opcode","errors","byzantium","core"],"related":[211,838,609,6093],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-140/","markdown":"## 何を解決するのか\n\nByzantium ハードフォーク（2017 年）より前、コントラクトが処理を中断する方法は 2 つしかありませんでした。ガスを使い切るか、無効な命令に当たるかです。どちらも、単に条件を確認して偽だった場合でも、残りのガスを**すべて**消費しました。しかも理由を説明することもできず、呼び出し元には「失敗した」としか見えませんでした。\n\nEIP-140 は、きれいに失敗する方法を追加します。停止し、すべての状態変更を元に戻し、未使用のガスを残し、メッセージを返します。\n\n## 仕組み\n\n- 新しいオペコード `REVERT` は `0xfd` で、スタックから `memory_offset` と `memory_length` の 2 つを受け取ります。\n- 実行が停止し、現在の呼び出しによるすべての状態変更（ログを含む）がロールバックされます。\n- メモリの該当範囲は、`RETURN` がデータを返すのと同じように、**戻りデータ**として呼び出し元に返されます。呼び出し元は [EIP-211](/eip-211/) の `RETURNDATASIZE` / `RETURNDATACOPY` で読み取れます。\n- ガスコストは `RETURN` と同じで、メモリ分だけを支払います。残りのガスは呼び出し元に戻ります。\n- 呼び出し元の `CALL`（または `CREATE` / `CREATE2`）は、他の失敗と同様に `0` をプッシュします。コントラクト作成の場合、コードはデプロイされません。\n- `REVERT` 自体に十分なガスがない場合やスタックアンダーフローが起きた場合は、通常のガス切れエラーとして扱われ、すべてのガスを消費します。\n\nこの EIP は、返されるバイト列の意味を定義していません。Solidity は、`require(cond, \"msg\")` には `Error(string)`（セレクタ `0x08c379a0`）、アサーションや算術の失敗には `Panic(uint256)`、`revert MyError(...)` には ABI エンコードされたカスタムエラーとしてエンコードします。\n\n## サンプルコード\n\n高水準の Solidity は `REVERT` にコンパイルされます。\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Vault {\n    error InsufficientBalance(uint256 have, uint256 want);\n    mapping(address =\u003e uint256) public balance;\n\n    function withdraw(uint256 amount) external {\n        uint256 b = balance[msg.sender];\n        if (b \u003c amount) revert InsufficientBalance(b, amount); // ABI エンコードされたエラーで REVERT\n        balance[msg.sender] = b - amount;\n        payable(msg.sender).transfer(amount);\n    }\n}\n```\n\nインラインアセンブリで生のオペコードを使い、32 バイトのペイロードを返す例です。\n\n```solidity\nassembly {\n    mstore(0, 0x2a)   // メモリに 42 を置く\n    revert(0, 32)     // REVERT(offset=0, length=32)\n}\n```\n\nオフチェーンで理由をデコードする例（ethers v6）:\n\n```ts\ntry {\n  await vault.withdraw(10n ** 18n);\n} catch (e: any) {\n  console.log(e.revert?.name, e.revert?.args); // \"InsufficientBalance\", [have, want]\n}\n```\n\n## 知っておくべきこと\n\n- `REVERT` は無料ではありません。それまでに使ったガスは支払う必要があります。返金されるのは*残りの*ガスだけで、これが古い無効オペコード方式との違いです。\n- Solidity 0.8.0 より前の `assert` の失敗は、無効オペコード `0xfe` にコンパイルされ、すべてのガスを使い切りました。0.8.0 以降は `Panic(uint256)` を伴う `REVERT` を使います。\n- 理由の戻りデータ形式は [EIP-838](/eip-838/) で別途提案されましたが、Draft のままです。`Error(string)` の規約は EIP ではなく Solidity が定めたものです。\n- Byzantium で [EIP-211](/eip-211/) と一緒に導入されました。フォークの全一覧は [EIP-609](/eip-609/) を参照してください。\n"},"ko":{"lang":"ko","tldr":"실행을 중단하고 상태를 롤백하면서 사용하지 않은 가스를 환불하고, 호출자에게 에러 메시지를 돌려주는 REVERT 오피코드를 추가한다.","tags":["evm","opcode","errors","byzantium","core"],"related":[211,838,609,6093],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-140/","markdown":"## 어떤 문제를 해결하나요?\n\nByzantium 하드포크(2017년) 이전에 컨트랙트가 실행을 중단할 수 있는 방법은 두 가지뿐이었습니다. 가스를 모두 소진하거나, 유효하지 않은 명령을 만나는 것입니다. 컨트랙트가 단지 조건을 확인했는데 거짓이었던 경우에도 둘 다 남은 가스를 **전부** 소비했습니다. 게다가 이유를 설명할 방법도 없어서, 호출자에게는 \"실패했다\"고만 보였습니다.\n\nEIP-140은 깔끔하게 실패하는 방법을 추가합니다. 멈추고, 모든 상태 변경을 되돌리고, 사용하지 않은 가스를 남기고, 메시지를 돌려줍니다.\n\n## 어떻게 동작하나요?\n\n- 새 오피코드 `REVERT`는 `0xfd`이며 스택에서 `memory_offset`과 `memory_length` 두 개를 받습니다.\n- 실행이 멈추고 현재 호출에서 발생한 모든 상태 변경(로그 포함)이 롤백됩니다.\n- 해당 메모리 구간은 `RETURN`이 데이터를 돌려주는 것과 같은 방식으로 **반환 데이터**로 호출자에게 전달됩니다. 호출자는 [EIP-211](/eip-211/)의 `RETURNDATASIZE` / `RETURNDATACOPY`로 읽을 수 있습니다.\n- 가스 비용은 `RETURN`과 같습니다. 메모리에 대해서만 지불합니다. 남은 가스는 호출자에게 돌아갑니다.\n- 호출한 `CALL`(또는 `CREATE` / `CREATE2`)은 다른 실패 때와 마찬가지로 `0`을 푸시합니다. 컨트랙트 생성의 경우 코드는 배포되지 않습니다.\n- `REVERT` 자체에 가스가 부족하거나 스택 언더플로가 발생하면 일반적인 가스 부족 에러로 처리되어 가스를 모두 소비합니다.\n\n이 EIP는 반환되는 바이트의 의미를 정의하지 않습니다. Solidity는 `require(cond, \"msg\")`에는 `Error(string)`(셀렉터 `0x08c379a0`)을, 단언문과 산술 실패에는 `Panic(uint256)`을, `revert MyError(...)`에는 ABI로 인코딩된 커스텀 에러를 사용합니다.\n\n## 샘플 코드\n\n고수준 Solidity는 `REVERT`로 컴파일됩니다.\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Vault {\n    error InsufficientBalance(uint256 have, uint256 want);\n    mapping(address =\u003e uint256) public balance;\n\n    function withdraw(uint256 amount) external {\n        uint256 b = balance[msg.sender];\n        if (b \u003c amount) revert InsufficientBalance(b, amount); // ABI 인코딩된 에러로 REVERT\n        balance[msg.sender] = b - amount;\n        payable(msg.sender).transfer(amount);\n    }\n}\n```\n\n인라인 어셈블리에서 원시 오피코드로 32바이트 페이로드를 반환하는 예입니다.\n\n```solidity\nassembly {\n    mstore(0, 0x2a)   // 메모리에 42를 넣는다\n    revert(0, 32)     // REVERT(offset=0, length=32)\n}\n```\n\n오프체인에서 사유를 디코딩하는 예(ethers v6):\n\n```ts\ntry {\n  await vault.withdraw(10n ** 18n);\n} catch (e: any) {\n  console.log(e.revert?.name, e.revert?.args); // \"InsufficientBalance\", [have, want]\n}\n```\n\n## 알아둘 점\n\n- `REVERT`는 공짜가 아닙니다. 그 시점까지 사용한 가스는 그대로 지불해야 합니다. 예전의 유효하지 않은 오피코드 방식과 달리 *남은* 가스만 환불됩니다.\n- Solidity 0.8.0 이전에는 `assert` 실패가 유효하지 않은 오피코드 `0xfe`로 컴파일되어 가스를 모두 소진했습니다. 0.8.0부터는 `Panic(uint256)`과 함께 `REVERT`를 사용합니다.\n- 사유의 반환 데이터 형식은 [EIP-838](/eip-838/)에서 별도로 제안되었지만 여전히 Draft입니다. `Error(string)` 규약은 EIP가 아니라 Solidity가 정한 것입니다.\n- Byzantium에서 [EIP-211](/eip-211/)과 함께 출시되었습니다. 전체 포크 목록은 [EIP-609](/eip-609/)를 참고하세요.\n"},"zh":{"lang":"zh","tldr":"新增 REVERT 操作码，它会中止执行并回滚状态，同时退还未使用的 gas，并向调用方返回错误信息。","tags":["evm","opcode","errors","byzantium","core"],"related":[211,838,609,6093],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-140/","markdown":"## 它解决什么问题？\n\n在 Byzantium 硬分叉（2017 年）之前，合约只有两种中止方式：耗尽 gas，或执行无效指令。即使合约只是检查了某个条件并发现为假，这两种方式也都会消耗**全部**剩余 gas，而且都无法说明原因，调用方只能看到\"失败\"。\n\nEIP-140 增加了一种干净的失败方式：停止、撤销所有状态更改、保留未使用的 gas，并返回一条消息。\n\n## 它如何运作\n\n- 新操作码 `REVERT` 位于 `0xfd`，从栈中取两个值：`memory_offset` 和 `memory_length`。\n- 执行停止，当前调用产生的所有状态更改（包括日志）都会被回滚。\n- 该内存片段会作为**返回数据**返回给调用方，方式与 `RETURN` 返回数据相同。调用方可以用 [EIP-211](/eip-211/) 中的 `RETURNDATASIZE` / `RETURNDATACOPY` 读取它。\n- gas 成本与 `RETURN` 相同：只需为内存付费。剩余的 gas 退还给调用方。\n- 发起调用的 `CALL`（或 `CREATE` / `CREATE2`）与任何失败情况一样压入 `0`。对于合约创建，不会部署任何代码。\n- 如果 `REVERT` 本身的 gas 不足，或发生栈下溢，则按普通的 out-of-gas 错误处理，消耗全部 gas。\n\n该 EIP 并未定义返回字节的含义。Solidity 对 `require(cond, \"msg\")` 编码为 `Error(string)`（选择器 `0x08c379a0`），对断言和算术失败编码为 `Panic(uint256)`，对 `revert MyError(...)` 编码为 ABI 编码的自定义错误。\n\n## 示例代码\n\n高级 Solidity 会编译为 `REVERT`：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Vault {\n    error InsufficientBalance(uint256 have, uint256 want);\n    mapping(address =\u003e uint256) public balance;\n\n    function withdraw(uint256 amount) external {\n        uint256 b = balance[msg.sender];\n        if (b \u003c amount) revert InsufficientBalance(b, amount); // 以 ABI 编码的错误执行 REVERT\n        balance[msg.sender] = b - amount;\n        payable(msg.sender).transfer(amount);\n    }\n}\n```\n\n在内联汇编中使用原始操作码，返回 32 字节的数据：\n\n```solidity\nassembly {\n    mstore(0, 0x2a)   // 把 42 放入内存\n    revert(0, 32)     // REVERT(offset=0, length=32)\n}\n```\n\n在链下解码原因（ethers v6）：\n\n```ts\ntry {\n  await vault.withdraw(10n ** 18n);\n} catch (e: any) {\n  console.log(e.revert?.name, e.revert?.args); // \"InsufficientBalance\", [have, want]\n}\n```\n\n## 需要注意\n\n- `REVERT` 并不免费。到那一刻为止已用掉的 gas 仍需支付。与旧的无效操作码方式不同，只有*剩余*的 gas 会被退还。\n- 0.8.0 之前的 Solidity 中，`assert` 失败会编译为无效操作码 `0xfe` 并耗尽所有 gas。自 0.8.0 起，它们使用带有 `Panic(uint256)` 的 `REVERT`。\n- 原因的返回数据格式曾在 [EIP-838](/eip-838/) 中单独提出，该提案至今仍是 Draft。`Error(string)` 这一约定由 Solidity 定义，而不是由某个 EIP 定义。\n- 与 [EIP-211](/eip-211/) 一起在 Byzantium 中上线。完整的分叉列表见 [EIP-609](/eip-609/)。\n"}},"requiredBy":[609,658,2014,5568]}
