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.

ERC8121 proposes a way to construct a function call on another chain from a stored value. It packages the function, arguments, return type, chain, and contract into one value.

Overview

When an application reads metadata on one chain, it may need credentials stored on another. Storing only a function name does not specify the argument types, values to pass, how to interpret the return value, destination chain, or contract. A 20-byte address alone also risks confusing contracts that have the same address on different chains.

In ERC8121, a stored value containing the information required for a single function call is called a hook. A value combining the destination chain and contract is called a target. The process of validating the hook, calling the specified function, and extracting its result as the resolved value is called resolution.

A hook stores the function types, actual argument values, return type, and target. The target field contains an ERC7930 value combining the chain and contract address. The client decodes target to determine which contract on which chain to call.

A hook contains the information required to reproduce a call, but does not prove that its target is safe. The client validates the format and type consistency, establishes that the target is trusted, and only then calls the function.

The original diagrams are retained and contain Japanese labels.

Validating a hook in source metadata and calling a contract on another chain using an ERC7930 target

Rather than connecting the source directly to the execution destination, the client reads the hook and calls the target only if validation succeeds.

Referencing a Value on Another Chain

For example, a metadata key named kyc on a contract on Optimism can reference a credential registry on Ethereum mainnet. The source stores a hook describing the function that returns the credential and its destination, rather than the credential itself.

After reading the original metadata, the client connects to the chain identified by the hook and calls the specified contract function. ERC8121 is not a standard for moving state through a bridge; it is a representation format for resolving a value located elsewhere through a function call.

Storing the Information for One Call

A hook stores not only the function name but also its definition including argument types, the actual values to pass, return type, and target. It can optionally store a four-byte check value, which can be compared with the value calculated from the function definition.

Because this information is packaged together, the client can construct calldata without looking up a separate ABI file. It can also determine from the hook which type to use when decoding the return value.

Establishing Trust Before Execution

Being self-describing and being trustworthy are different properties. Even a hook pointing to a malicious target can be well-formed.

The client extracts the chain and contract address from the ERC7930 value and checks them against an allowlist or external registry. If the target is unverified, the client can stop without calling the function.

Motivation

Referencing metadata or credentials on another chain requires storing the function to call, its arguments, return type, chain, and contract. If these are kept in separate configurations or documents, their correspondence can break when one is updated. A client reading only the stored value cannot reconstruct the types to use for calldata or the chain to send it to.

ERC8121 defines a common format for storing function calls as bytes or string. Humans can inspect the call through its string representation, while clients can validate it mechanically using selectors and types. Credential registries, metadata shared across multiple contracts, and a single registry on a specific chain can all be handled using the same resolution procedure.

Comparing scattered chain, contract address, ABI, and argument information with information consolidated in a hook

On the left, the information exists but the relationships between its components are not stored. On the right, the hook binds the components together, allowing the call to be reconstructed from the stored value.

The Problem of Separating the Destination and ABI

A function name and argument values alone do not determine whether to encode an argument as bytes32 or bytes. A contract address alone does not establish whether to call it on Ethereum mainnet or Optimism.

Depending on external ABI documents and chain configuration means that the same stored value could point to different functions or contracts under different settings. ERC8121 includes the types and destination that determine interpretation in the hook itself.

An Address Alone Does Not Identify the Chain

A 20-byte Ethereum-style address does not identify the target chain by itself. ERC7930 packages the version, chain type, chain reference, and address into a length-prefixed bytes value. The client can identify both the target chain and contract address from that value.

For more on ERC7930, see the following article.

ERC7930: A Unified Format for Addresses Across Chains

A Storage Format Readable by Both Humans and Clients

The format separately stores a string specifying the function name and argument types and another string specifying the function name and actual values. For example, the former defines the getOwner function with its argument type, while the latter represents passing the value 42 to the same function.

Humans can read the call from the two strings. Clients can derive the selector and ABI encoding types from the type string and validate the stored values. The string format can also be embedded in plain text such as Markdown.

Specification

Hook Structure

A hook stores the following fields.

Field Type Required Stored content Usage
functionSelector bytes4 Optional Four-byte function selector Comparison with the signature
functionSignature string Required Function name and argument types Selector calculation and ABI encoding
functionCall string Required Function name and actual arguments Extracting the function name and values
returnType string Required Solidity tuple notation for the return value ABI decoding
target bytes Required Chain and address in ERC7930 format Identifying the destination

If functionSelector is present, the client calculates and compares the value equivalent to bytes4(keccak256(bytes(functionSignature))). It does not call a hook if the values do not match. If omitted, the client still calculates the selector for the call from functionSignature.

Two Hook Function Forms

The form including a selector is as follows.

js
function hook(
    bytes4 functionSelector,
    string calldata functionSignature,
    string calldata functionCall,
    string calldata returnType,
    bytes calldata target
)

The procedure calculates the selector from the signature, compares it with the stored value, encodes the arguments, and calls the target. The schema itself has no return value.

The form omitting the selector is as follows.

js
function hook(
    string calldata functionSignature,
    string calldata functionCall,
    string calldata returnType,
    bytes calldata target
)

In this form, functionSignature is the first parameter. The constants distinguishing the two forms are as follows.

js
bytes4 constant HOOK_SELECTOR_WITH_SELECTOR = 0x037f43ed;
bytes4 constant HOOK_SELECTOR_WITHOUT_SELECTOR = 0x6113bfa3;

These selectors identify the hook format itself and are distinct from the optional functionSelector inside the hook.

functionCall Syntax

Value Syntax Example
String Single quotes 'alice'
bytes or hex 0x prefix 0x1234abcd
Number Numeric literal 42
Array Square brackets [1, 2, 3]
Tuple Parentheses ('alice', 42, true)
js
hook(
    0xc41a360a,
    "getOwner(uint256)",
    "getOwner(42)",
    "(address)",
    0x000100000101141234567890abcdef1234567890abcdef12345678
)

ABI-encode 42 as uint256, and decode the return value as (address).

Hook Encoding

The representation differs depending on whether the storage type is bytes or string.

Positions used to detect the optional selector and field ordering in bytes and string forms

The upper portion distinguishes the format selector from the optional functionSelector. The lower portion determines whether functionSelector is present from the first argument of hook(.

Bytes Form

js
bytes memory withSelector = abi.encodeWithSelector(
    HOOK_SELECTOR_WITH_SELECTOR,
    functionSelector,
    functionSignature,
    functionCall,
    "(bytes)",
    target
);

bytes memory withoutSelector = abi.encodeWithSelector(
    HOOK_SELECTOR_WITHOUT_SELECTOR,
    functionSignature,
    functionCall,
    "(bytes)",
    target
);

If the leading bytes are 0x037f43ed, select the schema with a selector; if they are 0x6113bfa3, select the schema without one. Do not decode other values as ERC8121 bytes hooks.

String Form

js
hook(0x9e574b14, "getContractMetadata(string)", "getContractMetadata('kyc')", "(bytes)", 0x000100000101141234567890abcdef1234567890abcdef12345678)

hook("getContractMetadata(string)", "getContractMetadata('kyc')", "(bytes)", 0x000100000101141234567890abcdef1234567890abcdef12345678)

If the first argument is 0x followed by eight hexadecimal digits, the form includes a selector. Otherwise, the form starts with functionSignature.

Hook Detection

The client knows in advance which metadata keys may contain hooks. For bytes, check the two format selectors; for string, check for hook(. After detection, validate the field count, types, selector, and target rather than calling immediately.

Read Resolution

  1. Detect the format

    Check the bytes format selector or the string prefix hook(.

  2. Parse the hook

    Extract the five fields.

  3. Check the selector

    If a stored selector exists, compare it with the value calculated from the signature.

  4. Decode the target

    Extract the chain and address from ERC7930.

  5. Determine whether the target is trusted

    Stop if the target is unverified.

  6. Parse functionCall

    Extract the function name and values, and encode them according to the signature types.

  7. Enable ERC3668

    Enable it on the target chain's provider.

  8. Call the target

    Send the selector and ABI-encoded parameters.

  9. Obtain the result

    Decode according to returnType.

Nine stages from hook detection and target trust verification to an ERC3668-enabled call and result retrieval

Selector comparison prevents mismatches in function types, while target verification determines whether the destination can be trusted. Success in one check does not justify skipping the other.

ERC3668 defines a procedure for retrieving data from a gateway when a contract returns OffchainLookup and validating it through a callback on the original contract. ERC8121 read resolution calls the target using a provider with this procedure enabled.

For more on ERC3668, see the following article.

ERC3668: How Offchain Data Lookup Works

Write Execution

Write operations share the same steps as reads up to target validation. The difference is that they sign a state-changing transaction and broadcast it to the target chain rather than reading the result.

js
const tx = await signer.sendTransaction({
    to: targetAddress,
    data: encodedFunctionCall,
});
const receipt = await tx.wait();

This is a supplementary example, not a normative reference implementation. ERC8121 does not specify signing authority, gas, or confirmation.

Example: Resolving a KYC Credential

The official specification contains two code examples that call a KYC provider on Ethereum mainnet using kyc metadata on Optimism. These are examples demonstrating the sequence for storage and resolution, not a standalone reference implementation.

Storing a Hook in the Source Contract

js
bytes4 constant HOOK_SELECTOR_WITHOUT_SELECTOR = 0x6113bfa3;

string memory functionSignature = "getCredential(string)";
string memory functionCall = "getCredential('kyc: 0x76F1Ff0186DDb9461890bdb3094AF74A5F24a162')";

// Ethereum mainnetのKYCProviderを示すERC7930 address
bytes memory target = hex"000100000101141234567890abcdef1234567890abcdef12345678";

bytes memory hookData = abi.encodeWithSelector(
    HOOK_SELECTOR_WITHOUT_SELECTOR,
    functionSignature,
    functionCall,
    "(string)",
    target
);

originatingContract.setContractMetadata("kyc", hookData);

Because the example selects HOOK_SELECTOR_WITHOUT_SELECTOR, it does not store functionSelector inside the hook. The client calculates the selector from the definition of the getCredential function.

functionSignature determines the types, and functionCall contains the credential identifier as an actual argument. "(string)" instructs the client to decode the KYC provider's return value as a string. target combines Ethereum mainnet and the KYC provider's address.

abi.encodeWithSelector constructs bytes in the order of the format selector, function definition, actual arguments, return type, and target. setContractMetadata("kyc", hookData) stores those bytes under the kyc key on Optimism. This does not guarantee that the example address is a trusted provider.

Resolving the Hook in the Client

js
const value = await originatingContract.getContractMetadata("kyc");
const hasSelector = value.startsWith("0x037f43ed");
let functionSelector, functionSignature, functionCall, returnType, target;

if (value.startsWith("0x037f43ed") || value.startsWith("0x6113bfa3")) {
    if (hasSelector) {
        ({ functionSelector, functionSignature, functionCall, returnType, target } = decodeHook(value));
    } else {
        ({ functionSignature, functionCall, returnType, target } = decodeHook(value));
        functionSelector = null;
    }

    const computedSelector = keccak256(functionSignature).slice(0, 10);
    if (functionSelector && functionSelector !== computedSelector) {
        throw new Error("Selector mismatch");
    }
    const selectorToUse = functionSelector || computedSelector;

    const { chainId, address } = decodeERC7930(target);
    if (!isTrustedResolver(chainId, address)) {
        throw new Error("Untrusted resolver");
    }

    const { functionName, args } = parseFunctionCall(functionCall);
    const targetProvider = getProviderForChain(chainId);
    const targetContract = new ethers.Contract(
        address,
        [`function ${functionSignature} view returns (bytes)`],
        targetProvider.ccipReadEnabled(true)
    );

    const resultBytes = await targetContract[functionName](...args);
    const credential = ethers.utils.defaultAbiCoder.decode([returnType], resultBytes);
}

getContractMetadata retrieves raw bytes. If they start with either of the two format selectors, decodeHook extracts the fields. If the stored selector and computedSelector do not match, the code throws; if the selector was omitted, it uses the calculated value.

The official example calculates selectorToUse but does not directly reference it in the subsequent code. It is a conceptual example in which ethers constructs calldata containing the selector by receiving functionSignature in the ABI.

decodeERC7930 separates the target into chainId and address. If isTrustedResolver returns false, the code throws before making the RPC call. parseFunctionCall extracts the function name and actual arguments, and the provider is configured with ccipReadEnabled(true). Finally, the client calls the target and decodes resultBytes using returnType.

decodeHook, decodeERC7930, isTrustedResolver, parseFunctionCall, and getProviderForChain are conceptual helpers. The complete implementations are not provided, so copying this code alone will not produce a working program. An implementation must also specify escaping, payload size, RPC error handling, and supported chains.

Additional Details

Why Include Both the Selector and Signature?

Even functions with the same name, such as getData, have different selectors depending on whether their arguments are fixed-length or dynamic bytes. functionSignature provides a human-readable representation of the types, and functionSelector can be used to check that string. A mismatch can be rejected before the call, but a match does not guarantee that the target is trustworthy.

Why Use ERC7930 for the Target?

A self-describing call requires a chain as well as a contract address. ERC7930 stores both in one binary envelope, allowing the destination to be reconstructed without external chain configuration. Consult the CAIP350 profile for the serialization and canonicality rules of each chain type.

Why Include returnType?

An EVM call returns ABI-encoded bytes. Including returnType makes it possible to identify the expected type and decode the result accordingly without an external ABI. ERC8121 itself does not restrict the return value to a particular type.

Why Require ERC3668?

A target may request external data through OffchainLookup rather than returning a value directly. An ERC3668-compatible client passes the gateway response to the callback for verification. ERC8121 allows this feature to be enabled only when resolving a hook; it does not need to be enabled for every ordinary call.

Compatibility

Clients that do not support ERC8121 return hooks as raw bytes or string values. They do not automatically initiate a call to another chain simply by reading the value.

Values Returned by Unsupported Clients

Both bytes beginning with 0x6113bfa3... and strings such as hook(...) are returned as ordinary metadata values. Reading storage still works, but the value is not resolved to the expected credential.

Boundaries to Check Separately During Integration

Verify the known metadata keys, parsers for both forms, ERC7930 namespace, target-chain provider, ERC3668 support, trusted targets, and recursive hook limits independently. ERC8121 is a Draft, so track changes to selectors, argument ordering, and detection rules.

Security

Format validation, target trust evaluation, and recursion termination are separate defenses.

Resolving only trusted targets and stopping recursive hooks at a depth limit

Validate the Format Before Resolution

An attacker can store a hook whose selector and signature do not match, a call with an incorrect number of arguments, or a malformed ERC7930 payload. ABI encoding without validation can lead to unintended function selection, decoding errors, and unnecessary RPC calls.

Before calling, check the format selector, field count, string syntax, selector match, returnType, and ERC7930 lengths. ERC8121 does not specify a maximum total payload length, so implementations establish a size limit. Passing format validation does not establish that the target is safe.

Scope of Target Trust

Even a well-formed hook can point to a target returning false credentials. The client checks the chain and address pair against an allowlist or third-party registry and does not resolve unverified targets.

Even after registration, proxy implementation changes and compromised administrative keys remain risks. Monitor the code hash, upgrade authority, and registration expiration separately. Because reads and writes have different consequences, do not unconditionally share the same allowlist between them. For writes, also restrict the functions and amounts that can be submitted. If the target is unverified, fail resolution itself.

Limit Recursive Hooks

If a target returns another hook that eventually points back to the original hook, resolution becomes cyclic. An implementation counts resolution depth and stops at the 3–5 levels suggested by the official specification. Recording visited hook hashes can also detect cycles before reaching the limit. A depth limit alone, however, will still execute a short cycle repeatedly until the limit is reached. Instead, add an identifier derived from the destination and call contents to a visited set and stop as soon as it appears again. Because legitimate chains also fail beyond 3–5 levels, fix the limit for each use case and return an error when it is exceeded.

Even a legitimate long chain cannot be resolved if it exceeds the limit. When the limit is reached, return an error rather than treating a partial result as success.

Conclusion

ERC8121 stores a single function call on another chain as a hook containing types, values, return type, and destination. The client validates the format and selector, determines that the ERC7930 target is trusted, and then performs either an ERC3668-enabled read or a signed write. Implementations must avoid calling unverified targets and impose limits on payload size and recursion depth.

I also publish articles elsewhere. You can find them at the following links.