# RPC Reference

All Cocoon RPC methods are available via the standard JSON-RPC 2.0 interface at the backend proxy endpoint (`http://localhost:8546` by default). Every method follows the same envelope format:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "namespace_methodName",
  "params": [...]
}
```

Standard Ethereum namespaces (`eth_`, `net_`, `web3_`) are also available and behave as per the Ethereum JSON-RPC specification.

{% hint style="info" %}
All addresses are checksummed hex strings (`0x...`). All amounts are `QUANTITY` values (hex-encoded integers) unless otherwise noted. All hashes are `DATA` values (hex-encoded byte arrays).
{% endhint %}

***

## `token_` — Permissioned Tokens

The `token_` namespace provides the full lifecycle for ERC-3643 permissioned tokens: deployment, minting, transfers, compliance, NAV publishing, and document management.

{% hint style="warning" %}
Most write methods on this namespace require an authenticated session. Pass a valid bearer token in the `Authorization` header when calling the backend proxy, or set `AUTH_MODE=advisory` for development.
{% endhint %}

### Deployment

#### `token_deploy`

Deploy a new ERC-3643 permissioned token contract.

| Field       | Value                                |
| ----------- | ------------------------------------ |
| **Params**  | `[deployParams: TokenDeployParams]`  |
| **Returns** | `{ address: ADDRESS, txHash: HASH }` |

```json
// TokenDeployParams
{
  "name": "string",
  "symbol": "string",
  "decimals": "QUANTITY",
  "owner": "ADDRESS",
  "identityRegistry": "ADDRESS",
  "compliance": "ADDRESS",
  "assetType": "\"stablecoin\" | \"fund\" | \"bond\" | \"equity\" | \"commodity\"",
  "denominatedCcy": "string"
}
```

`assetType` defaults to `fund`. `denominatedCcy` defaults to `USD` for funds, and to the token symbol for stablecoins.

***

### Minting and Burning

#### `token_mint`

Mint tokens to a single address. Requires the caller to have the `Operator` or `Admin` role.

| Field       | Value                                             |
| ----------- | ------------------------------------------------- |
| **Params**  | `[token: ADDRESS, to: ADDRESS, amount: QUANTITY]` |
| **Returns** | `{ txHash: HASH }`                                |

#### `token_batchMint`

Mint tokens to multiple addresses in a single transaction.

| Field       | Value                                                          |
| ----------- | -------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, recipients: ADDRESS[], amounts: QUANTITY[]]` |
| **Returns** | `{ txHash: HASH }`                                             |

#### `token_burn`

Burn tokens from an address. The caller must own the tokens or have an approved allowance.

| Field       | Value                                               |
| ----------- | --------------------------------------------------- |
| **Params**  | `[token: ADDRESS, from: ADDRESS, amount: QUANTITY]` |
| **Returns** | `{ txHash: HASH }`                                  |

***

### Token Controls

#### `token_pause`

Pause all transfers on a token. Only callable by the token owner.

| Field       | Value              |
| ----------- | ------------------ |
| **Params**  | `[token: ADDRESS]` |
| **Returns** | `{ txHash: HASH }` |

#### `token_freeze`

Freeze transfers to or from a specific address.

| Field       | Value                                                 |
| ----------- | ----------------------------------------------------- |
| **Params**  | `[token: ADDRESS, address: ADDRESS, frozen: boolean]` |
| **Returns** | `{ txHash: HASH }`                                    |

#### `token_forcedTransfer`

Execute a forced transfer between two addresses, bypassing standard compliance checks. Requires `Admin` role. Used for regulatory recovery scenarios.

| Field       | Value                                                            |
| ----------- | ---------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, from: ADDRESS, to: ADDRESS, amount: QUANTITY]` |
| **Returns** | `{ txHash: HASH }`                                               |

#### `token_recovery`

Recover tokens from a lost wallet by transferring the full balance to a new address. Both the old and new addresses must have verified identities linked to the same investor record.

| Field       | Value                                                                                   |
| ----------- | --------------------------------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, lostWallet: ADDRESS, newWallet: ADDRESS, investorOnchainId: ADDRESS]` |
| **Returns** | `{ txHash: HASH }`                                                                      |

#### `token_canTransfer`

Dry-run a transfer to check whether compliance rules permit it, without submitting a transaction.

| Field       | Value                                                            |
| ----------- | ---------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, from: ADDRESS, to: ADDRESS, amount: QUANTITY]` |
| **Returns** | `{ allowed: boolean, reason: string \| null }`                   |

***

### Investor Onboarding

#### `token_onboardInvestor`

Register an investor address against the token's identity registry. The investor must already have an on-chain identity (see `id_createIdentity`).

| Field       | Value                                                    |
| ----------- | -------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, investor: ADDRESS, identity: ADDRESS]` |
| **Returns** | `{ txHash: HASH }`                                       |

#### `token_getHolders`

Return a paginated list of current token holders with their balances.

| Field       | Value                                                                     |
| ----------- | ------------------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, offset?: QUANTITY, limit?: QUANTITY]`                   |
| **Returns** | `{ holders: [{ address: ADDRESS, balance: QUANTITY }], total: QUANTITY }` |

#### `token_getHolder`

Return detailed information for a single holder.

| Field       | Value                                                                                 |
| ----------- | ------------------------------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, address: ADDRESS]`                                                  |
| **Returns** | `{ address: ADDRESS, balance: QUANTITY, frozen: boolean, identity: ADDRESS \| null }` |

#### `token_getTokenInfo`

Return static and dynamic metadata for a token.

| Field       | Value                                                                                                                                                                                                                            |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS]`                                                                                                                                                                                                               |
| **Returns** | `{ name: string, symbol: string, decimals: QUANTITY, totalSupply: QUANTITY, paused: boolean, owner: ADDRESS, compliance: ADDRESS, identityRegistry: ADDRESS, assetType: string, denominatedCcy: string, holderCount: QUANTITY }` |

***

### NAV and Pricing

#### `token_publishNAV`

Publish a new Net Asset Value for a fund token. The NAV is stored on-chain and used by subscription/redemption calculations.

| Field       | Value                                                          |
| ----------- | -------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, navPerShare: QUANTITY, timestamp: QUANTITY]` |
| **Returns** | `{ txHash: HASH }`                                             |

#### `token_publishPrice`

Publish a generic price feed entry for a token (used for non-NAV instruments such as bonds or stablecoins with FX rates).

| Field       | Value                                                                      |
| ----------- | -------------------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, price: QUANTITY, currency: string, timestamp: QUANTITY]` |
| **Returns** | `{ txHash: HASH }`                                                         |

#### `token_getFeedHistory`

Retrieve historical NAV or price feed entries.

| Field       | Value                                                                                     |
| ----------- | ----------------------------------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, fromTimestamp: QUANTITY, toTimestamp: QUANTITY, limit?: QUANTITY]`      |
| **Returns** | `{ entries: [{ value: QUANTITY, currency: string, timestamp: QUANTITY, txHash: HASH }] }` |

### Fund Balance Sheet

#### `token_getFundBalanceSheet`

Return a snapshot of a fund token's balance sheet, showing liabilities (shares outstanding, NAV, AUM) and assets (stablecoin reserves, DBC bridge reserves, and bank cash).

| Field       | Value                                                                                                                                                                                                |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS]`                                                                                                                                                                                   |
| **Returns** | `{ liabilities: { sharesOutstanding: QUANTITY, nav: QUANTITY, aum: QUANTITY }, assets: { stablecoins: { [symbol: string]: string }, dbcReserves: { [symbol: string]: string }, bankCash: string } }` |

***

### Compliance Modules

#### `token_addComplianceModule`

Attach a compliance module contract to a token. Modules are called on every transfer and can block or modify it.

| Field       | Value                               |
| ----------- | ----------------------------------- |
| **Params**  | `[token: ADDRESS, module: ADDRESS]` |
| **Returns** | `{ txHash: HASH }`                  |

#### `token_setCountryAllowList`

Configure the country allow-list compliance module. Only investors with identity claims matching an allowed country code can hold the token.

| Field       | Value                                               |
| ----------- | --------------------------------------------------- |
| **Params**  | `[token: ADDRESS, allowedCountryCodes: QUANTITY[]]` |
| **Returns** | `{ txHash: HASH }`                                  |

#### `token_setMaxBalance`

Set the maximum token balance any single investor may hold.

| Field       | Value                                    |
| ----------- | ---------------------------------------- |
| **Params**  | `[token: ADDRESS, maxBalance: QUANTITY]` |
| **Returns** | `{ txHash: HASH }`                       |

***

### Document Management

#### `token_publishDocument`

Attach a document to a token. The document content is stored via the torrent layer; only the content hash and metadata are stored on-chain.

| Field       | Value                                                                             |
| ----------- | --------------------------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, name: string, docType: string, uri: string, contentHash: HASH]` |
| **Returns** | `{ txHash: HASH, docId: HASH }`                                                   |

#### `token_getDocument`

Retrieve a document record by ID.

| Field       | Value                                                                                      |
| ----------- | ------------------------------------------------------------------------------------------ |
| **Params**  | `[token: ADDRESS, docId: HASH]`                                                            |
| **Returns** | `{ name: string, docType: string, uri: string, contentHash: HASH, publishedAt: QUANTITY }` |

#### `token_listDocuments`

List all documents attached to a token.

| Field       | Value                                                                                                 |
| ----------- | ----------------------------------------------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS]`                                                                                    |
| **Returns** | `{ documents: [{ docId: HASH, name: string, docType: string, uri: string, publishedAt: QUANTITY }] }` |

***

### Subscriptions and Redemptions

#### `token_subscribe`

Subscribe to a fund token by exchanging a stablecoin amount for token shares at the current NAV.

| Field       | Value                                      |
| ----------- | ------------------------------------------ |
| **Params**  | `[token: ADDRESS, stableAmount: QUANTITY]` |
| **Returns** | `{ txHash: HASH, sharesIssued: QUANTITY }` |

#### `token_redeem`

Redeem token shares for the underlying stablecoin at the current NAV.

| Field       | Value                                        |
| ----------- | -------------------------------------------- |
| **Params**  | `[token: ADDRESS, shares: QUANTITY]`         |
| **Returns** | `{ txHash: HASH, stableReturned: QUANTITY }` |

***

## `id_` — Identity

The `id_` namespace manages on-chain identities, claims, and claim access control using the OnchainID / ERC-734/735 standard.

#### `id_createIdentity`

Deploy a new on-chain identity contract for an investor address.

| Field       | Value                                       |
| ----------- | ------------------------------------------- |
| **Params**  | `[owner: ADDRESS, managementKeys?: HASH[]]` |
| **Returns** | `{ identity: ADDRESS, txHash: HASH }`       |

#### `id_issueClaim`

Issue a signed claim to an identity. The caller must be a trusted claim issuer registered in the `TrustedIssuersRegistry`.

| Field       | Value                                                                             |
| ----------- | --------------------------------------------------------------------------------- |
| **Params**  | `[identity: ADDRESS, topic: QUANTITY, scheme: QUANTITY, data: DATA, uri: string]` |
| **Returns** | `{ claimId: HASH, txHash: HASH }`                                                 |

The `topic` field uses the ERC-735 claim topic registry. Registered topics:

| Topic (decimal) | Name                | Description                                       |
| --------------- | ------------------- | ------------------------------------------------- |
| `1`             | KYC                 | Identity verification                             |
| `2`             | AML                 | Anti-money-laundering screening                   |
| `3`             | Accreditation       | Accredited / qualified investor status            |
| `4`             | Sanctions Clear     | Continuous sanctions screening (30-day rolling)   |
| `5`             | Tax Residency       | CRS / FATCA tax residency declaration             |
| `6`             | UBO                 | Ultimate Beneficial Owner declaration             |
| `7`             | PEP Status          | Politically Exposed Person check (30-day rolling) |
| `8`             | Travel Rule Profile | Originator information for payment disclosures    |

#### `id_getClaim`

Retrieve a claim by its ID.

| Field       | Value                                                                                                             |
| ----------- | ----------------------------------------------------------------------------------------------------------------- |
| **Params**  | `[identity: ADDRESS, claimId: HASH]`                                                                              |
| **Returns** | `{ claimId: HASH, topic: QUANTITY, scheme: QUANTITY, issuer: ADDRESS, data: DATA, uri: string, signature: DATA }` |

#### `id_grantClaimAccess`

Grant a third party (e.g. a regulator or auditor) read access to an encrypted claim document stored via the torrent layer.

| Field       | Value                                                                      |
| ----------- | -------------------------------------------------------------------------- |
| **Params**  | `[identity: ADDRESS, claimId: HASH, grantee: ADDRESS, encryptedKey: DATA]` |
| **Returns** | `{ txHash: HASH }`                                                         |

#### `id_revokeClaim`

Revoke a previously issued claim.

| Field       | Value                                |
| ----------- | ------------------------------------ |
| **Params**  | `[identity: ADDRESS, claimId: HASH]` |
| **Returns** | `{ txHash: HASH }`                   |

#### `id_getIdentity`

Look up the on-chain identity address for a wallet address.

| Field       | Value                                                   |
| ----------- | ------------------------------------------------------- |
| **Params**  | `[address: ADDRESS]`                                    |
| **Returns** | `{ identity: ADDRESS \| null, owner: ADDRESS \| null }` |

#### `id_submitKycApplication`

Submit a KYC application for a given identity and claim topic, attaching supporting documents for issuer review.

| Field       | Value                                                     |
| ----------- | --------------------------------------------------------- |
| **Params**  | `[identity: ADDRESS, topic: QUANTITY, documents: DATA[]]` |
| **Returns** | `{ applicationId: string }`                               |

#### `id_getKycApplication`

Return the current status and metadata of a previously submitted KYC application.

| Field       | Value                                                                                                             |
| ----------- | ----------------------------------------------------------------------------------------------------------------- |
| **Params**  | `[applicationId: string]`                                                                                         |
| **Returns** | `{ applicationId: string, status: string, topic: QUANTITY, submittedAt: QUANTITY, reviewedAt: QUANTITY \| null }` |

`status` values: `pending`, `approved`, `rejected`.

#### `id_reviewKycApplication`

Approve or reject a KYC application. Caller must be the trusted claim issuer for the relevant topic. Approving the application issues the claim on-chain.

| Field       | Value                                                                      |
| ----------- | -------------------------------------------------------------------------- |
| **Params**  | `[applicationId: string, decision: "approve" \| "reject", notes?: string]` |
| **Returns** | `{ txHash: HASH \| null }`                                                 |

#### `id_renewClaim`

Renew an expiring claim. The issuer re-runs verification and replaces the old claim with a new one carrying an extended expiry.

| Field       | Value                                |
| ----------- | ------------------------------------ |
| **Params**  | `[identity: ADDRESS, claimId: HASH]` |
| **Returns** | `{ claimId: HASH, txHash: HASH }`    |

***

## `dbc_` — Confidential Cash

The `dbc_` namespace provides the full lifecycle for Digital Bearer Certificate (DBC) confidential value transfer: minting from ERC-20, private transfers, melting back to ERC-20, and regulated payment envelopes for institutional compliance.

{% hint style="warning" %}
DBC write methods require an authenticated session and appropriate UCAN capability. See the `## UCAN Capabilities` section in the Confidential Cash component guide for the full capability namespace.
{% endhint %}

#### `dbc_mint`

Lock ERC-20 tokens in the bridge and create a confidential DBC note.

| Field       | Value                                                         |
| ----------- | ------------------------------------------------------------- |
| **Params**  | `[token: ADDRESS, amount: QUANTITY, receiverPublicKey: DATA]` |
| **Returns** | `{ txHash: HASH, noteCommitment: DATA }`                      |

#### `dbc_melt`

Spend a DBC note and release the corresponding ERC-20 amount from the bridge.

| Field       | Value                                                      |
| ----------- | ---------------------------------------------------------- |
| **Params**  | `[noteId: DATA, keyImage: DATA, proof: DATA, to: ADDRESS]` |
| **Returns** | `{ txHash: HASH, amount: QUANTITY }`                       |

#### `dbc_transfer`

Spend input notes and create output notes using a ring signature and range proof.

| Field       | Value                                                                      |
| ----------- | -------------------------------------------------------------------------- |
| **Params**  | `[inputs: DATA[], outputs: DATA[], ringSignature: DATA, rangeProof: DATA]` |
| **Returns** | `{ txHash: HASH }`                                                         |

#### `dbc_getBalance`

Scan the note pool for outputs belonging to the caller's view key and return the spendable balance.

| Field       | Value                                        |
| ----------- | -------------------------------------------- |
| **Params**  | `[viewKey: DATA]`                            |
| **Returns** | `{ balance: QUANTITY, noteCount: QUANTITY }` |

#### `dbc_getEscrow`

Return the aggregate DBC bridge escrow holdings across all token symbols. Intended for fund manager use to monitor DBC reserves backing the fund.

| Field       | Value                               |
| ----------- | ----------------------------------- |
| **Params**  | `[]`                                |
| **Returns** | `{ [tokenSymbol: string]: string }` |

#### `dbc_sendRegulatedPayment`

Send a UCAN-wrapped DBC payment envelope with per-recipient selective disclosures and optional Travel Rule attachments.

| Field       | Value                                 |
| ----------- | ------------------------------------- |
| **Params**  | `[envelope: RegulatedDBCPayment]`     |
| **Returns** | `{ txHash: HASH, paymentId: string }` |

```json
// RegulatedDBCPayment (envelope)
{
  "sender": "ADDRESS",
  "recipients": ["ADDRESS"],
  "dbcPayment": "DATA",
  "disclosures": [{ "topic": "QUANTITY", "claimRef": "HASH" }],
  "travelRule": { "originatorName": "string", "originatorAccount": "string" } | null
}
```

#### `dbc_getPaymentReceipt`

Return the status and signed receipt for a regulated DBC payment once the counterparty has confirmed it.

| Field       | Value                                                          |
| ----------- | -------------------------------------------------------------- |
| **Params**  | `[paymentId: string]`                                          |
| **Returns** | `{ paymentId: string, status: string, receipt: DATA \| null }` |

`status` values: `pending`, `confirmed`, `rejected`, `refunded`.

***

## `auth_` — Authorization

The `auth_` namespace exposes the UCAN capability system and session management. UCAN delegations are encoded as JWTs and attached to transactions via EIP-8141 frame envelopes.

#### `auth_login`

Verify a Sign-In with Ethereum (SIWE) signature, discover the caller's on-chain roles, and return a UCAN session token.

| Field       | Value                                                                   |
| ----------- | ----------------------------------------------------------------------- |
| **Params**  | `[siweMessage: string, signature: DATA]`                                |
| **Returns** | `{ ucan: string, address: ADDRESS, roles: RoleSet, expiresAt: string }` |

`RoleSet` structure:

```json
{
  "tokens": [{ "address": "0x...", "name": "string", "roles": ["owner", "agent"] }],
  "claimIssuer": { "topics": [1, 2] } | null,
  "investor": { "identity": "0x...", "country": 756, "verified": true } | null
}
```

#### `auth_getSession`

Check the validity and remaining lifetime of an existing session token.

| Field       | Value                                                                                                 |
| ----------- | ----------------------------------------------------------------------------------------------------- |
| **Params**  | `[ucan: string]`                                                                                      |
| **Returns** | `{ valid: boolean, address: ADDRESS, roles: RoleSet, expiresAt: string, remainingSeconds: QUANTITY }` |

#### `auth_refreshRoles`

Re-discover on-chain roles for the authenticated user without requiring a new SIWE sign-in. Useful when on-chain role assignments change while a session is active.

| Field       | Value                                  |
| ----------- | -------------------------------------- |
| **Params**  | `[ucan: string]`                       |
| **Returns** | `{ roles: RoleSet, changed: boolean }` |

#### `auth_createDelegation`

Create a UCAN capability delegation, granting an audience address the ability to invoke specified methods on behalf of the issuer.

| Field       | Value                                                                                     |
| ----------- | ----------------------------------------------------------------------------------------- |
| **Params**  | `[issuer: ADDRESS, audience: ADDRESS, capabilities: Capability[], expiration?: QUANTITY]` |
| **Returns** | `{ delegation: string, cid: HASH }`                                                       |

```json
// Capability
{
  "with": "cocoon:token/0xTokenAddress",
  "can": "token/transfer"
}
```

#### `auth_verify`

Verify that a delegation JWT is valid, unexpired, and not revoked.

| Field       | Value                                                                                                              |
| ----------- | ------------------------------------------------------------------------------------------------------------------ |
| **Params**  | `[delegation: string]`                                                                                             |
| **Returns** | `{ valid: boolean, issuer: ADDRESS, audience: ADDRESS, capabilities: Capability[], expiration: QUANTITY \| null }` |

#### `auth_inspect`

Decode and return the contents of a delegation JWT without verifying chain or revocation status.

| Field       | Value                                                                                                                           |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------- |
| **Params**  | `[delegation: string]`                                                                                                          |
| **Returns** | `{ issuer: ADDRESS, audience: ADDRESS, capabilities: Capability[], expiration: QUANTITY \| null, notBefore: QUANTITY \| null }` |

#### `auth_revoke`

Revoke a previously issued delegation. Writes the delegation CID to the on-chain revocation registry.

| Field       | Value              |
| ----------- | ------------------ |
| **Params**  | `[cid: HASH]`      |
| **Returns** | `{ txHash: HASH }` |

***

## `qm_` — QMTree State

The `qm_` namespace exposes the QMTree Merkle state commitment. QMTree is the core data structure used to generate ZK proofs and verify state transitions.

#### `qm_getRoot`

Return the current QMTree root hash at a given block.

| Field       | Value                                                    |
| ----------- | -------------------------------------------------------- |
| **Params**  | `[blockNumber?: QUANTITY]`                               |
| **Returns** | `{ root: HASH, blockNumber: QUANTITY, txNum: QUANTITY }` |

#### `qm_getLeaf`

Return the value and position of a leaf node in the QMTree.

| Field       | Value                                                         |
| ----------- | ------------------------------------------------------------- |
| **Params**  | `[key: DATA, blockNumber?: QUANTITY]`                         |
| **Returns** | `{ key: DATA, value: DATA, leafIndex: QUANTITY, twig: HASH }` |

#### `qm_getProof`

Return a Merkle inclusion proof for a leaf node.

| Field       | Value                                                             |
| ----------- | ----------------------------------------------------------------- |
| **Params**  | `[key: DATA, blockNumber?: QUANTITY]`                             |
| **Returns** | `{ proof: HASH[], root: HASH, leafIndex: QUANTITY, value: DATA }` |

#### `qm_call`

Execute a read-only contract call against the QMTree state at a given root (without requiring the full chain state). Used for off-chain verification workflows.

| Field       | Value                                   |
| ----------- | --------------------------------------- |
| **Params**  | `[to: ADDRESS, data: DATA, root: HASH]` |
| **Returns** | `{ result: DATA }`                      |

#### `qm_callProof`

Execute a contract call and return both the result and a proof of correct execution against the given QMTree root.

| Field       | Value                                     |
| ----------- | ----------------------------------------- |
| **Params**  | `[to: ADDRESS, data: DATA, root: HASH]`   |
| **Returns** | `{ result: DATA, proof: ExecutionProof }` |

#### `qm_verifyProof`

Verify an execution proof against a given QMTree root without re-executing the call.

| Field       | Value                                 |
| ----------- | ------------------------------------- |
| **Params**  | `[root: HASH, proof: ExecutionProof]` |
| **Returns** | `{ valid: boolean }`                  |

#### `qm_getKeyProof`

Return a proof of the current value bound to a key, suitable for use in a SNARK circuit.

| Field       | Value                                                   |
| ----------- | ------------------------------------------------------- |
| **Params**  | `[key: DATA, blockNumber?: QUANTITY]`                   |
| **Returns** | `{ proof: HASH[], root: HASH, key: DATA, value: DATA }` |

#### `qm_getExclusionProof`

Return a proof that a key does **not** exist in the QMTree (non-membership proof).

| Field       | Value                                      |
| ----------- | ------------------------------------------ |
| **Params**  | `[key: DATA, blockNumber?: QUANTITY]`      |
| **Returns** | `{ proof: HASH[], root: HASH, key: DATA }` |

***

## `proof_` — ZK Proofs

The `proof_` namespace manages ZK proof generation, batching, and status queries. Proofs are generated by the Zilkworm prover and posted to Ethereum by the proof pipeline.

#### `proof_getProof`

Return the ZK proof for a specific block.

| Field       | Value                                                                                                              |
| ----------- | ------------------------------------------------------------------------------------------------------------------ |
| **Params**  | `[blockNumber: QUANTITY]`                                                                                          |
| **Returns** | `{ blockNumber: QUANTITY, proof: DATA, status: ProofStatus, postedAt: QUANTITY \| null, ethTxHash: HASH \| null }` |

`ProofStatus` values: `pending`, `generating`, `ready`, `posted`, `failed`.

#### `proof_getProofStatus`

Return only the status of a proof, without the proof data itself.

| Field       | Value                                                                           |
| ----------- | ------------------------------------------------------------------------------- |
| **Params**  | `[blockNumber: QUANTITY]`                                                       |
| **Returns** | `{ blockNumber: QUANTITY, status: ProofStatus, generatedAt: QUANTITY \| null }` |

#### `proof_getBatchProof`

Return the aggregate ZK proof for a batch of blocks.

| Field       | Value                                                                                      |
| ----------- | ------------------------------------------------------------------------------------------ |
| **Params**  | `[fromBlock: QUANTITY, toBlock: QUANTITY]`                                                 |
| **Returns** | `{ fromBlock: QUANTITY, toBlock: QUANTITY, proof: DATA, root: HASH, status: ProofStatus }` |

#### `proof_getLatestProved`

Return the block number and state root of the most recently proved (and Ethereum-posted) block.

| Field       | Value                                                                             |
| ----------- | --------------------------------------------------------------------------------- |
| **Params**  | `[]`                                                                              |
| **Returns** | `{ blockNumber: QUANTITY, stateRoot: HASH, ethTxHash: HASH, postedAt: QUANTITY }` |

***

## `erigon_` — Storage and WebF Extensions

The `erigon_` namespace exposes Cocoon's extended storage and web hosting capabilities: torrent-backed document storage and on-chain web site publishing via WebF.

### Torrent Storage

#### `erigon_resolveTorrent`

Resolve a torrent-ccip content reference to its current download metadata.

| Field       | Value                                                                                                                              |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| **Params**  | `[infoHash: HASH]`                                                                                                                 |
| **Returns** | `{ infoHash: HASH, name: string, files: [{ name: string, size: QUANTITY, path: string }], trackers: string[], magnetURI: string }` |

#### `erigon_publishTorrent`

Publish a new torrent and write its on-chain content reference. The file data must be accessible to the node's torrent storage backend.

| Field       | Value                                                          |
| ----------- | -------------------------------------------------------------- |
| **Params**  | `[files: [{ name: string, data: DATA }], announce?: string[]]` |
| **Returns** | `{ infoHash: HASH, magnetURI: string, txHash: HASH }`          |

#### `erigon_getInscription`

Retrieve an on-chain inscription (small content blob written directly into a transaction's calldata via EIP-8141 frame).

| Field       | Value                                                               |
| ----------- | ------------------------------------------------------------------- |
| **Params**  | `[txHash: HASH]`                                                    |
| **Returns** | `{ txHash: HASH, contentType: string, data: DATA, size: QUANTITY }` |

### WebF — On-Chain Web Hosting

#### `erigon_publishWebSite`

Publish a static web site by bundling its files into a torrent and writing the content root on-chain. The site is then accessible via the WebF gateway.

| Field       | Value                                                                                        |
| ----------- | -------------------------------------------------------------------------------------------- |
| **Params**  | `[name: string, files: [{ path: string, data: DATA, contentType: string }], owner: ADDRESS]` |
| **Returns** | `{ siteId: HASH, infoHash: HASH, txHash: HASH, gatewayURL: string }`                         |

#### `erigon_getWebSite`

Retrieve metadata for a published web site.

| Field       | Value                                                                                                                              |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| **Params**  | `[siteId: HASH]`                                                                                                                   |
| **Returns** | `{ siteId: HASH, name: string, owner: ADDRESS, infoHash: HASH, publishedAt: QUANTITY, lastUpdated: QUANTITY, gatewayURL: string }` |

#### `erigon_listWebSites`

List all published web sites, optionally filtered by owner.

| Field       | Value                                                                                                 |
| ----------- | ----------------------------------------------------------------------------------------------------- |
| **Params**  | `[owner?: ADDRESS, offset?: QUANTITY, limit?: QUANTITY]`                                              |
| **Returns** | `{ sites: [{ siteId: HASH, name: string, owner: ADDRESS, publishedAt: QUANTITY }], total: QUANTITY }` |

***

## `fx_` — FX Oracle

The `fx_` namespace provides foreign exchange rate management for the Cocoon platform. Supported pairs: EUR/USD, EUR/CHF, EUR/GBP, GBP/USD, USD/CHF, GBP/CHF.

#### `fx_getRates`

Return all current FX rates from the oracle.

| Field       | Value                                                                          |
| ----------- | ------------------------------------------------------------------------------ |
| **Params**  | `[]`                                                                           |
| **Returns** | `{ rates: [{ from: string, to: string, rate: string, updatedAt: QUANTITY }] }` |

#### `fx_getRate`

Return the current FX rate for a single currency pair.

| Field       | Value                                                             |
| ----------- | ----------------------------------------------------------------- |
| **Params**  | `[from: string, to: string]`                                      |
| **Returns** | `{ from: string, to: string, rate: string, updatedAt: QUANTITY }` |

#### `fx_setRate`

Set the FX rate for a currency pair. Requires `Admin` or `Oracle` role.

| Field       | Value                                      |
| ----------- | ------------------------------------------ |
| **Params**  | `[from: string, to: string, rate: string]` |
| **Returns** | `{ txHash: HASH }`                         |

#### `fx_convert`

Convert an amount from one currency to another using the current oracle rate.

| Field       | Value                                                        |
| ----------- | ------------------------------------------------------------ |
| **Params**  | `[amount: string, from: string, to: string]`                 |
| **Returns** | `{ result: string, rate: string, from: string, to: string }` |

***

## `events_` — Event Stream

{% hint style="info" %}
The `events_` and `stats_` methods listed in this section are **mock-phase only**. They are available in the local development and POC environment but are not yet part of the production RPC surface. Method signatures and return shapes may change before general availability.
{% endhint %}

#### `events_getLatest`

Return the most recent chain events up to the requested count.

| Field       | Value               |
| ----------- | ------------------- |
| **Params**  | `[count: QUANTITY]` |
| **Returns** | `Event[]`           |

#### `events_getLogs`

Return events matching a filter (block range, address, topics).

| Field       | Value                                                                                        |
| ----------- | -------------------------------------------------------------------------------------------- |
| **Params**  | `[filter: { fromBlock?: QUANTITY, toBlock?: QUANTITY, address?: ADDRESS, topics?: DATA[] }]` |
| **Returns** | `Event[]`                                                                                    |

#### `stats_getChainStats`

Return aggregated chain-level statistics.

| Field       | Value                                                                                                                                         |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| **Params**  | `[]`                                                                                                                                          |
| **Returns** | `{ blockNumber: QUANTITY, tps: QUANTITY, gasPrice: QUANTITY, totalTransactions: QUANTITY, dailyCounts: { date: string, count: QUANTITY }[] }` |

#### `stats_getFundStats`

Return fund-level statistics for a specific token.

| Field       | Value                                                                                                             |
| ----------- | ----------------------------------------------------------------------------------------------------------------- |
| **Params**  | `[tokenAddress: ADDRESS]`                                                                                         |
| **Returns** | `{ totalSupply: QUANTITY, aum: QUANTITY, subscribers24h: QUANTITY, redeemers24h: QUANTITY, netFlow7d: QUANTITY }` |

***

## HTTP REST API

The backend proxy (port 8546) exposes REST endpoints alongside the JSON-RPC interface for IBAN account lookups, audit log queries, and permission management. These are not JSON-RPC methods — they are standard HTTP endpoints.

### Health

#### `GET /health`

Returns the backend's operational status.

**Response:** `{ "status": "ok", "chainReachable": true }`

***

### IBAN Registry

IBAN endpoints enable bidirectional lookup between Ethereum addresses and Swiss-style IBANs (format: `CH` + 2 check digits + chain ID + 12-digit account = 21 characters).

#### `GET /api/ibans`

Return all registered IBAN accounts.

**Response:**

```json
{
  "ibans": [
    { "iban": "CH7900033000000000001", "address": "0xf39Fd6e5...", "name": "Admin" },
    { "iban": "CH5200033000000000002", "address": "0x70997970...", "name": "Alice" }
  ]
}
```

#### `GET /api/iban/:code`

Resolve an IBAN to its registered Ethereum address and display name.

**Response:** `{ "iban": "CH5200033000000000002", "address": "0x70997970...", "name": "Alice" }`

Returns HTTP 404 if the IBAN is not registered.

#### `GET /api/address/:addr/iban`

Reverse lookup: resolve an Ethereum address to its IBAN.

**Response:** `{ "address": "0x70997970...", "iban": "CH5200033000000000002", "name": "Alice" }`

Returns HTTP 404 if the address has no registered IBAN.

***

### Audit Log

Audit endpoints allow querying the audit log of all proxied RPC calls. Requires `Admin`, `Compliance`, or `Auditor` role.

#### `GET /api/audit`

Query the audit log with optional filters.

**Query parameters:**

| Parameter | Type     | Description                         |
| --------- | -------- | ----------------------------------- |
| `address` | string   | Filter by Ethereum address          |
| `user_id` | string   | Filter by user UUID                 |
| `method`  | string   | Filter by RPC method (prefix match) |
| `status`  | string   | `success`, `error`, or `blocked`    |
| `from`    | ISO 8601 | Start of time range                 |
| `to`      | ISO 8601 | End of time range                   |
| `offset`  | integer  | Pagination offset                   |
| `limit`   | integer  | Page size (default 50, max 500)     |

**Response:**

```json
{
  "entries": [{
    "id": 12345,
    "timestamp": "2026-04-13T10:00:00Z",
    "user_id": "uuid",
    "ethereum_address": "0x...",
    "role": "Trader",
    "method": "token_transfer",
    "params": { "token": "0x...", "to": "0x...", "amount": "1000..." },
    "status": "blocked",
    "error_code": -32001,
    "chain_tx_hash": null,
    "ip_address": "192.168.1.10"
  }],
  "total": 1,
  "offset": 0,
  "limit": 50
}
```

#### `GET /api/audit/:id`

Return a single audit entry by ID.

#### `GET /api/audit/export`

Export filtered audit entries as a CSV file. Accepts the same query parameters as `GET /api/audit`.

***

### Permission Rules

#### `GET /api/permissions`

List all active permission rules in the `PermissionRegistry`.

**Response:**

```json
{
  "rules": [
    { "id": 1, "role": "Trader", "method": "token_transfer", "argument": "amount", "constraint_type": "max_value", "constraint_value": "1000000000000000000000000", "active": true }
  ]
}
```

#### `POST /api/permissions`

Add a new permission rule. Writes to the `PermissionRegistry` contract on-chain. Requires `Admin` role.

**Request:**

```json
{
  "role": "SeniorTrader",
  "method": "token_transfer",
  "argument": "amount",
  "constraint_type": "max_value",
  "constraint_value": "5000000000000000000000000"
}
```

#### `DELETE /api/permissions/:id`

Remove a permission rule. Requires `Admin` role.

***

## Error Codes

All JSON-RPC methods return standard JSON-RPC errors. Cocoon-specific error codes:

| Code     | Name                      | Description                                                                                  |
| -------- | ------------------------- | -------------------------------------------------------------------------------------------- |
| `-32001` | `TransferNotAllowed`      | A `token_*` write was blocked by a compliance rule. The `message` field contains the reason. |
| `-32002` | `IdentityNotFound`        | The target address has no registered on-chain identity.                                      |
| `-32003` | `ClaimMissing`            | A required claim (KYC, accreditation, etc.) is absent or expired.                            |
| `-32004` | `DelegationInvalid`       | A UCAN delegation is malformed, expired, or revoked.                                         |
| `-32005` | `ProofNotReady`           | The requested ZK proof has not been generated yet.                                           |
| `-32006` | `TorrentUnavailable`      | The requested torrent content is not available from any peer.                                |
| `-32007` | `Unauthorized`            | The request lacks a valid session token and `AUTH_MODE=strict` is set.                       |
| `-32008` | `PaymentPending`          | A regulated DBC payment is awaiting receipt confirmation from the counterparty.              |
| `-32009` | `ClaimApplicationPending` | A KYC application has been submitted but not yet reviewed by the issuer.                     |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cocoon.erigon.tech/reference/rpc-reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
