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.

ERC7811 proposes a mechanism through which a DApp passes an account to a wallet, and the wallet returns the assets it knows about, grouped by chain. JSON-RPC is a request-response protocol in which a DApp sends a method name and arguments and receives a result. ERC7811 introduces the JSON-RPC method wallet_getAssets, allowing native tokens, ERC20 tokens, and ERC721 NFTs to be discovered through the same response.

Overview of Wallet Asset Discovery

To read an ERC20 balance, a DApp typically calls balanceOf on a known token contract. This approach cannot discover token contracts the DApp does not already know. When multiple chains are involved, the DApp must also determine which contracts to query on which chains.

A wallet may already know the connected account and have collected information about its assets. A provider is the component that carries JSON-RPC requests from a browser-based DApp to a wallet. With ERC7811, a DApp sends wallet_getAssets to an EIP1193-compatible provider, and the wallet returns potential assets associated with the account.

A provider forwards a DApp request to a wallet, which returns a list of assets across multiple chains

An indexer collects on-chain history and builds a searchable set of potential assets. Wallets may use different data sources depending on their implementation, such as on-chain RPC endpoints, indexers, and internal caches. ERC7811 standardizes the format of the request from the DApp and the response from the wallet. It does not prove how assets were discovered or whether the returned balances reflect the latest on-chain values.

Scope of Assets Returned by the Wallet

The request specifies one target account. The wallet returns the assets it can provide for that account, grouped by EIP155 chain ID.

When filters are omitted, the proposal recommends returning all assets available to the wallet. However, it does not define the full scope of assets considered available. Assets that have not yet been discovered, assets excluded as spam, and recent transfers not yet reflected by an indexer may be missing.

An empty array therefore means the wallet currently has no candidates to return. It is not on-chain proof that the account holds no assets.

Querying Known Contracts

The ERC20 balanceOf function accepts an account on a known token contract and returns the balance maintained by that contract. The ERC721 balanceOf function similarly returns the number of NFTs an account holds within a known NFT contract. To check an individual NFT, the DApp also needs its tokenId and the ownerOf function.

By contrast, wallet_getAssets first obtains candidate contract addresses and tokenId values from the wallet. ERC7811 can therefore be used to discover unknown assets, while the relevant contract can be queried to verify balances immediately before a transfer.

Requests and Responses

A wallet_getAssets request consists of the target account and optional filters. The wallet evaluates the filters and returns arrays of assets keyed by chain ID. The request-response boundary also includes details that the DApp and wallet must align on, such as the JSON-RPC argument format, filter precedence, and the meaning of empty results.

The flow from params normalization through filtering to asset responses grouped by chain

Wrapping params

ERC7811 defines a request object called WalletGetAssetsRequest. JSON-RPC 2.0 and EIP1193 allow both positional arrays and named objects in params. ERC7811 does not prescribe which form must be used in the complete JSON-RPC request.

The sample uses a single-element array containing the request object, a convention also used in Reown's public implementation.

ts
const response = await provider.request({
  method: "wallet_getAssets",
  params: [{
    account: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
    assetTypeFilter: ["native", "erc20"],
    chainFilter: ["0x1", "0xa"],
  }],
});

Reading params[0] as the request object is a convention specific to the sample. If the connected implementation expects a named object, it is incompatible with this code. The wallet selects one accepted wrapping convention during initial validation and returns JSON-RPC -32602 Invalid params for other forms.

The convention used by a public implementation is not itself an ERC7811 requirement. Other publicly available type definitions may use assetFilter structures or asset type representations that differ from the draft. Adoption of a convention and compliance with the specification must be assessed separately.

Filter Precedence

The request supports the following filters.

Filter Values When applied
assetFilter address and type grouped by chain When present, only this filter is used
assetTypeFilter native, erc20, erc721 Used when assetFilter is absent
chainFilter Chain IDs such as 0x1 and 0xa Used when assetFilter is absent

When assetFilter is present, the wallet ignores assetTypeFilter and chainFilter. This is because assetFilter already specifies the chains, addresses, and asset types.

For example, the following request targets only the native token on Ethereum mainnet. Neither erc20 in assetTypeFilter nor Optimism's 0xa in chainFilter affects the result.

json
{
  "account": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
  "assetFilter": {
    "0x1": [{ "address": "native", "type": "native" }]
  },
  "assetTypeFilter": ["erc20"],
  "chainFilter": ["0xa"]
}

If a DApp screen displays only ERC20 tokens, specify assetTypeFilter. On screens that use only one chain, adding chainFilter reduces the number of assets processed by the wallet and its data sources.

Asset Data Grouped by Chain

The response uses hexadecimal EIP155 chain IDs such as 0x1 as keys. Each value is an array of Asset objects discovered on that chain.

json
{
  "0x1": [
    { "address": "native", "balance": "0xde0b6b3a7640000", "type": "native" },
    {
      "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
      "balance": "0xf4240",
      "type": "erc20",
      "metadata": { "name": "USD Coin", "symbol": "USDC", "decimals": 6 }
    },
    {
      "address": "0x1111111111111111111111111111111111111111",
      "balance": "0x1",
      "type": "erc721",
      "metadata": {
        "name": "Example NFT",
        "symbol": "ENFT",
        "tokenId": "0x2a",
        "tokenURI": "ipfs://example"
      }
    }
  ]
}

balance is a hexadecimal string beginning with 0x, not a decimal string. To avoid losing precision, the DApp converts it to BigInt and uses metadata.decimals to determine the display precision for ERC20 tokens.

Following the proposal's type definitions, type uses the lowercase values native, erc20, and erc721. Some JSON examples in the proposal use uppercase ERC20 and ERC721, which do not match the type definitions. For interoperability, the wallet and DApp should agree on the representation rather than silently guessing how to normalize case.

The proposal is a draft, and its treatment of metadata is also inconsistent. The shared Asset type appears to require it, while the prose describes it as optional. When returning erc20 or erc721 assets, the proposal also specifies minimum metadata fields for each asset type. Although name, symbol, and decimals are optional in ERC20 itself, an ERC7811 wallet returning erc20 assets is responsible for including all three fields.

type Minimum metadata fields
native None
erc20 name、 symbol、 decimals
erc721 name, symbol, tokenId; tokenURI is optional

ERC7811's AssetType is designed to allow future ERCs to introduce strings beyond these three types. The sample below is a product-specific implementation supporting only the three known types. It rejects unknown asset types with -32602 instead of guessing how to display them. An implementation supporting extension types should accept them after adding validation for the metadata defined by the corresponding ERC.

Empty Results and NFT Representation

ERC7811 does not specify whether to omit a chain, return an empty array, or return a zero-balance Asset when the requested asset is not held. Deduplicating repeated Asset objects is also left to the implementation.

For ERC721, metadata contains one tokenId. However, it is not specified whether NFTs in the same collection should be returned individually or grouped by collection. The sample deduplicates NFTs using the combination of chain ID, contract address, and tokenId as their identity.

Under this convention, an empty array indicates that the response contains no asset candidates, while a zero balance indicates a zero explicitly returned by the wallet. Neither is used as proof of non-ownership. The relevant contract is queried again before a transfer or collateral valuation.

Capability Support and Authorization

Even if a wallet implements wallet_getAssets, the method may not be callable for the current chain or account. The DApp checks EIP5792 capability support and CAIP25 authorization separately. CAIP25 also uses different identifiers across revisions, and directly comparing strings can incorrectly reject an authorized request.

Decision order for capability checks, CAIP25 authorization, request routing, and error recovery

Capability Support by Chain

The DApp calls wallet_getCapabilities and checks assetDiscovery.supported for the target chain.

json
{
  "0x1": { "assetDiscovery": { "supported": true } },
  "0x0": { "assetDiscovery": { "supported": true } }
}

If the target chain has an entry, use that value. If the target chain has no entry, check 0x0, which represents support across all chains. If cached information differs from the current wallet_getCapabilities response, the DApp prioritizes the current response.

Even when capability support is true, the caller may not be authorized. assetDiscovery indicates whether the feature is available, while CAIP25 scopes represent the methods, chains, and accounts authorized within the current session.

Authorized Accounts and Chains

The pinned CAIP25 revision referenced by ERC7811 differs in data structure from the current CAIP25 revision described in this article.

Item Pinned revision referenced by ERC7811 Current CAIP25
Scopes sessionScopes scopes
Chains Scopes such as eip155:1 chains: ["1"] or chain-specific scopes
Accounts eip155:1:0x... accounts: ["0x..."]
Scope-specific additional information scopedProperties capabilities
Session-wide additional information sessionProperties properties

ERC7811 uses hexadecimal chain ID strings such as 0x1, whereas CAIP25 uses decimal strings such as 1. Both are therefore converted to integers before checking whether they represent the same chain.

CAIP10 account identifiers from the pinned revision, such as eip155:1:0x..., are split into the namespace, chain, and address. For accounts in the current CAIP25 revision, the chain represented by the scope is combined with the raw address. EVM addresses are accepted in a form that permits EIP55 checksum validation and normalized to consistent case for comparisons.

The current CAIP25 revision describes eip155:0 as a null reference applying to any EIP155 chain. However, the same revision includes examples using bare eip155 and a changelog entry removing namespace scopes. ERC7811 does not prescribe an error code for situations in which authorization cannot be established across this version boundary. The sample does not guess how to expand namespace-wide authorizations whose agreed revision and representation cannot be established. Instead, it stops with EIP1193's 4100 Unauthorized because authorization cannot be demonstrated. Only explicit chains or chain-specific scopes with nonzero chain IDs are used for authorization decisions.

The general CAIP10 specification does not define a normalization method shared by all namespaces. Lowercasing addresses for comparison is a sample-specific policy limited to EVM addresses in the EIP155 namespace.

When the account, chain, or session changes, the DApp discards previous capability and asset responses. The same applies when receiving a CAIP311 wallet_sessionChanged notification or retrieving permissions again with CAIP312 wallet_getSession after a disconnection. CAIP311 and CAIP312 are also drafts, however, and should be checked against the CAIP25 revision adopted by the connected implementation.

Wallet Service Routing

CAIP345 defines a route for sending wallet_getAssets to an HTTP JSON-RPC endpoint specified by the wallet. The DApp sends a complete JSON-RPC request via POST, and the service can use CORS and Cache-Control to control browser requests and caching. The service may be operated by a third party rather than the wallet operator. An id of 0, used only to associate the response with the request, is recommended. Query parameters in the wallet-provided URL are transmitted unchanged. If no wallet service is designated for the method, send the request directly to the wallet through the EIP1193 provider. CAIP345 does not specify automatic retries after HTTP request failures, so the DApp determines how to recover from service failures. The wallet should retain a route for handling direct method requests from DApps that do not support CAIP345.

However, CAIP345 uses sessionProperties and scopedProperties from an older CAIP25 revision. CAIP345 has not been normatively updated to specify how these map to properties and capabilities in the current CAIP25 revision. The DApp should not guess equivalent property names and should read only the revision agreed with the wallet.

CAIP345 also lacks a mechanism for assigning a method to a particular account. Even after selecting a wallet service URL, the DApp separately verifies whether the target account falls within the CAIP25 scope. To avoid introducing this unresolved version boundary into the code, the TypeScript sample implements only direct requests through an EIP1193 provider.

Error-Specific Recovery

The DApp handles EIP1193 and JSON-RPC errors differently depending on their causes.

Code Meaning DApp behavior
4100 Account or method not authorized Prompt the user to authorize it again
4200 Unsupported method Do not retry; switch to querying known contracts
4900 Provider disconnected from all chains Restore the connection and retry once
4901 Disconnected from the target chain Connect to the target chain and retry once
-32602 Invalid arguments Do not retry until the code or input has been corrected

For timeouts and unknown errors, do not repeatedly retry automatically. A delayed response from an old request could conflict with a new request, so return control to the user through a retry action in the interface. This recovery policy is a sample-specific decision based on EIP1193 and JSON-RPC rather than an ERC7811 rule.

TypeScript Sample Implementation

ERC7811 does not provide an official reference implementation or conformance tests. The following small implementation illustrates the proposal's types and filter precedence. The code uses lowercase asset types, hexadecimal balance strings, and chain-specific arrays as shared types.

Implementation architecture connecting shared types to wallet filtering, the provider, DApp, and tests

First, define the request and asset types.

ts
export type Hex = `0x${string}`;
export type Address = Hex;
export type ChainId = Hex;
export type AssetType = "native" | "erc20" | "erc721";

export type AssetIdentifier = {
  address: Address | "native";
  type: AssetType;
};

export type WalletGetAssetsRequest = {
  account: Address;
  assetFilter?: Record<ChainId, AssetIdentifier[]>;
  assetTypeFilter?: AssetType[];
  chainFilter?: ChainId[];
};

export type NativeAsset = {
  address: "native";
  balance: Hex;
  type: "native";
};

export type Erc20Asset = {
  address: Address;
  balance: Hex;
  type: "erc20";
  metadata: { name: string; symbol: string; decimals: number };
};

export type Erc721Asset = {
  address: Address;
  balance: Hex;
  type: "erc721";
  metadata: {
    name: string;
    symbol: string;
    tokenId: Hex;
    tokenURI?: string;
  };
};

export type Asset = NativeAsset | Erc20Asset | Erc721Asset;
export type WalletGetAssetsResponse = Record<ChainId, Asset[]>;

Representing Asset as a discriminated union determines which metadata is available after checking type. For example, decimals can be accessed safely within a branch where asset.type === "erc20". balance is also passed around as a hexadecimal string rather than converted into a JavaScript number.

Wallet-Side Filtering

Immediately after receiving a JSON-RPC request, the wallet validates params and the request object. The following code accepts only a single-element array and rejects invalid input with -32602.

ts
export class RpcError extends Error {
  constructor(public readonly code: number, message: string) {
    super(message);
  }
}

const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
const HEX_QUANTITY = /^0x(?:0|[1-9a-fA-F][0-9a-fA-F]*)$/;
const ASSET_TYPES = new Set<AssetType>(["native", "erc20", "erc721"]);

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function isAddress(value: unknown): value is Address {
  return typeof value === "string" && ADDRESS.test(value);
}

function isChainId(value: unknown): value is ChainId {
  return typeof value === "string" && HEX_QUANTITY.test(value);
}

function isAssetType(value: unknown): value is AssetType {
  return typeof value === "string" && ASSET_TYPES.has(value as AssetType);
}

export function parseWalletGetAssetsParams(
  params: unknown,
): WalletGetAssetsRequest {
  if (!Array.isArray(params) || params.length !== 1 || !isRecord(params[0])) {
    throw new RpcError(-32602, "params must be [WalletGetAssetsRequest]");
  }

  const request = params[0];
  if (!isAddress(request.account)) {
    throw new RpcError(-32602, "account must be a 20-byte address");
  }

  if (
    request.chainFilter !== undefined &&
    (!Array.isArray(request.chainFilter) || !request.chainFilter.every(isChainId))
  ) {
    throw new RpcError(-32602, "chainFilter contains an invalid chain ID");
  }

  if (
    request.assetTypeFilter !== undefined &&
    (!Array.isArray(request.assetTypeFilter) ||
      !request.assetTypeFilter.every(isAssetType))
  ) {
    throw new RpcError(-32602, "assetTypeFilter contains an unknown type");
  }

  if (request.assetFilter !== undefined) {
    if (!isRecord(request.assetFilter)) {
      throw new RpcError(-32602, "assetFilter must be a record");
    }

    for (const [chainId, identifiers] of Object.entries(request.assetFilter)) {
      if (!isChainId(chainId) || !Array.isArray(identifiers)) {
        throw new RpcError(-32602, "assetFilter contains an invalid chain");
      }

      for (const identifier of identifiers) {
        if (
          !isRecord(identifier) ||
          !(identifier.address === "native" || isAddress(identifier.address)) ||
          !isAssetType(identifier.type)
        ) {
          throw new RpcError(-32602, "assetFilter contains an invalid asset");
        }
      }
    }
  }

  return request as WalletGetAssetsRequest;
}

HEX_QUANTITY accepts only 0x0 or hexadecimal numbers without unnecessary leading zeros. ERC7811's Hex type does not specify address lengths or leading-zero requirements, so this validation is an input contract specific to the sample.

Within assetFilter, validate address and type for each chain ID. Once the input has been validated, subsequent processing can focus on filter precedence rather than repeatedly checking whether values exist.

Next, prepare authorization information that normalizes the differences between CAIP25 revisions.

ts
import { getAddress } from "viem";

type AuthorizedScope = {
  methods: Set<string>;
  accountChains: Set<string>;
};

export type Authorization = {
  scopes: AuthorizedScope[];
};

export function normalizeChainId(chainId: ChainId | string): bigint {
  if (chainId.startsWith("0x")) {
    if (!isChainId(chainId)) {
      throw new RpcError(-32602, "invalid hex chain ID");
    }
    return BigInt(chainId);
  }

  if (!/^(?:0|[1-9][0-9]*)$/.test(chainId)) {
    throw new RpcError(-32602, "invalid decimal chain ID");
  }
  return BigInt(chainId);
}

function normalizeEvmAddress(address: string): string {
  if (!ADDRESS.test(address)) {
    throw new RpcError(-32602, "invalid EVM address");
  }
  return getAddress(address).toLowerCase();
}

function accountChainKey(chainId: bigint, account: string): string {
  return `${chainId}:${normalizeEvmAddress(account)}`;
}

export function addLegacyScope(
  authorization: Authorization,
  input: { methods: string[]; accounts: string[] },
): void {
  const scope: AuthorizedScope = {
    methods: new Set(input.methods),
    accountChains: new Set(),
  };

  for (const accountId of input.accounts) {
    const match = /^eip155:([0-9]+):(0x[0-9a-fA-F]{40})$/.exec(accountId);
    if (!match) {
      throw new RpcError(-32602, "invalid EIP155 CAIP-10 account");
    }
    scope.accountChains.add(
      accountChainKey(normalizeChainId(match[1]), match[2]),
    );
  }
  authorization.scopes.push(scope);
}

export function addCurrentScope(
  authorization: Authorization,
  scopeKey: string,
  input: { chains?: string[]; accounts: string[]; methods: string[] },
): void {
  if (scopeKey === "eip155:0") {
    throw new RpcError(4100, "ambiguous namespace-wide CAIP-25 authorization");
  }

  const chainIds = new Set((input.chains ?? []).map(normalizeChainId));
  const chainScope = /^eip155:([0-9]+)$/.exec(scopeKey);
  if (chainScope) {
    chainIds.add(normalizeChainId(chainScope[1]));
  } else if (scopeKey !== "eip155") {
    throw new RpcError(-32602, "unsupported CAIP-25 scope");
  }
  if (chainIds.size === 0) {
    throw new RpcError(-32602, "CAIP-25 scope has no explicit chain");
  }

  authorization.scopes.push({
    methods: new Set(input.methods),
    accountChains: new Set(
      [...chainIds].flatMap((chainId) =>
        input.accounts.map((account) => accountChainKey(chainId, account)),
      ),
    ),
  });
}

export function isAuthorized(
  authorization: Authorization,
  account: Address,
  chainIds: ChainId[],
): boolean {
  if (chainIds.length === 0) {
    const accountSuffix = `:${normalizeEvmAddress(account)}`;
    return authorization.scopes.some(
      (scope) =>
        scope.methods.has("wallet_getAssets") &&
        [...scope.accountChains].some((entry) => entry.endsWith(accountSuffix)),
    );
  }

  return chainIds.every((chainId) =>
    authorization.scopes.some(
      (scope) =>
        scope.methods.has("wallet_getAssets") &&
        scope.accountChains.has(
          accountChainKey(normalizeChainId(chainId), account),
        ),
    ),
  );
}

normalizeChainId converts both ERC7811's 0x1 and CAIP25's 1 to 1n. A regular expression splits CAIP10 account identifiers in the pinned CAIP25 revision into eip155, a decimal chain ID, and an EVM address. In the current CAIP25 revision, chains and accounts are separate, but in a chain-specific scope such as eip155:8453, the scope key itself also identifies the chain. The addCurrentScope function therefore accepts both the scope key and value. The current CAIP25 revision describes eip155:0 as a null reference applying to any chain in the namespace. However, the same revision includes bare eip155 examples and a changelog entry removing namespace scopes, making the accepted namespace-wide representation ambiguous. ERC7811 does not define a specific error code for this ambiguity. The sample does not convert eip155:0 to numeric zero or a wildcard chain. Instead, it stops with EIP1193's 4100 Unauthorized because authorization cannot be demonstrated. It accepts only explicit chains or nonzero chain-specific scopes according to the revision agreed with the wallet.

Methods and chain-account pairs are stored separately for each scope. Each requested chain is authorized only when wallet_getAssets, the target account, and the target chain appear together in the same scope. Permissions from different scopes are not combined. Even if both filters and candidate holdings are empty, leaving no chains to check, the implementation verifies that the method and account belong to the same scope.

The normalizeEvmAddress function uses viem's getAddress to validate mixed-case checksums and lowercases addresses for comparison. This processing applies only to comparisons between EVM addresses. It does not apply to addresses displayed in the interface or account identifiers from other namespaces.

Asset filtering begins by checking whether assetFilter is present.

ts
function assetKey(chainId: ChainId, asset: Asset): string {
  const address = asset.address.toLowerCase();
  if (asset.type === "erc721") {
    return `${chainId}:${address}:erc721:${asset.metadata.tokenId}`;
  }
  return `${chainId}:${address}:${asset.type}`;
}

function deduplicate(
  assetsByChain: WalletGetAssetsResponse,
): WalletGetAssetsResponse {
  const result: WalletGetAssetsResponse = {};

  for (const [chainId, assets] of Object.entries(assetsByChain) as [
    ChainId,
    Asset[],
  ][]) {
    const seen = new Set<string>();
    result[chainId] = assets.filter((asset) => {
      const key = assetKey(chainId, asset);
      if (seen.has(key)) return false;
      seen.add(key);
      return true;
    });
  }

  return result;
}

export function filterAssets(
  allAssets: WalletGetAssetsResponse,
  request: WalletGetAssetsRequest,
): WalletGetAssetsResponse {
  const assets = deduplicate(allAssets);

  if (request.assetFilter !== undefined) {
    const result: WalletGetAssetsResponse = {};
    for (const [chainId, identifiers] of Object.entries(
      request.assetFilter,
    ) as [ChainId, AssetIdentifier[]][]) {
      const candidates = assets[chainId] ?? [];
      result[chainId] = candidates.filter((asset) =>
        identifiers.some(
          (identifier) =>
            identifier.type === asset.type &&
            identifier.address.toLowerCase() === asset.address.toLowerCase(),
        ),
      );
    }
    return result;
  }

  const allowedChains = request.chainFilter
    ? new Set(request.chainFilter.map(normalizeChainId))
    : undefined;
  const allowedTypes = request.assetTypeFilter
    ? new Set(request.assetTypeFilter)
    : undefined;
  const result: WalletGetAssetsResponse = {};

  for (const [chainId, chainAssets] of Object.entries(assets) as [
    ChainId,
    Asset[],
  ][]) {
    if (allowedChains && !allowedChains.has(normalizeChainId(chainId))) {
      continue;
    }
    result[chainId] = chainAssets.filter(
      (asset) => !allowedTypes || allowedTypes.has(asset.type),
    );
  }
  return result;
}

export function handleWalletGetAssets(
  params: unknown,
  allAssets: WalletGetAssetsResponse,
  authorization: Authorization,
): WalletGetAssetsResponse {
  const request = parseWalletGetAssetsParams(params);
  const requestedChains = request.assetFilter
    ? (Object.keys(request.assetFilter) as ChainId[])
    : request.chainFilter ?? (Object.keys(allAssets) as ChainId[]);

  if (!isAuthorized(authorization, request.account, requestedChains)) {
    throw new RpcError(4100, "wallet_getAssets is not authorized");
  }
  return filterAssets(allAssets, request);
}

The assetFilter branch returns immediately after constructing its result. The subsequent chainFilter and assetTypeFilter logic is therefore skipped, faithfully implementing the proposal's precedence.

The deduplicate function distinguishes ERC20 and native tokens by chain, address, and type. For ERC721, it also includes tokenId, so distinct NFTs in the same collection are not removed. This behavior is not mandated by ERC7811. It is a sample-specific policy intended to make the meaning of empty results and duplicates consistent.

DApp-Side Requests

The DApp checks capability support for the target chain or 0x0 before calling wallet_getAssets. The following code falls back to known-contract queries only when the method is unsupported and returns authorization and connection errors as separate outcomes.

ts
type Provider = {
  request(args: { method: string; params?: unknown }): Promise<unknown>;
};

type CapabilityMap = Record<
  ChainId,
  { assetDiscovery?: { supported?: boolean } }
>;

type DiscoveryResult =
  | { status: "ok"; assets: WalletGetAssetsResponse }
  | { status: "reauthorize" }
  | { status: "fallback" }
  | { status: "reconnect"; chainOnly: boolean }
  | { status: "invalid-request" };

function supportsAssetDiscovery(
  capabilities: CapabilityMap,
  chainId: ChainId,
): boolean {
  if (Object.hasOwn(capabilities, chainId)) {
    return capabilities[chainId]?.assetDiscovery?.supported === true;
  }
  return capabilities["0x0"]?.assetDiscovery?.supported === true;
}

function rpcCode(error: unknown): number | undefined {
  if (typeof error !== "object" || error === null || !("code" in error)) {
    return undefined;
  }
  return typeof error.code === "number" ? error.code : undefined;
}

function validateAsset(value: unknown): Asset {
  if (!isRecord(value) || !isChainId(value.balance) || !isAssetType(value.type)) {
    throw new RpcError(-32602, "wallet returned an invalid asset");
  }

  if (value.type === "native") {
    if (value.address !== "native") {
      throw new RpcError(-32602, "native asset must use the native address");
    }
    return value as NativeAsset;
  }

  if (!isAddress(value.address) || !isRecord(value.metadata)) {
    throw new RpcError(-32602, "token metadata is missing");
  }
  normalizeEvmAddress(value.address);

  const { name, symbol } = value.metadata;
  if (typeof name !== "string" || typeof symbol !== "string") {
    throw new RpcError(-32602, "token name or symbol is invalid");
  }

  if (value.type === "erc20") {
    const decimals = value.metadata.decimals;
    if (typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0) {
      throw new RpcError(-32602, "ERC20 decimals is invalid");
    }
    return value as Erc20Asset;
  }

  const { tokenId, tokenURI } = value.metadata;
  if (
    !isChainId(tokenId) ||
    (tokenURI !== undefined && typeof tokenURI !== "string")
  ) {
    throw new RpcError(-32602, "ERC721 metadata is invalid");
  }
  return value as Erc721Asset;
}

export function validateWalletGetAssetsResponse(
  value: unknown,
): WalletGetAssetsResponse {
  if (!isRecord(value)) {
    throw new RpcError(-32602, "wallet returned an invalid response");
  }

  const result: WalletGetAssetsResponse = {};
  for (const [chainId, assets] of Object.entries(value)) {
    if (!isChainId(chainId) || !Array.isArray(assets)) {
      throw new RpcError(-32602, "wallet returned an invalid chain entry");
    }
    result[chainId] = assets.map(validateAsset);
  }
  return result;
}

export async function discoverAssets(
  provider: Provider,
  account: Address,
  chainId: ChainId,
): Promise<DiscoveryResult> {
  const capabilities = (await provider.request({
    method: "wallet_getCapabilities",
    params: [account],
  })) as CapabilityMap;

  if (!supportsAssetDiscovery(capabilities, chainId)) {
    return { status: "fallback" };
  }

  try {
    const assets = await provider.request({
      method: "wallet_getAssets",
      params: [{
        account,
        assetTypeFilter: ["native", "erc20", "erc721"],
        chainFilter: [chainId],
      } satisfies WalletGetAssetsRequest],
    });

    return {
      status: "ok",
      assets: validateWalletGetAssetsResponse(assets),
    };
  } catch (error) {
    switch (rpcCode(error)) {
      case 4100:
        return { status: "reauthorize" };
      case 4200:
        return { status: "fallback" };
      case 4900:
        return { status: "reconnect", chainOnly: false };
      case 4901:
        return { status: "reconnect", chainOnly: true };
      case -32602:
        return { status: "invalid-request" };
      default:
        throw error;
    }
  }
}

supportsAssetDiscovery checks whether the target chain key exists first, reading 0x0 only if that key is absent. If support is explicitly false for the target chain, it is not overridden by a global true. When support is false, the DApp does not send wallet_getAssets and can fall back to querying known contracts without waiting for an unsupported-method error.

On a 4100 result, the DApp asks the user to authorize the account or method again. For 4900 and 4901, the caller retries once after restoring the connection. Resending the same input after -32602 will not succeed, so processing stops until the code or input is corrected.

validateWalletGetAssetsResponse validates at runtime that the response contains chain-specific arrays and that each asset's type, balance, and metadata have the expected structure. A type assertion alone cannot validate values received from a wallet. Production implementations can enforce the same boundary using a schema library such as Zod.

Even after validation, name, symbol, and tokenURI remain untrusted strings. Display them as text rather than inserting them as HTML, and impose length limits. Do not retrieve tokenURI automatically. Validate permitted URI schemes, response sizes, Content-Type, and timeouts separately.

Testing Specification Requirements

Vitest tests verify not only that functions succeed but also that the proposal's precedence and article-specific implementation boundaries are independently enforced. Representative tests are shown below.

ts
import { describe, expect, it, vi } from "vitest";
import {
  addCurrentScope,
  addLegacyScope,
  discoverAssets,
  filterAssets,
  isAuthorized,
  normalizeChainId,
  parseWalletGetAssetsParams,
  validateWalletGetAssetsResponse,
  type WalletGetAssetsResponse,
  type Authorization,
} from "./erc7811";

const ACCOUNT = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";
const OTHER = "0x1111111111111111111111111111111111111111";
const assets: WalletGetAssetsResponse = {
  "0x1": [
    { address: "native", balance: "0x10", type: "native" },
    {
      address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
      balance: "0xf4240",
      type: "erc20",
      metadata: { name: "USD Coin", symbol: "USDC", decimals: 6 },
    },
  ],
  "0xa": [{ address: "native", balance: "0x20", type: "native" }],
};

describe("wallet_getAssets", () => {
  it("1要素のparamsだけを受理する", () => {
    expect(
      parseWalletGetAssetsParams([{ account: ACCOUNT, chainFilter: ["0x1"] }]),
    ).toEqual({ account: ACCOUNT, chainFilter: ["0x1"] });

    expect(() => parseWalletGetAssetsParams({ account: ACCOUNT })).toThrowError(
      expect.objectContaining({ code: -32602 }),
    );
    expect(() => parseWalletGetAssetsParams([{
      account: ACCOUNT,
      assetTypeFilter: ["erc1155"],
    }])).toThrowError(expect.objectContaining({ code: -32602 }));
  });

  it("assetFilterが他の2つのfilterより優先される", () => {
    const result = filterAssets(assets, {
      account: ACCOUNT,
      assetFilter: { "0x1": [{ address: "native", type: "native" }] },
      assetTypeFilter: ["erc20"],
      chainFilter: ["0xa"],
    });

    expect(result).toEqual({
      "0x1": [{ address: "native", balance: "0x10", type: "native" }],
    });
  });

  it("未対応の資産typeを応答として受理しない", () => {
    expect(() => validateWalletGetAssetsResponse({
      "0x1": [{ address: "native", balance: "0x1", type: "erc1155" }],
    })).toThrowError(expect.objectContaining({ code: -32602 }));
  });

  it("hexとdecimalのchain IDを同じ値として比較できる", () => {
    expect(normalizeChainId("0x1")).toBe(1n);
    expect(normalizeChainId("1")).toBe(1n);
    expect(normalizeChainId("0xa")).toBe(10n);
  });

  it("固定版と現行版のaccount表現を同じ認可へ変換する", () => {
    const legacy: Authorization = { scopes: [] };
    addLegacyScope(legacy, {
      methods: ["wallet_getAssets"],
      accounts: [`eip155:1:${ACCOUNT}`, `eip155:10:${OTHER}`],
    });

    const current: Authorization = { scopes: [] };
    addCurrentScope(current, "eip155:1", {
      accounts: [ACCOUNT.toLowerCase()],
      methods: ["wallet_getAssets"],
    });

    expect(isAuthorized(legacy, ACCOUNT, ["0x1"])).toBe(true);
    expect(isAuthorized(legacy, ACCOUNT, ["0xa"])).toBe(false);
    expect(isAuthorized(current, ACCOUNT, ["0x1"])).toBe(true);
    expect(isAuthorized(current, ACCOUNT, ["0xa"])).toBe(false);
    expect(isAuthorized(current, ACCOUNT, [])).toBe(true);

    expect(() => addCurrentScope({ scopes: [] }, "eip155:0", {
      accounts: [ACCOUNT],
      methods: ["wallet_getAssets"],
    })).toThrowError(expect.objectContaining({ code: 4100 }));
  });

  it("別々のscopeにあるmethodとaccountを組み合わせない", () => {
    const authorization: Authorization = { scopes: [] };
    addCurrentScope(authorization, "eip155:1", {
      accounts: [ACCOUNT],
      methods: [],
    });
    addCurrentScope(authorization, "eip155:1", {
      accounts: [OTHER],
      methods: ["wallet_getAssets"],
    });

    expect(isAuthorized(authorization, ACCOUNT, ["0x1"])).toBe(false);
  });

  it("対象chainと0x0のcapabilityを順に確認する", async () => {
    const provider = {
      request: vi.fn()
        .mockResolvedValueOnce({ "0x0": { assetDiscovery: { supported: true } } })
        .mockResolvedValueOnce({ "0x1": [] }),
    };

    await expect(discoverAssets(provider, ACCOUNT, "0x1")).resolves.toEqual({
      status: "ok",
      assets: { "0x1": [] },
    });
  });

  it("対象chainのfalseを0x0のtrueで上書きしない", async () => {
    const provider = {
      request: vi.fn().mockResolvedValueOnce({
        "0x1": { assetDiscovery: { supported: false } },
        "0x0": { assetDiscovery: { supported: true } },
      }),
    };

    await expect(discoverAssets(provider, ACCOUNT, "0x1")).resolves.toEqual({
      status: "fallback",
    });
    expect(provider.request).toHaveBeenCalledTimes(1);
  });

  it.each([
    [4100, { status: "reauthorize" }],
    [4200, { status: "fallback" }],
    [4900, { status: "reconnect", chainOnly: false }],
    [4901, { status: "reconnect", chainOnly: true }],
    [-32602, { status: "invalid-request" }],
  ])("error code %sを別の結果へ変換する", async (code, expected) => {
    const provider = {
      request: vi.fn()
        .mockResolvedValueOnce({ "0x1": { assetDiscovery: { supported: true } } })
        .mockRejectedValueOnce({ code }),
    };

    await expect(discoverAssets(provider, ACCOUNT, "0x1")).resolves.toEqual(expected);
  });
});

In the second test, assetTypeFilter and chainFilter contradict assetFilter. Nevertheless, only Ethereum mainnet's native token is returned, confirming the early return in the assetFilter branch.

The chain ID test ensures that ERC7811 hexadecimal representations and CAIP25 decimal representations can be converted into the same integer. The authorization tests normalize the pinned revision's eip155:1:0x... and the current revision's chain-specific scopes into the same authorization decision, rejecting mismatched chains. They also verify that the ambiguous namespace-wide eip155:0 representation is not accepted as chain ID zero or as a wildcard, but instead results in EIP1193's 4100 Unauthorized. A further test rejects cases in which the method and account are in separate scopes, preventing permission aggregation.

Tests for requests and responses containing unknown asset types enforce the sample's boundary of supporting only the three known types. When supporting extensions such as ERC1155, replace these failure cases with validation of the new type and its metadata.

The table-driven error tests distinguish the states returned by the DApp for different failures of wallet_getAssets. In particular, only 4200 proceeds to known-contract queries, while 4100 waits for the user to authorize the request again.

These are not official ERC7811 conformance tests. They distinguish the filter precedence specified by the proposal from the input validation, deduplication, and recovery policies added by the sample.

Security and Trust Boundaries

The Security Considerations section of ERC7811 is empty. Receiving an asset list does not establish the authenticity, freshness, valuation, or transferability of the reported balances. The DApp and wallet must address the boundaries that the proposal does not yet define in their implementations.

Request and response formats defined by ERC7811 and trust boundaries left to implementers

Response Authenticity and Freshness

wallet_getAssets returns the asset candidates known to the wallet. Indexer lag, caches, chain reorganizations, and update delays immediately after transfers may cause differences from current on-chain values.

A DApp can use ERC7811 responses to populate asset selection screens. Immediately before proceeding with consequential operations such as transfers, collateral valuation, or payments, however, query the relevant contract or a trusted RPC endpoint again for balances and ownership. When the account or chain changes, discard previous responses rather than reusing them for another user or chain.

Privacy of Asset Lists

An aggregated list of balances and NFTs across chains could be used to identify users or infer their behavior. The wallet returns assets only for accounts, methods, and chains authorized within the connected session. The DApp should also specify the chainFilter or assetTypeFilter needed by the screen, avoiding unconditional retrieval of all assets.

When a CAIP345 wallet service is used, the HTTP service operator can also read the account and filters. Because this exposes information to third parties differently from a route handled entirely by an in-app provider, the DApp should inform users of the destination. If a proxy is involved, both the wallet service and the proxy operator can read the same request.

Displaying Metadata

name and symbol are received from the wallet or a data source used by the wallet. The DApp displays them as text rather than inserting them as HTML and limits their length to prevent layout disruption.

tokenURI references external data. Automatically fetching it upon receipt may disclose the DApp user's IP address to the referenced server and produce large responses or unexpected Content-Type values. If fetching it, validate permitted URI schemes, response sizes, Content-Type, and timeouts, separately from asset discovery.

Response Size and Unresolved Draft Questions

The ERC7811 draft described here does not define the following.

  • Pagination and item limits

    There is no specification for the number of assets returned per page or a cursor for retrieving subsequent results.

  • Timeouts and retries

    Implementations determine how long to wait and how many times to retry when a wallet or indexer cannot respond.

  • Spam asset exclusion

    There is no definition of which assets are considered spam or how to indicate exclusions in the response.

  • Prices and sorting

    Sorting by descending estimated value is recommended, but price sources, valuation currency, update timestamps, and tie-breaking order are undefined.

  • Multiple accounts

    A single request can specify only one account.

  • Change notifications and incremental updates

    ERC7811 defines an individual request and response. It does not specify subscriptions to changes in asset holdings, change notifications, incremental retrieval, or cache duration.

Requests without filters may produce large responses. DApps should limit requests to required chains and asset types, and wallets should document their own limits, cache durations, and failure behavior. Do not present these implementation policies as ERC7811 guarantees. Check the differences whenever the draft is updated. At the time of the original article, the proposal history showed no substantive text updates after a typographical correction on June 10, 2025. Check the draft again before publishing or updating an implementation.

Conclusion

ERC7811 provides a starting point for DApps to receive wallet-known asset candidates by chain rather than exhaustively querying unknown asset contracts. The main implementation concerns are assetFilter precedence, metadata for each asset type, separate capability and authorization checks, CAIP25 identifier normalization, and revalidation of received values. Pagination, response authenticity and freshness, and compatibility between CAIP345 and current CAIP25 remain unresolved. Implement wallet-specific behavior separately from the proposal's requirements.

The primary sources for ERC7811 and related specifications are listed below.

I also publish articles elsewhere if you would like to explore them.