Introduction
Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.
I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.
I also build and publish a variety of tools, libraries, and open-source projects.
ERC-3668 defines a mechanism for retrieving and verifying external data without storing everything on-chain.
This article explains the proposal, with additional context and examples.
My other articles cover EIPs, BIPs, SLIPs, CAIPs, ENSIPs, RFCs, and ACPs.
Overview
ERC-3668 standardizes how smart contracts obtain externally stored data. Instead of returning the requested value immediately, a contract reverts with a custom error called OffchainLookup.
The error contains gateway URLs, request data, and a callback selector. The client sends a request to a gateway using this information, obtains a response, and calls the contract's callback with the response. The callback verifies the data according to the application's rules.
This allows clients to handle external data transparently while leaving the verification mechanism to contract developers. Depending on the verification scheme, applications can use data more efficiently than storing it all on-chain without introducing additional trust assumptions.
For more background on CCIP, see the following resource.
Motivation
High storage and transaction costs on Ethereum have encouraged developers to move data off-chain. Approaches include storing hashes or Merkle roots and using Layer 2 networks. These approaches retain only the information required for verification on-chain and check externally supplied data against it when needed.
Historically, projects developed their own retrieval mechanisms. A mechanism that worked for one application was not necessarily compatible with clients or developers working with another.
ERC-3668 lets compatible clients retrieve offchain data without having to know how each application stores it. Possible use cases include:
- Interacting with a contract that uses an externally stored list of eligible airdrop recipients.
- Displaying token information stored on Layer 2 through an interface on Layer 1.
- Resolving ENS data delegated to a Layer 2 network without requiring custom client support for that particular storage scheme.
- Allowing a contract to request external data when needed without requiring its caller to know the details of the retrieval mechanism in advance.
A common offchain lookup protocol makes Ethereum applications more flexible and efficient.
Specification
Overview
CCIP Read provides a standard flow for retrieving information external to a smart contract. It consists of three main steps.
Step 1: Query the contract
The client invokes a contract function as it would for an ordinary blockchain call. If the function needs external data, it reverts with OffchainLookup rather than returning an immediate answer.
The error contains:
- Gateway URLs for obtaining the external data.
- Request data (
callData). - The callback function selector (
callbackFunction). - Additional context required later (
extraData).
The contract is instructing the client to retrieve the required information from a gateway.
Step 2: Query the gateway
The client sends an HTTP request to a gateway using the information from the first step. The request includes the contract's callData. The gateway processes the request and returns a response.
The response payload is opaque to the client; it does not need to interpret its application-specific meaning.
Step 3: Call the contract again
The client calls the contract's callback, passing the gateway response and the original extraData as arguments.
The contract verifies the supplied information and, if verification succeeds, returns the result or proceeds with the relevant transaction logic.
If additional external data is required, the callback can revert with another OffchainLookup. The client then repeats the lookup flow within its configured recursion limit.
Complete lookup flow
The following diagram shows the interaction between the client, contract, and gateway.
┌──────┐ ┌────────┐ ┌─────────────┐
│Client│ │Contract│ │Gateway @ url│
└──┬───┘ └───┬────┘ └──────┬──────┘
│ │ │
│ somefunc(...) │ │
├─────────────────────────────────────────────────►│ │
│ │ │
│ revert OffchainLookup(sender, urls, callData, │ │
│ callbackFunction, extraData) │ │
│◄─────────────────────────────────────────────────┤ │
│ │ │
│ HTTP request (sender, callData) │ │
├──────────────────────────────────────────────────┼────────────►│
│ │ │
│ Response (result) │ │
│◄─────────────────────────────────────────────────┼─────────────┤
│ │ │
│ callbackFunction(result, extraData) │ │
├─────────────────────────────────────────────────►│ │
│ │ │
│ answer │ │
│◄─────────────────────────────────────────────────┤ │
│ │ │Contracts supporting CCIP Read
When a function requires offchain data, a CCIP Read contract signals this by reverting with the OffchainLookup error. This tells the client where and how to retrieve the necessary information.
The OffchainLookup error
The contract defines the following error and uses it when external data is required.
error OffchainLookup(
address sender,
string[] urls,
bytes callData,
bytes4 callbackFunction,
bytes extraData
);-
senderThe address of the contract issuing the error. It allows the caller to distinguish an error from the contract it invoked from one propagated by an inner contract. -
urlsA list of gateway URLs. It may be empty, in which case a client would need its own configured retrieval mechanism or fail the lookup. When multiple URLs are supplied, the preferred ordering should be reflected in the list. URL templates may contain the placeholders{sender}and{data}, which are replaced with the contract address and request data. -
callDataThe request payload for the gateway. It is commonly ABI-encoded, but its application-specific format is determined by the contract and gateway. -
callbackFunctionA four-byte function selector identifying the callback to invoke after receiving the gateway response. -
extraDataAdditional context needed by the callback. The client passes this value through unchanged.
Implementing the callback
The contract implements a callback to validate the gateway response. Its general shape is shown below.
function callback(bytes response, bytes extraData)
public view returns (同じ戻り値型);The Japanese placeholder in this pseudocode means "the same return type." The callback must return data compatible with the original function's return type, so the lookup can appear transparent to the caller.
A callback may also revert with another OffchainLookup to request more external data. Clients impose a limit on repeated lookups.
Implementation example
Consider a balanceOf function whose balance data is stored off-chain. A gateway supplies a proof, which the contract then verifies.
function balanceOf(address addr) public view returns(uint balance) {
revert OffchainLookup(
address(this),
[url],
abi.encodeWithSelector(Gateway.getSignedBalance.selector, addr),
ContractName.balanceOfWithProof.selector,
abi.encode(addr)
);
}The address addr appears in both callData and extraData. The gateway needs it to identify the requested balance, and the contract needs it to verify that the response corresponds to the original query. If the contract obtained the address only from the gateway's response, a malicious gateway could substitute data belonging to a different address.
Handling nested CCIP Read calls
A CCIP Read contract may call another contract that also implements CCIP Read. Care is needed when handling an OffchainLookup error raised in a nested call. Incorrect propagation can cause the client to interpret an intermediate result as the result of the original call.
Rules for nested calls
When a CCIP-aware contract calls another contract:
- If the called contract reverts with
OffchainLookup, the caller must verify that the error'ssendermatches the callee. A mismatch must be rejected with another error, such asInvalidOperation. - The caller must not simply propagate the callee's
OffchainLookupunchanged. In nested or reentrant call patterns, an error can otherwise appear to come from the outermost contract, causing the client to handle it incorrectly. - A simpler implementation can reject nested CCIP lookups entirely by replacing any such errors with a different error. This avoids supporting recursive contract composition.
An error "bubbles up" when it propagates through the call stack to a caller without being handled.
In Solidity and CCIP Read, an error such as OffchainLookup bubbles up if a contract calls another contract and passes the resulting error back to its own caller without special handling.
Example of incorrect behavior
If nested OffchainLookup errors are propagated unchanged, the following situation can arise:
- Contract A calls contract B.
- B calls A again.
- A reverts with
OffchainLookupin the nested call. - B does not understand CCIP Read and propagates the error.
- A also propagates the error.
- The client sees what appears to be an error issued directly by A, even though it arose during a nested call. Handling it as a top-level lookup may produce an incorrect result.
Implementation example
The following conceptual example illustrates how to handle a nested lookup. It uses Solidity-like try/catch syntax. The original example is pseudocode, not a compilable implementation: typed custom-error catches and the low-level call shown in the callback require appropriate implementation changes.
contract NestedLookup {
error InvalidOperation();
error OffchainLookup(
address sender,
string[] urls,
bytes callData,
bytes4 callbackFunction,
bytes extraData
);
function a(bytes calldata data) external view returns(bytes memory) {
try target.b(data) returns (bytes memory ret) {
return ret;
} catch OffchainLookup(
address sender,
string[] urls,
bytes callData,
bytes4 callbackFunction,
bytes extraData
) {
if(sender != address(target)) {
revert InvalidOperation();
}
revert OffchainLookup(
address(this),
urls,
callData,
NestedLookup.aCallback.selector,
abi.encode(address(target), callbackFunction, extraData)
);
}
}
function aCallback(bytes calldata response, bytes calldata extraData)
external view returns(bytes memory)
{
(address inner, bytes4 innerCallbackFunction, bytes memory innerExtraData) =
abi.decode(extraData, (address, bytes4, bytes));
return abi.decode(
inner.call(
abi.encodeWithSelector(innerCallbackFunction, response, innerExtraData)
),
(bytes)
);
}
}- The
try/catchillustrates intercepting anOffchainLookupfrom the callee. - The caller verifies that
sendermatchestargetand rejects invalid errors withInvalidOperation. - If the error is valid, the caller constructs its own
OffchainLookup, encoding the callee address, original callback selector, and original additional data in itsextraData. - The
aCallbackfunction illustrates restoring the inner callback context so the original callback can be invoked correctly. A production implementation must also preserve the remaining outer-call logic.
Gateway interface
CCIP Read obtains data from a gateway using URLs specified in an OffchainLookup error. Standard request and response formats allow compatible clients and gateways to communicate.
URL templates and request formats
A contract's URLs may contain two placeholders:
{sender}is replaced by the contract address, formatted as lowercase hexadecimal with a0xprefix.{data}is replaced by the hexadecimal representation ofcallData, also with a0xprefix.
These substitutions produce the request URL.
For example:
urls = ["https://example.com/gateway/{sender}/{data}.json"]
sender = "0xaabbccddeeaabbccddeeaabbccddeeaabbccddee"
callData = "0x00112233"The resulting URL is:
https://example.com/gateway/0xaabbccddeeaabbccddeeaabbccddeeaabbccddee/0x00112233.jsonChoosing between GET and POST
- If the URL includes
{data}, the client sends a GET request. - If the URL does not include
{data}, the client sends a POST request.
For POST, the client uses an application/json request body with the following structure.
{
"data": "0x-prefixed hex string containing the callData from the contract",
"sender": "0x-prefixed hex string containing the sender parameter from the contract"
}Gateway response format
A successful gateway response uses application/json and contains the result bytes in the following structure.
{
"data": "0x-prefixed hex string containing the result data."
}On failure, the gateway returns an appropriate HTTP status code. A JSON error response may contain a human-readable message.
{
"message": "A human-readable error message."
}For instance, an unsupported address may result in a 404, invalid request data in a 400, and an internal server failure in a 500.
Request examples
GET request
# リクエスト
curl -D - https://example.com/gateway/0x226159d592E2b063810a10Ebf6dcbADA94Ed68b8/0xd5fa2b00.json
# 正常な応答
HTTP/2 200
content-type: application/json; charset=UTF-8
{"data": "0xdeadbeefdecafbad"}
# エラー応答
HTTP/2 404
content-type: application/json; charset=UTF-8
{"message": "Gateway address not supported."}POST request
# リクエスト
curl -D - -X POST -H "Content-Type: application/json" \
--data '{"data":"0xd5fa2b00","sender":"0x226159d592E2b063810a10Ebf6dcbADA94Ed68b8"}' \
https://example.com/gateway/0x226159d592E2b063810a10Ebf6dcbADA94Ed68b8.json
# 正常な応答
HTTP/2 200
content-type: application/json; charset=UTF-8
{"data": "0xdeadbeefdecafbad"}
# エラー応答
HTTP/2 404
content-type: application/json; charset=UTF-8
{"message": "Gateway address not supported."}The original shell examples retain their Japanese comments: request, successful response, and error response.
Client lookup protocol
A client supporting CCIP Read must handle the offchain lookup flow in addition to ordinary smart contract calls.
Basic flow
The client first invokes the target contract using the contract address and call data. If the function succeeds, the client returns the result to the user. Ordinary errors are propagated as usual.
When the call reverts with OffchainLookup, the client extracts sender, urls, callData, callbackFunction, and extraData and continues the lookup. It verifies that the sender matches the contract it invoked before making a gateway request.
Constructing URLs and making external requests
The client substitutes sender and callData into the supplied URL templates. When several gateways are available, it generally tries them in list order.
The client sends an HTTP request. Under the protocol's error handling rules, a 4xx response terminates the lookup with an error. A 5xx response allows the client to try another available gateway. A successful 2xx response supplies the result data. If no eligible gateway succeeds, the lookup fails.
Executing the callback
After obtaining the gateway response, the client invokes the specified callbackFunction with the response and extraData. The contract validates the response and returns the result, or may request further information through another OffchainLookup.
To avoid unbounded recursion, clients must limit repeated lookups. The specification recommends allowing at least four.
Pseudocode
The specification describes the client behavior using pseudocode. The following example illustrates the flow rather than a runnable HTTP client.
async function httpcall(urls, to, callData) {
const args = {sender: to.toLowerCase(), data: callData.toLowerCase()};
for(const url of urls) {
const queryUrl = url.replace(/\{([^}]*)\}/g, (match, p1) => args[p1]);
// GET または POST リクエスト
const response = await fetch(queryUrl, url.includes('{data}') ? undefined : args);
const result = await response.text();
if(result.statusCode >= 400 && result.statusCode <= 499) {
throw new Error(data.error.message);
}
if(result.statusCode >= 200 && result.statusCode <= 299) {
return result;
}
}
}
async function durin_call(provider, to, data) {
for(let i = 0; i < 4; i++) {
try {
return await provider.call(to, data);
} catch(error) {
if(error.code !== "CALL_EXCEPTION") {
throw(error);
}
const {sender, urls, callData, callbackFunction, extraData} = error.data;
if(sender !== to) {
throw new Error("Cannot handle OffchainLookup raised inside nested call");
}
const result = httpcall(urls, to, callData);
data = abi.encodeWithSelector(callbackFunction, result, extraData);
}
}
throw new Error("Too many CCIP read redirects");
}Using CCIP Read in transactions
CCIP Read is commonly used for read-only calls such as eth_call, but its lookup mechanism can also be applied to transactions submitted through methods such as eth_sendTransaction or eth_sendRawTransaction.
This enables applications that combine on-chain execution with offchain proofs.
Transaction flow
Before submitting a transaction, clients often use eth_estimateGas or eth_call to simulate its execution. If the simulation produces an OffchainLookup, the client retrieves external data using the client lookup protocol.
The difference is that the final callback invocation is submitted as an actual transaction instead of just a read-only call. The client constructs the transaction with the gateway response and the required callback data, then submits it after the applicable authorization and signing steps.
Example use case
A user might need to claim an on-chain entitlement using a proof stored off-chain. The client obtains that proof from a gateway, embeds it in the transaction data, and submits it to the smart contract for verification.
Terminology
-
Client A browser JavaScript application, backend service, or other component that queries the blockchain and understands the CCIP Read lookup procedure.
-
Contract A smart contract deployed on a blockchain such as Ethereum.
-
Gateway A service that responds to CCIP Read requests for an application, typically over HTTPS.
Rationale
Why use a revert to communicate lookup instructions?
A client needs to know when a contract function requires external data. One alternative would be to add a special marker to the ABI. However, extending existing functions this way would complicate compatibility and could introduce different return types for the same function, leading to decoding failures in existing clients. Developers might also need duplicate functions such as offchainBalanceOf alongside balanceOf.
Using a custom revert instead keeps the function interface unchanged. A contract can signal that external data is needed by reverting with OffchainLookup, allowing CCIP-aware clients to extend the existing call flow.
Why send the contract address to the gateway?
A gateway should ideally support multiple contracts using the same interface rather than only one contract.
Passing the contract address as sender lets the gateway identify and, if necessary, query the original contract for additional information. Multiple contracts can share a general-purpose gateway, reducing the implementation burden.
Why include extraData?
The context of the initial execution is not automatically preserved across separate calls. The extraData field carries information from the original request to the callback, allowing the callback to validate that a response corresponds to that request.
For example, the callback can detect a gateway response for a different query if it has sufficient context and verifies the relevant proof.
Why support both GET and POST?
GET and POST serve different gateway requirements.
- GET is simple and places query data in the URL. It can work with static web servers or files hosted on IPFS, making it useful for straightforward use cases.
- URL length can be limited by browsers, servers, and intermediaries. Around 2 KB is a conservative practical compatibility consideration, not a universal HTTP limit.
POST allows more complex or larger payloads to be sent in a JSON body. Supporting both approaches accommodates simple static gateways and more flexible services.
Compatibility
CCIP Read is designed with existing contracts and clients in mind. Contracts that use offchain retrieval can coexist with contracts that retain conventional behavior.
Effect on existing contracts
Contracts that do not use ERC-3668 continue to behave as before. Ordinary calls and error handling still work, including for clients that do not understand CCIP Read. Developers can choose whether to adopt the protocol.
Supporting clients
A compatible client extends the existing call flow to handle OffchainLookup when encountered. Ordinary successful contract calls do not require additional gateway requests.
Clients without CCIP Read support
A contract that relies on CCIP Read requires a compatible client. Otherwise, the client receives the OffchainLookup error but cannot complete the lookup, and the user sees a failed call.
Both the contract and the client must therefore support CCIP Read for this functionality to work.
Security considerations
Validating gateway responses
Contracts must include enough information in extraData to validate the gateway's response and detect malicious substitutions. For a request concerning a particular address, for example, the callback can use the original address to verify that the returned data belongs to the correct account.
The response itself must also be authenticated or verified using application-specific rules. Possible approaches include:
- Verifying Merkle proofs against a trusted state commitment, such as one representing a Layer 2 network's state.
- Verifying a signature over the response using a trusted signer's key.
These checks can detect tampered or fabricated responses under the application's trust assumptions. They cannot guarantee that a gateway will make data available.
Validating client-supplied extraData
When CCIP Read is used in transactions, an untrusted client may attempt to supply manipulated extraData. Contracts must repeat the relevant validation in the callback rather than relying on checks performed only during the initial simulated call.
For a transaction restricted to a specific address, for example, the callback must enforce authorization as well. Otherwise, an attacker may bypass restrictions by calling the callback directly with crafted data.
HTTP requests and fingerprinting
A CCIP Read client, such as a user's browser, sends HTTP requests to gateways. This creates privacy risks: a gateway operator may be able to correlate a user's IP address with a wallet address or other identifying request data.
The severity depends on the application. Resolving a public ENS name may reveal relatively little about a user's identity, while requests associated with a specific NFT transfer may provide more identifying information.
Recommended mitigations
The following measures can reduce these privacy risks:
- Client libraries should provide options to proxy or reject CCIP Read requests, with controls at the domain or contract level.
- CCIP Read for transactions should be disabled by default and enabled explicitly by the user.
- When invoking untrusted contract code, application developers should avoid including a
fromaddress in calls unless necessary. - Wallet developers should proxy CCIP Read requests used to retrieve user-related information, or disable transaction-related CCIP Read where appropriate.
These measures help retain the benefits of offchain retrieval while protecting user privacy and security.
Citation
Nick Johnson (@arachnid), "ERC-3668: CCIP Read—Secure offchain data retrieval," Ethereum Improvement Proposals, no. 3668, July 2020. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-3668.
Conclusion
ERC-3668 allows smart contracts to request and verify external data without storing all of it on-chain. The client coordinates the lookup, while the contract remains responsible for validating the returned data.
If you have questions, feel free to contact me on Twitter.
You can also find my work on the following sites.




