{"eip":6787,"title":"Order Book DEX with Two Phase Withdrawal","description":"An order book-based DEX Interface that ensures the asset security of both users and the exchange","authors":["Jessica (@qizheng09)","Roy (@royshang)","Jun (@SniperUsopp)"],"status":"Draft","type":"Standards Track","category":"ERC","created":"2023-03-27","discussionsTo":"https://ethereum-magicians.org/t/order-book-dex-standard/13573","repo":"ERCs","label":"ERC-6787","officialUrl":"https://eips.ethereum.org/EIPS/eip-6787","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-6787.md","url":"https://eips.huatuo.xyz/eip-6787/","tldr":{"en":"A draft interface for order-book DEXs that adds a two-phase forced withdrawal: users can always get their funds out, but only after a window in which the exchange settles their open positions.","ja":"オーダーブック型 DEX 向けのドラフトインターフェース。2 段階の強制引き出しを追加し、ユーザーはいつでも資金を引き出せるが、取引所が未決済ポジションを精算する猶予期間を経る必要がある。","ko":"오더북 DEX를 위한 초안 인터페이스로, 2단계 강제 출금을 추가한다. 사용자는 언제든 자금을 꺼낼 수 있지만, 거래소가 미결제 포지션을 정산하는 대기 기간을 거쳐야 한다.","zh":"一份面向订单簿 DEX 的草案接口，增加了两阶段强制提款：用户随时都能取出资金，但需要经过一个窗口期，让交易所结算其未平仓头寸。"},"tags":["defi","dex","order-book","withdrawal","layer2"],"explainers":{"en":{"lang":"en","tldr":"A draft interface for order-book DEXs that adds a two-phase forced withdrawal: users can always get their funds out, but only after a window in which the exchange settles their open positions.","tags":["defi","dex","order-book","withdrawal","layer2"],"related":[20],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-6787/","markdown":"## What problem does it solve?\n\nOrder-book exchanges running on Layer 2 typically hold user deposits in a contract and match trades off-chain. Users need an escape hatch: if the operator stops cooperating, they must be able to force their money out on-chain. But a naive forced withdrawal is abusable. A trader sitting on a losing perpetual position could yank their collateral before the loss is settled, leaving the exchange to absorb it.\n\nERC-6787 proposes a common interface for such DEXs, with a forced withdrawal split into two steps so both sides are protected.\n\n## How it works\n\nThe interface has four functions and one event:\n\n| Function | Purpose |\n| --- | --- |\n| `deposit(token, amount)` | Move tokens into the exchange contract |\n| `withdraw(token, amount)` | Normal, cooperative withdrawal |\n| `prepareForceWithdraw(token, amount)` | Phase 1: announce a forced withdrawal; returns a unique `requestID` |\n| `commitForceWithdraw(requestID)` | Phase 2: execute the forced withdrawal once the waiting period has passed |\n\n`PrepareForceWithdraw(user, tokenAddress, amount)` must be emitted when phase 1 succeeds.\n\nBetween the two phases the exchange has a timeout window to check the user's account, forcibly cancel open orders and settle trades. After that, the user can commit the withdrawal directly without the operator's help. Each request has its own `requestID`, so a user can run several in parallel. The design assumes the exchange keeps a 1:1 reserve of deposited assets in the contract.\n\n## Sample code\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IOrderBookDEX {\n    event PrepareForceWithdraw(address indexed user, address indexed tokenAddress, uint256 amount);\n\n    function deposit(address token, uint256 amount) external;\n    function withdraw(address token, uint256 amount) external;\n    function prepareForceWithdraw(address token, uint256 amount) external returns (uint256 requestID);\n    function commitForceWithdraw(uint256 requestID) external;\n}\n```\n\nUser flow (ethers v6):\n\n```ts\n// Simulate first to learn the requestID the call will return, then send it.\nconst requestId = await dex.prepareForceWithdraw.staticCall(usdc, amount);\nawait (await dex.prepareForceWithdraw(usdc, amount)).wait();\n\n// ...after the exchange's waiting period has elapsed:\nawait (await dex.commitForceWithdraw(requestId)).wait();\n```\n\n## Things to know\n\n- Status is **Draft**. The spec is short and leaves many things to the implementation.\n- The length of the waiting period, how the exchange settles positions within it, and what happens if it doesn't, are not specified.\n- The prepare event does not include the `requestID`, so off-chain tooling cannot match it to a later commit from logs alone. In the sample, the `staticCall` trick only works if the next ID is predictable; a real integration should get it from the implementation's own event or view function.\n- Security considerations in the spec are marked \"needs discussion\". Treat any implementation as requiring careful audit.\n"},"ja":{"lang":"ja","tldr":"オーダーブック型 DEX 向けのドラフトインターフェース。2 段階の強制引き出しを追加し、ユーザーはいつでも資金を引き出せるが、取引所が未決済ポジションを精算する猶予期間を経る必要がある。","tags":["defi","dex","order-book","withdrawal","layer2"],"related":[20],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-6787/","markdown":"## 何を解決するのか\n\nLayer 2 上で動くオーダーブック型取引所は、通常ユーザーの預入をコントラクトに保管し、取引のマッチングをオフチェーンで行います。ユーザーには脱出口が必要です。運営者が協力しなくなった場合でも、オンチェーンで資金を強制的に引き出せなければなりません。しかし単純な強制引き出しは悪用されかねません。含み損のある無期限先物（perpetual）ポジションを持つトレーダーが、損失が精算される前に担保を引き出し、損失を取引所に負わせてしまうおそれがあります。\n\nERC-6787 は、こうした DEX の共通インターフェースを提案します。強制引き出しを 2 段階に分けることで、双方を保護します。\n\n## 仕組み\n\nインターフェースは 4 つの関数と 1 つのイベントで構成されます。\n\n| 関数 | 役割 |\n| --- | --- |\n| `deposit(token, amount)` | トークンを取引所コントラクトに預け入れる |\n| `withdraw(token, amount)` | 通常の協調的な引き出し |\n| `prepareForceWithdraw(token, amount)` | フェーズ 1: 強制引き出しを宣言し、一意の `requestID` を返す |\n| `commitForceWithdraw(requestID)` | フェーズ 2: 待機期間の経過後に強制引き出しを実行する |\n\nフェーズ 1 が成功したときは `PrepareForceWithdraw(user, tokenAddress, amount)` を発行しなければなりません。\n\n2 つのフェーズの間に、取引所にはタイムアウト期間があり、ユーザーのアカウントを確認し、未約定の注文を強制的にキャンセルし、取引を精算できます。その後、ユーザーは運営者の助けなしに直接引き出しを確定できます。各リクエストには固有の `requestID` があるため、ユーザーは複数を並行して実行できます。この設計は、取引所が預入資産の 1:1 の準備金をコントラクト内に保持していることを前提としています。\n\n## サンプルコード\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IOrderBookDEX {\n    event PrepareForceWithdraw(address indexed user, address indexed tokenAddress, uint256 amount);\n\n    function deposit(address token, uint256 amount) external;\n    function withdraw(address token, uint256 amount) external;\n    function prepareForceWithdraw(address token, uint256 amount) external returns (uint256 requestID);\n    function commitForceWithdraw(uint256 requestID) external;\n}\n```\n\nユーザーのフロー（ethers v6）:\n\n```ts\n// Simulate first to learn the requestID the call will return, then send it.\nconst requestId = await dex.prepareForceWithdraw.staticCall(usdc, amount);\nawait (await dex.prepareForceWithdraw(usdc, amount)).wait();\n\n// ...after the exchange's waiting period has elapsed:\nawait (await dex.commitForceWithdraw(requestId)).wait();\n```\n\n## 知っておくべきこと\n\n- ステータスは **Draft** です。仕様は短く、多くを実装に委ねています。\n- 待機期間の長さ、その間に取引所がどのようにポジションを精算するか、精算しなかった場合に何が起きるかは規定されていません。\n- prepare イベントには `requestID` が含まれないため、オフチェーンのツールはログだけでは後続の commit と対応付けられません。サンプルの `staticCall` の手法は、次の ID が予測可能な場合にのみ機能します。実際の統合では、実装独自のイベントか view 関数から取得してください。\n- 仕様のセキュリティに関する考慮事項は「needs discussion」とされています。どの実装も慎重な監査が必要だと考えてください。\n"},"ko":{"lang":"ko","tldr":"오더북 DEX를 위한 초안 인터페이스로, 2단계 강제 출금을 추가한다. 사용자는 언제든 자금을 꺼낼 수 있지만, 거래소가 미결제 포지션을 정산하는 대기 기간을 거쳐야 한다.","tags":["defi","dex","order-book","withdrawal","layer2"],"related":[20],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-6787/","markdown":"## 어떤 문제를 해결하나요?\n\n레이어 2에서 동작하는 오더북 거래소는 보통 사용자 예치금을 컨트랙트에 보관하고 거래 매칭은 오프체인에서 처리합니다. 사용자에게는 비상 탈출구가 필요합니다. 운영자가 협조하지 않더라도 온체인에서 자금을 강제로 꺼낼 수 있어야 합니다. 하지만 단순한 강제 출금은 악용될 수 있습니다. 손실 중인 무기한 선물(perpetual) 포지션을 가진 트레이더가 손실이 정산되기 전에 담보를 빼내, 손실을 거래소가 떠안게 될 수 있습니다.\n\nERC-6787은 이런 DEX를 위한 공통 인터페이스를 제안하며, 강제 출금을 두 단계로 나눠 양쪽을 모두 보호합니다.\n\n## 어떻게 동작하나요?\n\n인터페이스는 함수 네 개와 이벤트 하나로 구성됩니다.\n\n| 함수 | 역할 |\n| --- | --- |\n| `deposit(token, amount)` | 토큰을 거래소 컨트랙트에 예치 |\n| `withdraw(token, amount)` | 일반적인 협조적 출금 |\n| `prepareForceWithdraw(token, amount)` | 1단계: 강제 출금을 선언하고 고유한 `requestID`를 반환 |\n| `commitForceWithdraw(requestID)` | 2단계: 대기 기간이 지난 뒤 강제 출금을 실행 |\n\n1단계가 성공하면 `PrepareForceWithdraw(user, tokenAddress, amount)`를 반드시 발생시켜야 합니다.\n\n두 단계 사이에 거래소는 타임아웃 기간 동안 사용자 계정을 확인하고, 미체결 주문을 강제로 취소하고, 거래를 정산할 수 있습니다. 그 후 사용자는 운영자의 도움 없이 직접 출금을 확정할 수 있습니다. 각 요청에는 고유한 `requestID`가 있어서 사용자는 여러 건을 동시에 진행할 수 있습니다. 이 설계는 거래소가 예치된 자산의 1:1 준비금을 컨트랙트에 보유한다고 가정합니다.\n\n## 샘플 코드\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IOrderBookDEX {\n    event PrepareForceWithdraw(address indexed user, address indexed tokenAddress, uint256 amount);\n\n    function deposit(address token, uint256 amount) external;\n    function withdraw(address token, uint256 amount) external;\n    function prepareForceWithdraw(address token, uint256 amount) external returns (uint256 requestID);\n    function commitForceWithdraw(uint256 requestID) external;\n}\n```\n\n사용자 흐름(ethers v6):\n\n```ts\n// Simulate first to learn the requestID the call will return, then send it.\nconst requestId = await dex.prepareForceWithdraw.staticCall(usdc, amount);\nawait (await dex.prepareForceWithdraw(usdc, amount)).wait();\n\n// ...after the exchange's waiting period has elapsed:\nawait (await dex.commitForceWithdraw(requestId)).wait();\n```\n\n## 알아둘 점\n\n- 상태는 **Draft**입니다. 명세가 짧고 많은 부분을 구현에 맡기고 있습니다.\n- 대기 기간의 길이, 그 기간에 거래소가 포지션을 어떻게 정산하는지, 정산하지 않으면 어떻게 되는지는 명시되어 있지 않습니다.\n- prepare 이벤트에는 `requestID`가 없으므로, 오프체인 도구는 로그만으로 이후의 commit과 대응시킬 수 없습니다. 샘플의 `staticCall` 방식은 다음 ID를 예측할 수 있을 때만 동작하므로, 실제 연동에서는 구현체 자체의 이벤트나 view 함수에서 얻어야 합니다.\n- 명세의 보안 고려 사항은 \"needs discussion\"으로 표시되어 있습니다. 모든 구현은 신중한 감사가 필요하다고 봐야 합니다.\n"},"zh":{"lang":"zh","tldr":"一份面向订单簿 DEX 的草案接口，增加了两阶段强制提款：用户随时都能取出资金，但需要经过一个窗口期，让交易所结算其未平仓头寸。","tags":["defi","dex","order-book","withdrawal","layer2"],"related":[20],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-6787/","markdown":"## 它解决什么问题？\n\n运行在 Layer 2 上的订单簿交易所通常把用户存款放在合约里，并在链下撮合交易。用户需要一个逃生通道：如果运营方不再配合，他们必须能够在链上强制取出自己的资金。但简单的强制提款可能被滥用。持有亏损永续合约头寸的交易者可以在亏损结算之前抽走抵押品，让交易所来承担损失。\n\nERC-6787 为这类 DEX 提出了一个通用接口，把强制提款拆成两步，从而同时保护双方。\n\n## 它如何运作\n\n该接口有四个函数和一个事件：\n\n| 函数 | 用途 |\n| --- | --- |\n| `deposit(token, amount)` | 把代币存入交易所合约 |\n| `withdraw(token, amount)` | 正常的协作式提款 |\n| `prepareForceWithdraw(token, amount)` | 阶段 1：声明强制提款；返回唯一的 `requestID` |\n| `commitForceWithdraw(requestID)` | 阶段 2：等待期过后执行强制提款 |\n\n阶段 1 成功时必须触发 `PrepareForceWithdraw(user, tokenAddress, amount)`。\n\n两个阶段之间，交易所有一个超时窗口，用来检查用户账户、强制取消未成交订单并结算交易。之后，用户可以不依赖运营方，直接提交提款。每个请求都有自己的 `requestID`，因此用户可以并行发起多个请求。该设计假设交易所在合约中以 1:1 的比例保留所存资产的储备。\n\n## 示例代码\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IOrderBookDEX {\n    event PrepareForceWithdraw(address indexed user, address indexed tokenAddress, uint256 amount);\n\n    function deposit(address token, uint256 amount) external;\n    function withdraw(address token, uint256 amount) external;\n    function prepareForceWithdraw(address token, uint256 amount) external returns (uint256 requestID);\n    function commitForceWithdraw(uint256 requestID) external;\n}\n```\n\n用户流程（ethers v6）：\n\n```ts\n// Simulate first to learn the requestID the call will return, then send it.\nconst requestId = await dex.prepareForceWithdraw.staticCall(usdc, amount);\nawait (await dex.prepareForceWithdraw(usdc, amount)).wait();\n\n// ...after the exchange's waiting period has elapsed:\nawait (await dex.commitForceWithdraw(requestId)).wait();\n```\n\n## 需要注意\n\n- 状态为 **Draft**。规范很简短，许多事项留给实现自行决定。\n- 等待期的长度、交易所在此期间如何结算头寸，以及它没有结算时会发生什么，均未规定。\n- prepare 事件不包含 `requestID`，因此链下工具无法仅凭日志把它与之后的 commit 对应起来。示例中的 `staticCall` 技巧只有在下一个 ID 可预测时才有效；真实的集成应从实现自己的事件或 view 函数中获取。\n- 规范中的安全注意事项标注为\"needs discussion\"。任何实现都应视为需要仔细审计。\n"}}}
