{"eip":8377,"title":"Reference-Relative Slippage Bounds","description":"An interface for swap slippage relative to a live reference price at execution time, not a static minimum fixed at signing time","authors":["Faisal Firdani (@zexoverz)"],"status":"Draft","type":"Standards Track","category":"ERC","created":"2026-08-05","requires":[165,7726],"discussionsTo":"https://ethereum-magicians.org/t/erc-8377-reference-relative-slippage-bounds/29292","repo":"ERCs","label":"ERC-8377","officialUrl":"https://eips.ethereum.org/EIPS/eip-8377","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-8377.md","url":"https://eips.huatuo.xyz/eip-8377/","tldr":{"en":"A draft swap interface where slippage is checked against a fresh oracle price read at execution time instead of a minAmountOut fixed at signing, narrowing the gap sandwich bots exploit.","ja":"スリッページを、署名時に固定された minAmountOut ではなく、実行時に読み取った最新のオラクル価格に対してチェックするスワップインターフェースのドラフト。サンドイッチボットが突く隙を狭める。","ko":"슬리피지를 서명 시점에 고정된 minAmountOut이 아니라 실행 시점에 읽은 최신 오라클 가격에 대해 검사하는 스왑 인터페이스 초안. 샌드위치 봇이 노리는 틈을 좁힌다.","zh":"一种草案兑换接口，滑点是根据执行时读取的最新预言机价格来检查，而不是根据签名时固定的 minAmountOut，从而缩小三明治机器人所利用的空隙。"},"tags":["defi","swap","slippage","mev","oracle"],"explainers":{"en":{"lang":"en","tldr":"A draft swap interface where slippage is checked against a fresh oracle price read at execution time instead of a minAmountOut fixed at signing, narrowing the gap sandwich bots exploit.","tags":["defi","swap","slippage","mev","oracle"],"related":[7726,5143,165],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-8377/","markdown":"## What problem does it solve?\n\nToday a swap is protected by one number, `minAmountOut`, chosen when the transaction is built. That number is a target for MEV:\n\n- **It goes stale.** It is based on a quote from block N, but the swap runs at block N+k. A sandwich bot can push the price within that gap; as long as the output stays above the stale floor, the attack is profitable and the user never notices.\n- **It is set wide.** To avoid failed transactions, wallets often default to 1–3 % slippage, and that headroom is exactly what can be extracted.\n- **No standard.** Every router encodes slippage differently.\n\nERC-8377 lets the caller send a slippage **policy** instead of a fixed floor. The contract reads a reference price at execution time from an [ERC-7726](/eip-7726/) quote oracle and derives the floor from it.\n\n## How it works\n\nThe caller passes a `SlippagePolicy`:\n\n| Field | Meaning |\n| --- | --- |\n| `quoteOracle` | ERC-7726 oracle giving a mid price; must enforce freshness and must not be the pool being traded |\n| `expectedCostBps` | Honest, expected discount from mid (pool fee + modeled price impact) |\n| `maxDeviationBps` | Extra adverse shortfall tolerated beyond the expected output |\n| `hardFloor` | Absolute minimum output, whatever the oracle says |\n| `deadline` | Unix time after which the trade intent expires (0 = none) |\n\n`swapWithPolicy` then must, in order:\n\n1. Reject bad policies (`bps \u003e 10_000`) and a zero recipient.\n2. Revert `DeadlineExpired` if the deadline has passed, before touching the oracle.\n3. Call `getQuote(amountIn, tokenIn, tokenOut)` on the oracle (never trust a caller-supplied reference).\n4. Compute `expectedOut = ref × (10000 − expectedCostBps) / 10000` and `floor = max(expectedOut × (10000 − maxDeviationBps) / 10000, hardFloor)`.\n5. Run the route and measure the output as the **recipient's** `tokenOut` balance increase, not what the route reports.\n6. Revert `SlippageExceeded` if the output is below the floor.\n\nSeparating expected cost from adverse deviation is the key idea: an honest fill is always a bit below mid, so a single tolerance would have to be wide again. Implementations must support [ERC-165](/eip-165/) with interface id `0x41b46b60`.\n\n## Sample code\n\nThe floor logic at the heart of an implementation (Solidity, route execution left abstract):\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IERC7726 {\n    function getQuote(uint256 baseAmount, address base, address quote) external view returns (uint256);\n}\ninterface IERC20 { function balanceOf(address) external view returns (uint256); }\n\nstruct SlippagePolicy {\n    address quoteOracle; uint32 expectedCostBps; uint32 maxDeviationBps; uint256 hardFloor; uint256 deadline;\n}\n\nabstract contract SlippageGuard {\n    error SlippageExceeded(uint256 realizedOut, uint256 floor);\n    error InvalidPolicy(uint32 expectedCostBps, uint32 maxDeviationBps);\n    error InvalidRecipient();\n    error DeadlineExpired(uint256 deadline, uint256 timestamp);\n\n    function _route(address tokenIn, address tokenOut, uint256 amountIn, address recipient, bytes calldata routeData) internal virtual;\n\n    function swapWithPolicy(address tokenIn, address tokenOut, uint256 amountIn, address recipient,\n        SlippagePolicy calldata p, bytes calldata routeData) external returns (uint256 amountOut)\n    {\n        if (p.expectedCostBps \u003e 10_000 || p.maxDeviationBps \u003e 10_000) revert InvalidPolicy(p.expectedCostBps, p.maxDeviationBps);\n        if (recipient == address(0)) revert InvalidRecipient();\n        if (p.deadline != 0 \u0026\u0026 block.timestamp \u003e p.deadline) revert DeadlineExpired(p.deadline, block.timestamp);\n\n        uint256 ref = IERC7726(p.quoteOracle).getQuote(amountIn, tokenIn, tokenOut);\n        uint256 expectedOut = ref * (10_000 - p.expectedCostBps) / 10_000;\n        uint256 floor = expectedOut * (10_000 - p.maxDeviationBps) / 10_000;\n        if (p.hardFloor \u003e floor) floor = p.hardFloor;\n\n        uint256 before = IERC20(tokenOut).balanceOf(recipient);\n        _route(tokenIn, tokenOut, amountIn, recipient, routeData);\n        amountOut = IERC20(tokenOut).balanceOf(recipient) - before;\n\n        if (amountOut \u003c floor) revert SlippageExceeded(amountOut, floor);\n    }\n}\n```\n\nExample from the spec: reference 1000, expected cost 30 bps, deviation 50 bps → floor 992; a fill of 991 reverts.\n\n## Things to know\n\n- **Status: Draft.** Field layout and the interface id may still change.\n- The oracle is the trust root. A stale or manipulable oracle makes the floor manipulable; callers must check that the specific oracle instance actually enforces a freshness bound.\n- It narrows, but does not eliminate, MEV. Extraction within `maxDeviationBps`, back-running and reordering remain; combine it with private mempools or similar protections.\n- Honest trades can revert if the venue legitimately diverges from the reference (thin liquidity, fast moves), so size `maxDeviationBps` for the venue.\n- It is complementary to [ERC-5143](/eip-5143/), which adds static slippage bounds to ERC-4626 vault calls. Routers can offer both this and classic `minAmountOut` entrypoints.\n"},"ja":{"lang":"ja","tldr":"スリッページを、署名時に固定された minAmountOut ではなく、実行時に読み取った最新のオラクル価格に対してチェックするスワップインターフェースのドラフト。サンドイッチボットが突く隙を狭める。","tags":["defi","swap","slippage","mev","oracle"],"related":[7726,5143,165],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-8377/","markdown":"## 何を解決するのか\n\n現在、スワップは、トランザクションを作る時点で選ばれる `minAmountOut` という 1 つの数値で保護されています。この数値は MEV の標的になります。\n\n- **古くなる。** ブロック N の見積もりに基づいているのに、スワップが実行されるのはブロック N+k です。サンドイッチボットはその間に価格を動かせます。出力が古い下限を上回っている限り、攻撃は利益になり、ユーザーは気付きません。\n- **広く設定される。** トランザクションの失敗を避けるため、ウォレットはスリッページをデフォルトで 1〜3 % にすることが多く、その余裕こそが抜き取られる部分です。\n- **標準がない。** ルーターごとにスリッページのエンコード方法が異なります。\n\nERC-8377 は、呼び出し元が固定の下限ではなくスリッページの**ポリシー**を送れるようにします。コントラクトは実行時に [ERC-7726](/eip-7726/) の見積もりオラクルから基準価格を読み取り、そこから下限を導き出します。\n\n## 仕組み\n\n呼び出し元は `SlippagePolicy` を渡します。\n\n| フィールド | 意味 |\n| --- | --- |\n| `quoteOracle` | 中間価格を返す ERC-7726 オラクル。鮮度を強制する必要があり、取引対象のプールであってはならない |\n| `expectedCostBps` | 中間価格からの、誠実な（想定される）ディスカウント（プール手数料 + モデル化した価格インパクト） |\n| `maxDeviationBps` | 想定される出力を超えて許容される、追加の不利な不足分 |\n| `hardFloor` | オラクルが何と言おうと変わらない、絶対的な最小出力 |\n| `deadline` | これ以降に取引の意図が失効する Unix 時刻（0 = なし） |\n\n`swapWithPolicy` は次の順序で実行しなければなりません。\n\n1. 不正なポリシー（`bps \u003e 10_000`）とゼロの受取人を拒否する。\n2. デッドラインを過ぎていれば、オラクルに触れる前に `DeadlineExpired` で revert する。\n3. オラクルの `getQuote(amountIn, tokenIn, tokenOut)` を呼び出す（呼び出し元が提供する基準は決して信用しない）。\n4. `expectedOut = ref × (10000 − expectedCostBps) / 10000` と、`floor = max(expectedOut × (10000 − maxDeviationBps) / 10000, hardFloor)` を計算する。\n5. ルートを実行し、出力をルートの報告値ではなく、**受取人の** `tokenOut` 残高の増加分として測定する。\n6. 出力が下限を下回っていれば `SlippageExceeded` で revert する。\n\n想定コストと不利な乖離を分けることが重要な発想です。誠実な約定は常に中間価格より少し下になるため、許容幅が 1 つだけだと、再び広くせざるを得なくなります。実装は、インターフェース ID `0x41b46b60` で [ERC-165](/eip-165/) をサポートしなければなりません。\n\n## サンプルコード\n\n実装の中心となる下限のロジック（Solidity、ルートの実行は抽象のまま）:\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IERC7726 {\n    function getQuote(uint256 baseAmount, address base, address quote) external view returns (uint256);\n}\ninterface IERC20 { function balanceOf(address) external view returns (uint256); }\n\nstruct SlippagePolicy {\n    address quoteOracle; uint32 expectedCostBps; uint32 maxDeviationBps; uint256 hardFloor; uint256 deadline;\n}\n\nabstract contract SlippageGuard {\n    error SlippageExceeded(uint256 realizedOut, uint256 floor);\n    error InvalidPolicy(uint32 expectedCostBps, uint32 maxDeviationBps);\n    error InvalidRecipient();\n    error DeadlineExpired(uint256 deadline, uint256 timestamp);\n\n    function _route(address tokenIn, address tokenOut, uint256 amountIn, address recipient, bytes calldata routeData) internal virtual;\n\n    function swapWithPolicy(address tokenIn, address tokenOut, uint256 amountIn, address recipient,\n        SlippagePolicy calldata p, bytes calldata routeData) external returns (uint256 amountOut)\n    {\n        if (p.expectedCostBps \u003e 10_000 || p.maxDeviationBps \u003e 10_000) revert InvalidPolicy(p.expectedCostBps, p.maxDeviationBps);\n        if (recipient == address(0)) revert InvalidRecipient();\n        if (p.deadline != 0 \u0026\u0026 block.timestamp \u003e p.deadline) revert DeadlineExpired(p.deadline, block.timestamp);\n\n        uint256 ref = IERC7726(p.quoteOracle).getQuote(amountIn, tokenIn, tokenOut);\n        uint256 expectedOut = ref * (10_000 - p.expectedCostBps) / 10_000;\n        uint256 floor = expectedOut * (10_000 - p.maxDeviationBps) / 10_000;\n        if (p.hardFloor \u003e floor) floor = p.hardFloor;\n\n        uint256 before = IERC20(tokenOut).balanceOf(recipient);\n        _route(tokenIn, tokenOut, amountIn, recipient, routeData);\n        amountOut = IERC20(tokenOut).balanceOf(recipient) - before;\n\n        if (amountOut \u003c floor) revert SlippageExceeded(amountOut, floor);\n    }\n}\n```\n\n仕様の例: 基準価格 1000、想定コスト 30 bps、乖離 50 bps → 下限 992。991 での約定は revert します。\n\n## 知っておくべきこと\n\n- **ステータス: Draft。** フィールドのレイアウトとインターフェース ID はまだ変わる可能性があります。\n- オラクルが信頼の根です。古い、または操作可能なオラクルは、下限を操作可能にします。呼び出し元は、その特定のオラクルインスタンスが実際に鮮度の上限を強制しているかを確認する必要があります。\n- MEV を狭めますが、なくすわけではありません。`maxDeviationBps` の範囲内での抜き取り、バックランニング、並べ替えは残ります。プライベート mempool などの保護と組み合わせてください。\n- 取引所が基準から正当に乖離した場合（流動性が薄い、動きが速いなど）、誠実な取引でも revert する可能性があるため、`maxDeviationBps` は取引所に合わせて設定してください。\n- ERC-4626 のボールト呼び出しに静的なスリッページの境界を追加する [ERC-5143](/eip-5143/) を補完するものです。ルーターは、これと従来の `minAmountOut` のエントリポイントの両方を提供できます。\n"},"ko":{"lang":"ko","tldr":"슬리피지를 서명 시점에 고정된 minAmountOut이 아니라 실행 시점에 읽은 최신 오라클 가격에 대해 검사하는 스왑 인터페이스 초안. 샌드위치 봇이 노리는 틈을 좁힌다.","tags":["defi","swap","slippage","mev","oracle"],"related":[7726,5143,165],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-8377/","markdown":"## 어떤 문제를 해결하나요?\n\n현재 스왑은 트랜잭션을 만들 때 정해지는 숫자 하나, `minAmountOut`으로 보호됩니다. 이 숫자는 MEV의 표적이 됩니다.\n\n- **오래됩니다.** 블록 N의 견적을 바탕으로 하지만 스왑은 블록 N+k에서 실행됩니다. 샌드위치 봇은 그 사이에 가격을 움직일 수 있습니다. 출력이 오래된 하한 위에 있는 한 공격은 이익이 되고 사용자는 알아채지 못합니다.\n- **넓게 설정됩니다.** 트랜잭션 실패를 피하려고 지갑은 흔히 슬리피지를 1–3 %로 기본 설정하는데, 그 여유분이 바로 빼앗길 수 있는 부분입니다.\n- **표준이 없습니다.** 라우터마다 슬리피지를 인코딩하는 방식이 다릅니다.\n\nERC-8377은 호출자가 고정된 하한 대신 슬리피지 **정책**을 보내게 합니다. 컨트랙트는 실행 시점에 [ERC-7726](/eip-7726/) 견적 오라클에서 기준 가격을 읽고 거기서 하한을 도출합니다.\n\n## 어떻게 동작하나요?\n\n호출자는 `SlippagePolicy`를 전달합니다.\n\n| 필드 | 의미 |\n| --- | --- |\n| `quoteOracle` | 중간 가격을 제공하는 ERC-7726 오라클. 최신성을 강제해야 하며 거래 대상 풀이어서는 안 됨 |\n| `expectedCostBps` | 중간 가격 대비 정직한 예상 할인(풀 수수료 + 모델링한 가격 영향) |\n| `maxDeviationBps` | 예상 출력을 넘어 허용되는 추가적인 불리한 부족분 |\n| `hardFloor` | 오라클이 무엇이라 하든 적용되는 절대 최소 출력 |\n| `deadline` | 이 시점 이후 거래 의도가 만료되는 Unix 시간(0 = 없음) |\n\n그다음 `swapWithPolicy`는 다음을 순서대로 수행해야 합니다.\n\n1. 잘못된 정책(`bps \u003e 10_000`)과 0 주소 수령인을 거부합니다.\n2. 마감 시한이 지났다면 오라클을 건드리기 전에 `DeadlineExpired`로 revert합니다.\n3. 오라클에서 `getQuote(amountIn, tokenIn, tokenOut)`을 호출합니다(호출자가 제공한 기준은 절대 신뢰하지 않음).\n4. `expectedOut = ref × (10000 − expectedCostBps) / 10000`과 `floor = max(expectedOut × (10000 − maxDeviationBps) / 10000, hardFloor)`를 계산합니다.\n5. 경로를 실행하고 출력을 경로가 보고하는 값이 아니라 **수령인의** `tokenOut` 잔액 증가분으로 측정합니다.\n6. 출력이 하한보다 낮으면 `SlippageExceeded`로 revert합니다.\n\n예상 비용과 불리한 편차를 분리하는 것이 핵심 아이디어입니다. 정직한 체결은 항상 중간 가격보다 조금 낮으므로, 허용 범위가 하나뿐이면 다시 넓게 잡아야 합니다. 구현은 인터페이스 id `0x41b46b60`으로 [ERC-165](/eip-165/)를 지원해야 합니다.\n\n## 샘플 코드\n\n구현의 핵심인 하한 로직(Solidity, 경로 실행은 추상으로 남김):\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IERC7726 {\n    function getQuote(uint256 baseAmount, address base, address quote) external view returns (uint256);\n}\ninterface IERC20 { function balanceOf(address) external view returns (uint256); }\n\nstruct SlippagePolicy {\n    address quoteOracle; uint32 expectedCostBps; uint32 maxDeviationBps; uint256 hardFloor; uint256 deadline;\n}\n\nabstract contract SlippageGuard {\n    error SlippageExceeded(uint256 realizedOut, uint256 floor);\n    error InvalidPolicy(uint32 expectedCostBps, uint32 maxDeviationBps);\n    error InvalidRecipient();\n    error DeadlineExpired(uint256 deadline, uint256 timestamp);\n\n    function _route(address tokenIn, address tokenOut, uint256 amountIn, address recipient, bytes calldata routeData) internal virtual;\n\n    function swapWithPolicy(address tokenIn, address tokenOut, uint256 amountIn, address recipient,\n        SlippagePolicy calldata p, bytes calldata routeData) external returns (uint256 amountOut)\n    {\n        if (p.expectedCostBps \u003e 10_000 || p.maxDeviationBps \u003e 10_000) revert InvalidPolicy(p.expectedCostBps, p.maxDeviationBps);\n        if (recipient == address(0)) revert InvalidRecipient();\n        if (p.deadline != 0 \u0026\u0026 block.timestamp \u003e p.deadline) revert DeadlineExpired(p.deadline, block.timestamp);\n\n        uint256 ref = IERC7726(p.quoteOracle).getQuote(amountIn, tokenIn, tokenOut);\n        uint256 expectedOut = ref * (10_000 - p.expectedCostBps) / 10_000;\n        uint256 floor = expectedOut * (10_000 - p.maxDeviationBps) / 10_000;\n        if (p.hardFloor \u003e floor) floor = p.hardFloor;\n\n        uint256 before = IERC20(tokenOut).balanceOf(recipient);\n        _route(tokenIn, tokenOut, amountIn, recipient, routeData);\n        amountOut = IERC20(tokenOut).balanceOf(recipient) - before;\n\n        if (amountOut \u003c floor) revert SlippageExceeded(amountOut, floor);\n    }\n}\n```\n\n명세의 예시: 기준 1000, 예상 비용 30 bps, 편차 50 bps → 하한 992. 991로 체결되면 revert됩니다.\n\n## 알아둘 점\n\n- **상태: Draft.** 필드 레이아웃과 인터페이스 id는 아직 바뀔 수 있습니다.\n- 오라클이 신뢰의 뿌리입니다. 오래되었거나 조작 가능한 오라클은 하한을 조작 가능하게 만듭니다. 호출자는 해당 오라클 인스턴스가 실제로 최신성 한도를 강제하는지 확인해야 합니다.\n- MEV를 줄이지만 없애지는 못합니다. `maxDeviationBps` 안에서의 탈취, 백러닝, 재정렬은 남아 있으므로 프라이빗 mempool 같은 보호 수단과 함께 쓰세요.\n- 거래 장소가 기준에서 정당하게 벗어나면(얕은 유동성, 빠른 가격 변동) 정직한 거래도 revert될 수 있으므로, `maxDeviationBps`는 거래 장소에 맞게 정하세요.\n- ERC-4626 볼트 호출에 정적 슬리피지 한도를 추가하는 [ERC-5143](/eip-5143/)과 상호 보완적입니다. 라우터는 이것과 기존의 `minAmountOut` 진입점을 모두 제공할 수 있습니다.\n"},"zh":{"lang":"zh","tldr":"一种草案兑换接口，滑点是根据执行时读取的最新预言机价格来检查，而不是根据签名时固定的 minAmountOut，从而缩小三明治机器人所利用的空隙。","tags":["defi","swap","slippage","mev","oracle"],"related":[7726,5143,165],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-8377/","markdown":"## 它解决什么问题？\n\n如今，一笔兑换由构造交易时选定的一个数字 `minAmountOut` 来保护。这个数字是 MEV 的目标：\n\n- **它会过时。**它基于区块 N 的报价，但兑换在区块 N+k 才执行。三明治机器人可以在这段间隙内推动价格；只要输出仍高于过时的下限，攻击就有利可图，用户却毫无察觉。\n- **它设得很宽。**为避免交易失败，钱包通常默认设为 1–3 % 的滑点，而这部分余量正是可以被榨取的。\n- **没有标准。**每个 router 对滑点的编码方式都不同。\n\nERC-8377 让调用者发送滑点**策略**，而不是固定的下限。合约在执行时从 [ERC-7726](/eip-7726/) 报价预言机读取参考价格，并据此推导出下限。\n\n## 它如何运作\n\n调用者传入一个 `SlippagePolicy`：\n\n| 字段 | 含义 |\n| --- | --- |\n| `quoteOracle` | 给出中间价的 ERC-7726 预言机；必须强制要求新鲜度，且不能是正在交易的池子 |\n| `expectedCostBps` | 相对中间价的诚实、预期折价（池费用 + 建模的价格冲击） |\n| `maxDeviationBps` | 在预期输出之外所能容忍的额外不利差额 |\n| `hardFloor` | 绝对最低输出，无论预言机如何报价 |\n| `deadline` | 交易意图过期的 Unix 时间（0 = 无） |\n\n`swapWithPolicy` 随后必须按顺序执行：\n\n1. 拒绝无效的策略（`bps \u003e 10_000`）和零地址接收方。\n2. 如果已过截止时间，则在接触预言机之前以 `DeadlineExpired` revert。\n3. 在预言机上调用 `getQuote(amountIn, tokenIn, tokenOut)`（绝不信任调用者提供的参考价）。\n4. 计算 `expectedOut = ref × (10000 − expectedCostBps) / 10000` 和 `floor = max(expectedOut × (10000 − maxDeviationBps) / 10000, hardFloor)`。\n5. 执行路由，并以**接收方**的 `tokenOut` 余额增加量来衡量输出，而不是路由自己报告的数额。\n6. 如果输出低于下限，则以 `SlippageExceeded` revert。\n\n把预期成本与不利偏差分开是关键思路：诚实的成交总是略低于中间价，因此只用一个容忍度的话，又得设得很宽。实现必须支持 [ERC-165](/eip-165/)，接口 id 为 `0x41b46b60`。\n\n## 示例代码\n\n实现核心的下限逻辑（Solidity，路由执行保持抽象）：\n\n```solidity\n// SPDX-License-Identifier: CC0-1.0\npragma solidity ^0.8.20;\n\ninterface IERC7726 {\n    function getQuote(uint256 baseAmount, address base, address quote) external view returns (uint256);\n}\ninterface IERC20 { function balanceOf(address) external view returns (uint256); }\n\nstruct SlippagePolicy {\n    address quoteOracle; uint32 expectedCostBps; uint32 maxDeviationBps; uint256 hardFloor; uint256 deadline;\n}\n\nabstract contract SlippageGuard {\n    error SlippageExceeded(uint256 realizedOut, uint256 floor);\n    error InvalidPolicy(uint32 expectedCostBps, uint32 maxDeviationBps);\n    error InvalidRecipient();\n    error DeadlineExpired(uint256 deadline, uint256 timestamp);\n\n    function _route(address tokenIn, address tokenOut, uint256 amountIn, address recipient, bytes calldata routeData) internal virtual;\n\n    function swapWithPolicy(address tokenIn, address tokenOut, uint256 amountIn, address recipient,\n        SlippagePolicy calldata p, bytes calldata routeData) external returns (uint256 amountOut)\n    {\n        if (p.expectedCostBps \u003e 10_000 || p.maxDeviationBps \u003e 10_000) revert InvalidPolicy(p.expectedCostBps, p.maxDeviationBps);\n        if (recipient == address(0)) revert InvalidRecipient();\n        if (p.deadline != 0 \u0026\u0026 block.timestamp \u003e p.deadline) revert DeadlineExpired(p.deadline, block.timestamp);\n\n        uint256 ref = IERC7726(p.quoteOracle).getQuote(amountIn, tokenIn, tokenOut);\n        uint256 expectedOut = ref * (10_000 - p.expectedCostBps) / 10_000;\n        uint256 floor = expectedOut * (10_000 - p.maxDeviationBps) / 10_000;\n        if (p.hardFloor \u003e floor) floor = p.hardFloor;\n\n        uint256 before = IERC20(tokenOut).balanceOf(recipient);\n        _route(tokenIn, tokenOut, amountIn, recipient, routeData);\n        amountOut = IERC20(tokenOut).balanceOf(recipient) - before;\n\n        if (amountOut \u003c floor) revert SlippageExceeded(amountOut, floor);\n    }\n}\n```\n\n规范中的示例：参考价 1000，预期成本 30 bps，偏差 50 bps → 下限 992；成交 991 会 revert。\n\n## 需要注意\n\n- **状态：Draft。**字段布局和接口 id 仍可能变化。\n- 预言机是信任的根基。过时或可被操纵的预言机会使下限可被操纵；调用者必须检查具体的预言机实例是否确实强制执行了新鲜度界限。\n- 它缩小了 MEV，但并未消除。在 `maxDeviationBps` 范围内的榨取、后置交易（back-running）和重新排序依然存在；请与私有 mempool 或类似的保护措施结合使用。\n- 如果交易场所合理地偏离参考价（流动性薄、行情快速变动），诚实的交易也可能 revert，因此应根据交易场所来设定 `maxDeviationBps` 的大小。\n- 它与 [ERC-5143](/eip-5143/) 互补，后者为 ERC-4626 金库调用增加了静态滑点界限。Router 可以同时提供这个入口和传统的 `minAmountOut` 入口。\n"}}}
