{"eip":3668,"title":"CCIP Read—Secure offchain data retrieval","description":"CCIP Read provides a mechanism to allow a contract to fetch external data.","authors":["Nick Johnson (@arachnid)"],"status":"Final","type":"Standards Track","category":"ERC","created":"2020-07-19","discussionsTo":"https://ethereum-magicians.org/t/durin-secure-offchain-data-retrieval/6728","repo":"ERCs","label":"ERC-3668","officialUrl":"https://eips.ethereum.org/EIPS/eip-3668","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-3668.md","url":"https://eips.huatuo.xyz/eip-3668/","tldr":{"en":"Lets a contract answer a call by reverting with a pointer to an offchain gateway, so clients fetch the data and hand it back to the contract for verification.","ja":"コントラクトが、オフチェーンのゲートウェイを指すポインタとともに revert することで呼び出しに応答できるようにし、クライアントがデータを取得して、検証のためにコントラクトへ渡し直す。","ko":"컨트랙트가 오프체인 게이트웨이를 가리키는 포인터와 함께 revert하여 호출에 응답하게 하고, 클라이언트가 데이터를 가져와 검증을 위해 컨트랙트에 다시 건네게 한다.","zh":"让合约通过回滚并附带指向链下网关的指针来响应调用，客户端据此获取数据，再交还给合约验证。"},"tags":["offchain","ccip-read","gateway","ens","l2"],"explainers":{"en":{"lang":"en","tldr":"Lets a contract answer a call by reverting with a pointer to an offchain gateway, so clients fetch the data and hand it back to the contract for verification.","tags":["offchain","ccip-read","gateway","ens","l2"],"related":[137,2544,5559],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-3668/","markdown":"## What problem does it solve?\n\nStoring data onchain is expensive, so many applications keep data elsewhere (Merkle trees, L2s, plain servers) and store only enough onchain to verify it. Before this ERC, every such project invented its own lookup scheme, and wallets or dapps had to integrate each one separately.\n\nCCIP Read (also called \"Durin\") defines one generic flow: the contract tells the client *where* to get the missing data, the client fetches it over HTTPS, and the contract checks the answer. A client that implements the flow once can read from any contract using any storage backend, without knowing the details. ENS uses it to resolve names whose records live offchain or on L2s.\n\n## How it works\n\n1. **Call the contract.** Instead of returning, the function reverts with:\n   ```solidity\n   error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);\n   ```\n2. **Query a gateway.** The client picks a URL template from `urls`, substituting `{sender}` (lowercase hex address) and `{data}` (hex `callData`). If the template contains `{data}` it sends a GET; otherwise it POSTs JSON `{\"data\": ..., \"sender\": ...}`. The gateway replies with JSON `{\"data\": \"0x...\"}`.\n3. **Call back.** The client calls `callbackFunction(response, extraData)` on the same contract. The callback verifies the response (signature, Merkle proof, storage proof...) and returns the result with the same return type as the original function. It may also revert with another `OffchainLookup`, restarting the loop.\n\nKey rules:\n\n- `sender` must equal the contract the client called; otherwise the client refuses. This stops a lookup raised deep inside a nested call from being mistaken for the top-level answer. CCIP-aware contracts that call other contracts must catch and re-wrap such errors rather than letting them bubble up.\n- `extraData` is opaque and must be passed back unchanged. The contract should put anything it needs to verify the answer there, rather than trusting the gateway to echo the query.\n- On a 4xx response the client stops with an error; on 5xx it tries the next URL.\n- Clients must cap the number of chained lookups per call (at least 4 is recommended).\n- The same flow can preflight a transaction: run the lookup during `eth_call`/`eth_estimateGas`, then send the callback as the real transaction.\n\n## Sample code\n\nContract side (verification logic omitted):\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract OffchainBalances {\n    error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);\n\n    string[] public urls = [\"https://gateway.example/{sender}/{data}.json\"];\n\n    function balanceOf(address addr) external view returns (uint256) {\n        revert OffchainLookup(\n            address(this),\n            urls,\n            abi.encode(addr),                     // sent to the gateway\n            this.balanceOfWithProof.selector,\n            abi.encode(addr)                      // kept by the client, returned untouched\n        );\n    }\n\n    function balanceOfWithProof(bytes calldata response, bytes calldata extraData)\n        external view returns (uint256)\n    {\n        address addr = abi.decode(extraData, (address));\n        (uint256 balance, bytes memory proof) = abi.decode(response, (uint256, bytes));\n        require(_verify(addr, balance, proof), \"bad proof\");\n        return balance;\n    }\n\n    function _verify(address, uint256, bytes memory) internal pure returns (bool) {\n        return true; // replace with a signature or Merkle proof check\n    }\n}\n```\n\nClient side with ethers v6, which implements the lookup loop when asked:\n\n```ts\nimport { Interface, JsonRpcProvider } from \"ethers\";\n\nconst provider = new JsonRpcProvider(process.env.RPC_URL);\nconst iface = new Interface([\"function balanceOf(address) view returns (uint256)\"]);\nconst raw = await provider.call({\n  to: contractAddress,\n  data: iface.encodeFunctionData(\"balanceOf\", [user]),\n  enableCcipRead: true, // follow OffchainLookup reverts\n});\nconst [bal] = iface.decodeFunctionResult(\"balanceOf\", raw);\n```\n\n## Things to know\n\n- Status: **Final**.\n- The trust model is set by the callback, not by the protocol. A callback that skips verification simply trusts whatever server answers.\n- Gateways see every query, which has privacy implications, and an unavailable gateway makes the function unusable; listing several URLs helps.\n- ENS name resolution through offchain or L2 resolvers relies on this flow together with wildcard resolution ([ERC-2544](/eip-2544/)). [ERC-5559](/eip-5559/) (Stagnant) sketched a similar deferral pattern for writes.\n"},"ja":{"lang":"ja","tldr":"コントラクトが、オフチェーンのゲートウェイを指すポインタとともに revert することで呼び出しに応答できるようにし、クライアントがデータを取得して、検証のためにコントラクトへ渡し直す。","tags":["offchain","ccip-read","gateway","ens","l2"],"related":[137,2544,5559],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-3668/","markdown":"## 何を解決するのか\n\nオンチェーンにデータを保存するのは高価なので、多くのアプリケーションはデータを別の場所（Merkle ツリー、L2、普通のサーバー）に置き、検証に必要な最小限だけをオンチェーンに保存します。この ERC 以前は、そうしたプロジェクトがそれぞれ独自の検索方式を発明しており、ウォレットや dapp はそれぞれを個別に統合しなければなりませんでした。\n\nCCIP Read（「Durin」とも呼ばれる）は、汎用的なフローを 1 つ定義します。コントラクトが、足りないデータを*どこで*取得するかをクライアントに伝え、クライアントが HTTPS でそれを取得し、コントラクトが回答を検証します。このフローを一度実装したクライアントは、詳細を知らなくても、どのストレージバックエンドを使うコントラクトからでも読み取れます。ENS は、レコードがオフチェーンや L2 にある名前の解決にこれを使っています。\n\n## 仕組み\n\n1. **コントラクトを呼び出す。** 関数は値を返す代わりに、次のエラーで revert します。\n   ```solidity\n   error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);\n   ```\n2. **ゲートウェイに問い合わせる。** クライアントは `urls` から URL テンプレートを選び、`{sender}`（小文字の 16 進アドレス）と `{data}`（16 進の `callData`）を置換します。テンプレートに `{data}` が含まれていれば GET を送り、そうでなければ JSON `{\"data\": ..., \"sender\": ...}` を POST します。ゲートウェイは JSON `{\"data\": \"0x...\"}` で応答します。\n3. **コールバックする。** クライアントは同じコントラクトの `callbackFunction(response, extraData)` を呼び出します。コールバックは応答を検証（署名、Merkle 証明、ストレージ証明など）し、元の関数と同じ戻り値の型で結果を返します。別の `OffchainLookup` で revert して、ループを再開することもできます。\n\n主なルール:\n\n- `sender` はクライアントが呼び出したコントラクトと等しくなければならず、そうでなければクライアントは拒否します。これにより、ネストした呼び出しの深部で発生したルックアップが、最上位の回答と取り違えられるのを防ぎます。他のコントラクトを呼び出す CCIP 対応コントラクトは、そのようなエラーをそのまま上に伝播させるのではなく、キャッチして包み直さなければなりません。\n- `extraData` は不透明で、変更せずに返さなければなりません。コントラクトは、ゲートウェイがクエリをそのまま返すことを信頼するのではなく、回答の検証に必要なものをそこに入れるべきです。\n- 4xx 応答ではクライアントはエラーで停止し、5xx では次の URL を試します。\n- クライアントは、1 回の呼び出しあたりの連鎖するルックアップの数に上限を設けなければなりません（少なくとも 4 を推奨）。\n- 同じフローでトランザクションのプリフライトもできます。`eth_call`/`eth_estimateGas` の間にルックアップを実行し、その後コールバックを実際のトランザクションとして送ります。\n\n## サンプルコード\n\nコントラクト側（検証ロジックは省略）:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract OffchainBalances {\n    error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);\n\n    string[] public urls = [\"https://gateway.example/{sender}/{data}.json\"];\n\n    function balanceOf(address addr) external view returns (uint256) {\n        revert OffchainLookup(\n            address(this),\n            urls,\n            abi.encode(addr),                     // sent to the gateway\n            this.balanceOfWithProof.selector,\n            abi.encode(addr)                      // kept by the client, returned untouched\n        );\n    }\n\n    function balanceOfWithProof(bytes calldata response, bytes calldata extraData)\n        external view returns (uint256)\n    {\n        address addr = abi.decode(extraData, (address));\n        (uint256 balance, bytes memory proof) = abi.decode(response, (uint256, bytes));\n        require(_verify(addr, balance, proof), \"bad proof\");\n        return balance;\n    }\n\n    function _verify(address, uint256, bytes memory) internal pure returns (bool) {\n        return true; // replace with a signature or Merkle proof check\n    }\n}\n```\n\nethers v6 によるクライアント側。要求すればルックアップのループを実装してくれます。\n\n```ts\nimport { Interface, JsonRpcProvider } from \"ethers\";\n\nconst provider = new JsonRpcProvider(process.env.RPC_URL);\nconst iface = new Interface([\"function balanceOf(address) view returns (uint256)\"]);\nconst raw = await provider.call({\n  to: contractAddress,\n  data: iface.encodeFunctionData(\"balanceOf\", [user]),\n  enableCcipRead: true, // follow OffchainLookup reverts\n});\nconst [bal] = iface.decodeFunctionResult(\"balanceOf\", raw);\n```\n\n## 知っておくべきこと\n\n- ステータス: **Final**。\n- 信頼モデルを決めるのはプロトコルではなくコールバックです。検証を省略するコールバックは、どのサーバーが応答しても単にそれを信頼することになります。\n- ゲートウェイはすべてのクエリを見るため、プライバシー上の影響があります。ゲートウェイが利用できなければ関数は使えなくなるため、複数の URL を列挙すると助けになります。\n- オフチェーンや L2 のリゾルバーを通じた ENS の名前解決は、このフローとワイルドカード解決（[ERC-2544](/eip-2544/)）に依存しています。[ERC-5559](/eip-5559/)（Stagnant）は、書き込み向けに似た遅延パターンを素描しました。\n"},"ko":{"lang":"ko","tldr":"컨트랙트가 오프체인 게이트웨이를 가리키는 포인터와 함께 revert하여 호출에 응답하게 하고, 클라이언트가 데이터를 가져와 검증을 위해 컨트랙트에 다시 건네게 한다.","tags":["offchain","ccip-read","gateway","ens","l2"],"related":[137,2544,5559],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-3668/","markdown":"## 어떤 문제를 해결하나요?\n\n온체인에 데이터를 저장하는 것은 비싸기 때문에 많은 애플리케이션이 데이터를 다른 곳(Merkle 트리, L2, 일반 서버)에 두고 검증에 필요한 최소한만 온체인에 저장합니다. 이 ERC 이전에는 그런 프로젝트마다 자체 조회 방식을 만들어 냈고, 지갑이나 dapp은 각각을 따로 연동해야 했습니다.\n\nCCIP Read(\"Durin\"이라고도 함)는 하나의 범용 흐름을 정의합니다. 컨트랙트가 부족한 데이터를 *어디서* 가져올지 클라이언트에 알려 주고, 클라이언트가 HTTPS로 가져오며, 컨트랙트가 응답을 검사합니다. 이 흐름을 한 번 구현한 클라이언트는 세부 사항을 몰라도 어떤 스토리지 백엔드를 쓰는 컨트랙트에서든 읽을 수 있습니다. ENS는 레코드가 오프체인이나 L2에 있는 이름을 해석하는 데 이를 사용합니다.\n\n## 어떻게 동작하나요?\n\n1. **컨트랙트를 호출합니다.** 함수는 값을 반환하는 대신 다음 에러로 revert합니다.\n   ```solidity\n   error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);\n   ```\n2. **게이트웨이에 질의합니다.** 클라이언트는 `urls`에서 URL 템플릿을 하나 골라 `{sender}`(소문자 16진수 주소)와 `{data}`(16진수 `callData`)를 치환합니다. 템플릿에 `{data}`가 있으면 GET을 보내고, 없으면 JSON `{\"data\": ..., \"sender\": ...}`를 POST합니다. 게이트웨이는 JSON `{\"data\": \"0x...\"}`로 응답합니다.\n3. **콜백합니다.** 클라이언트는 같은 컨트랙트의 `callbackFunction(response, extraData)`를 호출합니다. 콜백은 응답을 검증(서명, Merkle 증명, 스토리지 증명 등)하고 원래 함수와 같은 반환 타입으로 결과를 반환합니다. 또 다른 `OffchainLookup`으로 revert해 루프를 다시 시작할 수도 있습니다.\n\n핵심 규칙:\n\n- `sender`는 클라이언트가 호출한 컨트랙트와 같아야 하며, 그렇지 않으면 클라이언트는 거부합니다. 이는 중첩된 호출 깊은 곳에서 발생한 조회가 최상위 응답으로 오인되는 것을 막습니다. 다른 컨트랙트를 호출하는 CCIP 인식 컨트랙트는 그런 에러를 위로 그대로 전파하지 말고 잡아서 다시 감싸야 합니다.\n- `extraData`는 불투명하며 변경 없이 그대로 돌려줘야 합니다. 컨트랙트는 게이트웨이가 질의를 그대로 되돌려 주리라 신뢰하는 대신, 응답을 검증하는 데 필요한 것을 여기에 넣어야 합니다.\n- 4xx 응답이면 클라이언트는 에러로 중단하고, 5xx이면 다음 URL을 시도합니다.\n- 클라이언트는 호출당 연쇄 조회 횟수에 상한을 두어야 합니다(최소 4회를 권장).\n- 같은 흐름으로 트랜잭션을 사전 점검(preflight)할 수도 있습니다. `eth_call`/`eth_estimateGas` 중에 조회를 실행한 뒤, 콜백을 실제 트랜잭션으로 보냅니다.\n\n## 샘플 코드\n\n컨트랙트 쪽(검증 로직 생략):\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract OffchainBalances {\n    error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);\n\n    string[] public urls = [\"https://gateway.example/{sender}/{data}.json\"];\n\n    function balanceOf(address addr) external view returns (uint256) {\n        revert OffchainLookup(\n            address(this),\n            urls,\n            abi.encode(addr),                     // sent to the gateway\n            this.balanceOfWithProof.selector,\n            abi.encode(addr)                      // kept by the client, returned untouched\n        );\n    }\n\n    function balanceOfWithProof(bytes calldata response, bytes calldata extraData)\n        external view returns (uint256)\n    {\n        address addr = abi.decode(extraData, (address));\n        (uint256 balance, bytes memory proof) = abi.decode(response, (uint256, bytes));\n        require(_verify(addr, balance, proof), \"bad proof\");\n        return balance;\n    }\n\n    function _verify(address, uint256, bytes memory) internal pure returns (bool) {\n        return true; // replace with a signature or Merkle proof check\n    }\n}\n```\n\nethers v6를 쓰는 클라이언트 쪽. 요청하면 조회 루프를 구현해 줍니다.\n\n```ts\nimport { Interface, JsonRpcProvider } from \"ethers\";\n\nconst provider = new JsonRpcProvider(process.env.RPC_URL);\nconst iface = new Interface([\"function balanceOf(address) view returns (uint256)\"]);\nconst raw = await provider.call({\n  to: contractAddress,\n  data: iface.encodeFunctionData(\"balanceOf\", [user]),\n  enableCcipRead: true, // follow OffchainLookup reverts\n});\nconst [bal] = iface.decodeFunctionResult(\"balanceOf\", raw);\n```\n\n## 알아둘 점\n\n- 상태: **Final**.\n- 신뢰 모델은 프로토콜이 아니라 콜백이 정합니다. 검증을 건너뛰는 콜백은 어떤 서버가 응답하든 그냥 신뢰하는 셈입니다.\n- 게이트웨이는 모든 질의를 보므로 프라이버시에 영향이 있고, 게이트웨이를 쓸 수 없으면 함수를 사용할 수 없게 됩니다. 여러 URL을 나열하면 도움이 됩니다.\n- 오프체인이나 L2 리졸버를 통한 ENS 이름 해석은 이 흐름과 와일드카드 해석([ERC-2544](/eip-2544/))에 의존합니다. [ERC-5559](/eip-5559/)(Stagnant)는 쓰기에 대한 비슷한 지연 패턴을 스케치했습니다.\n"},"zh":{"lang":"zh","tldr":"让合约通过回滚并附带指向链下网关的指针来响应调用，客户端据此获取数据，再交还给合约验证。","tags":["offchain","ccip-read","gateway","ens","l2"],"related":[137,2544,5559],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-3668/","markdown":"## 它解决什么问题？\n\n在链上存储数据很昂贵，所以许多应用把数据放在别处（Merkle 树、L2、普通服务器），只在链上保存足以验证它的最少信息。在这个 ERC 出现之前，每个这样的项目都发明了自己的查询方案，钱包和 dapp 不得不分别集成每一种。\n\nCCIP Read（也称\"Durin\"）定义了一个通用流程：合约告诉客户端到*哪里*获取缺失的数据，客户端通过 HTTPS 获取，合约再检查答案。实现过一次该流程的客户端，无需了解细节，就能读取使用任何存储后端的任何合约。ENS 用它来解析记录存放在链下或 L2 上的名称。\n\n## 它如何运作\n\n1. **调用合约。** 函数不返回结果，而是以如下错误回滚：\n   ```solidity\n   error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);\n   ```\n2. **查询网关。** 客户端从 `urls` 中选一个 URL 模板，替换其中的 `{sender}`（小写十六进制地址）和 `{data}`（十六进制 `callData`）。如果模板包含 `{data}`，就发送 GET；否则 POST JSON `{\"data\": ..., \"sender\": ...}`。网关以 JSON `{\"data\": \"0x...\"}` 响应。\n3. **回调。** 客户端在同一个合约上调用 `callbackFunction(response, extraData)`。回调验证响应（签名、Merkle 证明、存储证明……），并以与原函数相同的返回类型返回结果。它也可以再次以另一个 `OffchainLookup` 回滚，从而重新开始循环。\n\n关键规则：\n\n- `sender` 必须等于客户端所调用的合约，否则客户端会拒绝。这样可以避免在嵌套调用深处抛出的查询被误认为是顶层的答案。会调用其他合约的支持 CCIP 的合约，必须捕获并重新包装这类错误，而不能让它们直接向上冒泡。\n- `extraData` 是不透明的，必须原样传回。合约应把验证答案所需的任何内容放在这里，而不是信任网关把查询原样回显。\n- 收到 4xx 响应时，客户端以错误终止；收到 5xx 时，则尝试下一个 URL。\n- 客户端必须限制每次调用中连锁查询的次数（建议至少为 4）。\n- 同样的流程也可用于对交易做预检：在 `eth_call`/`eth_estimateGas` 期间运行查询，然后把回调作为真正的交易发送。\n\n## 示例代码\n\n合约端（省略验证逻辑）：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract OffchainBalances {\n    error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);\n\n    string[] public urls = [\"https://gateway.example/{sender}/{data}.json\"];\n\n    function balanceOf(address addr) external view returns (uint256) {\n        revert OffchainLookup(\n            address(this),\n            urls,\n            abi.encode(addr),                     // sent to the gateway\n            this.balanceOfWithProof.selector,\n            abi.encode(addr)                      // kept by the client, returned untouched\n        );\n    }\n\n    function balanceOfWithProof(bytes calldata response, bytes calldata extraData)\n        external view returns (uint256)\n    {\n        address addr = abi.decode(extraData, (address));\n        (uint256 balance, bytes memory proof) = abi.decode(response, (uint256, bytes));\n        require(_verify(addr, balance, proof), \"bad proof\");\n        return balance;\n    }\n\n    function _verify(address, uint256, bytes memory) internal pure returns (bool) {\n        return true; // replace with a signature or Merkle proof check\n    }\n}\n```\n\n使用 ethers v6 的客户端，在被要求时它会实现查询循环：\n\n```ts\nimport { Interface, JsonRpcProvider } from \"ethers\";\n\nconst provider = new JsonRpcProvider(process.env.RPC_URL);\nconst iface = new Interface([\"function balanceOf(address) view returns (uint256)\"]);\nconst raw = await provider.call({\n  to: contractAddress,\n  data: iface.encodeFunctionData(\"balanceOf\", [user]),\n  enableCcipRead: true, // follow OffchainLookup reverts\n});\nconst [bal] = iface.decodeFunctionResult(\"balanceOf\", raw);\n```\n\n## 需要注意\n\n- 状态：**Final**。\n- 信任模型由回调决定，而不是由协议决定。跳过验证的回调等于直接信任任何响应的服务器。\n- 网关能看到每一次查询，这会带来隐私方面的影响；网关不可用会让该函数无法使用，列出多个 URL 有所帮助。\n- 通过链下或 L2 解析器进行的 ENS 名称解析，依赖该流程以及通配符解析（[ERC-2544](/eip-2544/)）。[ERC-5559](/eip-5559/)（Stagnant）为写入勾勒了类似的延迟模式。\n"}},"requiredBy":[7694,8121,8143]}
