For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to page URLs.
Skip to content

ZamaSDK

Entry point for all confidential contract operations.

Entry point for all confidential contract operations — creates tokens, manages permits, and coordinates the relayer and signer.

Import

import { ZamaSDK } from "@zama-fhe/sdk";

Usage

import { createConfig } from "@zama-fhe/sdk/viem";
import { ZamaSDK } from "@zama-fhe/sdk";
import { web } from "@zama-fhe/sdk/web";
import { sepolia, mainnet } from "@zama-fhe/sdk/chains";

const config = createConfig({
  chains: [sepolia, mainnet],
  publicClient,
  walletClient,
  relayers: { [sepolia.id]: web(), [mainnet.id]: web() },
});

const sdk = new ZamaSDK(config);
import { createConfig, ZamaSDK, memoryStorage } from "@zama-fhe/sdk";
import { node } from "@zama-fhe/sdk/node";
import { sepolia } from "@zama-fhe/sdk/chains";

const config = createConfig({
  chains: [sepolia],
  signer: myCustomSigner, // GenericSigner
  provider: myCustomProvider, // GenericProvider
  storage: memoryStorage,
  relayers: { [sepolia.id]: node() },
});

const sdk = new ZamaSDK(config);

createConfig options

All options below are passed to createConfig(), which validates them and returns a ZamaConfig for the ZamaSDK constructor.

chains

readonly FheChain[]

FHE chain configurations. At least one chain is required. Use built-in presets from @zama-fhe/sdk/chains.

relayers

Record<number, RelayerConfig>, one entry per chain in chains, keyed by chain id

Per-chain relayer factories. A chain in chains without an entry fails createConfig with a ConfigurationError. An entry whose chain is not in chains is unused: createConfig warns through your logger and ignores it.

provider / signer

Created automatically by adapter-specific createConfig (viem, ethers, wagmi). For the generic createConfig from @zama-fhe/sdk, pass a GenericProvider and optionally a GenericSigner. Omit the signer for read-only usage (indexers, SSR). Signer-dependent operations throw SignerNotConfiguredError when invoked without a signer.

storage

GenericStorage | undefined

Persists the encrypted transport key pair across sessions. Use indexedDBStorage (browser), memoryStorage (tests), or asyncLocalStorage (Node.js servers). Defaults to indexedDBStorage in browsers, memoryStorage elsewhere.

permitStorage

GenericStorage | undefined

Optional dedicated storage for permits. Defaults to storage. Use this to keep permits out of long-lived storage (e.g. IndexedDB for transport key pair, memory for permits) for high-security flows.

transportKeyPairTTL

number | undefined

Transport key pair validity duration in seconds. Default: 2592000 (30 days). Must be a positive integer. After expiry, the next decrypt prompts a wallet signature to regenerate the key pair.

permitTTL

number | undefined

Permit lifetime in days. Default: 30. Controls how long each signed EIP-712 permit remains valid.

clearCredentialsOnWalletChange

boolean | undefined

Wipe the previous account's transport key pair, permits, and decrypt cache whenever the connected account changes or disconnects (account switch, empty account list, disconnect). Default: true. Set to false to keep them: credentials are stored per signer address, so a user switching A → B → A then reuses A's permits and cached decrypts without signing again. Permits expire after permitTTL and transport key pairs after transportKeyPairTTL; cached decrypts stay until permits.clear or permits.revokePermits runs. With the option off, call permits.clear in your sign-out flow while the wallet is still connected.

transportKeyPairScope

string | undefined

Opt-in shared-tenant scope for Wallet-as-a-Service / B2B2C operators managing many end-user wallets from one operator-controlled key store. An opaque identifier (typically a tenant ID) — every signer configured with the same scope shares one transport key pair instead of one per signer. Permits stay per-signer regardless of scope. Default: undefined (one transport key pair per signer).

Sharing only works when every signer in the scope reads and writes the same storage instance. See Security Model for the tradeoff, and permits.warmTransportKeyPairScope / permits.revokeTransportKeyPair for the scope's lifecycle.

registryTTL

number | undefined

How long cached registry results remain valid, in seconds. Default: 86400 (24 hours). Must be a non-negative integer.

onEvent

ZamaSDKEventListener | undefined

Lifecycle event callback for debugging and telemetry. Events never carry private keys, permit signatures, or ZK proofs — but DecryptEnd/DecryptError do carry decrypted cleartext values (see below), so avoid logging full event payloads for those two if your logging pipeline isn't already trusted with plaintext.

Events

Every event extends a common shape (an optional tokenAddress, a timestamp, and, for multi-phase operations like unshield, a shared operationId), plus fields specific to its type:

Event
Fires when

EncryptStart / EncryptEnd / EncryptError

An FHE encryption begins, succeeds, or fails.

DecryptStart / DecryptEnd / DecryptError

A decryption begins, succeeds, or fails — DecryptEnd/DecryptError carry decrypted cleartext values; see decryption.decryptValues for the full walkthrough and code samples.

PermitError

grantPermit, grantDelegationPermit, or registerPermit fails — but not every failure of these methods: transport-key-pair issues (TransportKeyPairChangedError, KeyWrappingError) are deliberately excluded from this event.

TransactionError

submitTransaction itself rejects — before broadcast (estimation/validation), while waiting for the receipt, or when the mined receipt reports a revert (receipt.status === "reverted").

ShieldSubmitted, TransferSubmitted, TransferFromSubmitted, SetOperatorSubmitted, ApproveUnderlyingSubmitted, WrapSubmitted, UnwrapSubmitted, FinalizeUnwrapSubmitted

The corresponding write transaction is submitted — each carries the transaction's txHash.

VaultSubmitted

A vault write is submitted — carries the txHash, the address of the contract the transaction calls as tokenAddress (the batcher, the router, or the token for a join sent as a token transfer), and vaultOperation (join, quit, claim, dispatchBatch, finalize, or routerJoin for a multi-vault join). See Vault deposits and redemptions.

DelegationSubmitted / RevokeDelegationSubmitted

A delegation grant or revoke transaction is submitted — see Delegation events.

UnshieldPhase1Submitted / UnshieldPhase2Started / UnshieldPhase2Submitted

The two-phase unshield flow's request and finalize steps progress.

TransactionError and PermitError usually carry the same classified error your await also throws or rejects with, so you can wire similar handling into telemetry — but don't assume they always match exactly. One documented exception: finalizing an already-finalized unshield concurrently (two tabs, a double click) emits TransactionError with the raw TransactionRevertedError from the losing finalize attempt, then unshield()/unshieldAll()/resumeUnshield() translates that into the more specific UnshieldAlreadyFinalizedError before it reaches your await.

TransactionError.operation is one of the write operations (transfer, wrap, unwrap, finalizeUnwrap, delegateDecryption, and others); PermitError.operation is grantPermit, grantDelegationPermit, or registerPermit. See SigningRejectedError and SigningFailedError for the shapes PermitError.error most commonly carries.

telemetry

"header" | "query" | "off" | boolean | undefined

How the SDK usage labels (SDK version, package layer, runtime, and high-level operation) travel on relayer requests. "header" (default) sends them as x-zama-sdk-* headers. "query" sends them as zama_sdk_* query parameters instead, for proxies that rebuild the request headers. "off" sends nothing. true and false are still accepted and mean "header" and "off". The labels carry no end-user data; a self-hosted relayer simply ignores them. See SDK usage telemetry for exactly what is sent.

runtime

FhevmRuntimeConfig | undefined

Global @fhevm/sdk runtime config — WASM asset loading, threading, module versions, and a process-wide fallback relayer auth. See Configuration: tune FHE runtime performance and behavior for the full field-by-field walkthrough and defaults.

runtime.logger is not forwarded — pass your logger via createConfig's top-level logger instead. runtime.auth is a process-wide fallback relayer authentication, forwarded to @fhevm/sdk as-is; see Authentication for the auth methods.

logger

GenericLogger | undefined

Optional logger for SDK diagnostics — a minimal four-level interface (error/warn/info/debug) that console and common logging libraries (pino, winston, an OpenTelemetry DiagLogger) satisfy directly. The SDK is silent by default and never bundles a logging library. See Configuration: supply a logger for level conventions.

Constructor options

The ZamaSDK constructor takes the resolved ZamaConfig plus an optional second argument for options that apply to the SDK instance rather than the shared config:

transportKeyPairDerivationSecret

string | Uint8Array | undefined

Encrypts the transport private key before every write, for headless environments with no secure storage backend to delegate to (a CLI tool, an agent, a bare-metal box). Default: undefined — the transport key pair is stored in plaintext, and at-rest security is delegated to the storage backend. Rejected outside a headless environment (a browser or React Native constructor throws ConfigurationError), since those already have a secure default (IndexedDB, a platform keychain) that this option would only weaken.

See Configuration: wrap the transport key pair at rest for environment-by-environment guidance and Security Model for the mechanism and entropy requirements.

Properties

registry

WrappersRegistry (readonly)

Auto-configured wrappers registry instance. Shares the SDK's provider, chain registry addresses, and registryTTL. Prefer this over createWrappersRegistry() to benefit from a single shared cache.

Methods

createToken

(address: Address) => Token

Creates a Token instance for an ERC-7984 confidential token. Supports balance reads, encrypted transfers, operator approvals, and delegated decryption.

createWrappedToken

(address: Address) => WrappedToken

Creates a WrappedToken instance for an ERC-7984 ERC-20 wrapper. Adds wrapper-specific operations (shield, unshield, allowance) on top of the base Token API. The address is the wrapper contract itself — the wrapper IS the confidential token.

createWrappersRegistry

(registryAddresses?: Record<number, Address>) => WrappersRegistry

Creates a wrappers registry instance for querying on-chain token wrapper pairs. Registry addresses come from built-in defaults, configured chain definitions, and optional overrides passed to this method.

permits.grantPermit

(contractAddresses: Address[]) => Promise<void>

Pre-authorize contract addresses for decryption. Signs permits only for contracts not already covered by existing permits. Subsequent decryption.decryptValues calls whose encrypted values span the covered set proceed without a wallet prompt.

permits.hasPermit

(contractAddresses: Address[]) => Promise<boolean>

Checks whether the current signer already has stored permits covering every requested contract address. This is a pure storage lookup: it does not prompt the wallet and returns false when the SDK has no signer.

Use this for UI state. sdk.permits.grantPermit() is already idempotent and skips the wallet prompt when a covering permit exists.

permits.grantDelegationPermit

(delegator: Address, contractAddresses: Address[]) => Promise<void>

Signs and stores a delegated-decryption permit for contracts that the connected signer will decrypt on behalf of delegator. The on-chain delegation must already exist and have propagated before delegated decryption succeeds.

permits.hasDelegationPermit

(delegator: Address, contractAddresses: Address[]) => Promise<boolean>

Checks whether the current signer has stored delegated-decryption permits for delegator and every requested contract.

permits.registerPermit

(prepared: PreparedPermit, signature: Hex) => Promise<void>

Verify and persist the signature an out-of-process signer produced for an offline.preparePermit payload — the second phase of the offline permit flow. No wallet account required: the permit is scoped by prepared.signerAddress and, for a delegated permit, the delegator address embedded in the signature-verified eip712 — not a connected signer. Idempotent: registering the same (prepared, signature) pair more than once (e.g. a retried webhook delivery) replaces the stored entry instead of duplicating it.

Throws:

  • ConfigurationError - prepared doesn't match the PreparedPermit shape (e.g. it crossed a process boundary and was corrupted)

  • PreparedPermitChainMismatchError - the chain embedded in prepared.eip712 doesn't match the currently active chain

  • PreparedPermitExpiredError - the permit's validity window has already elapsed

  • TransportKeyPairChangedError - no transport key pair is stored for prepared.signerAddress, or it no longer matches the public key prepared.eip712 was built against (e.g. a TTL expiry or eviction in between); call preparePermit again

  • SigningFailedError - the signature is invalid or malformed

See the Offline reference for preparePermit's request/response shape and the Offline signing guide for the full workflow.

permits.batchRegisterPermits

(permits: SignedPreparedPermit[]) => Promise<void>

registerPermit for every offline.batchPreparePermits payload, each paired with its signature. Every permit is verified before any is stored, so a permit that fails verification leaves the store untouched. Storing stays best-effort, like registerPermit: a failed store write is logged, not thrown. Throws ConfigurationError for an empty list, and otherwise whatever registerPermit throws for the first failing permit; with more than one permit, the error message is prefixed with that permit's position (permits[i]: …).

decryption.decryptValues

(inputs: DecryptInput[]) => Promise<Record<EncryptedValue, ClearValue>>

Renamed from decryption.userDecrypt (then briefly decryptValuesFromPairs) to align with the Zama glossary and the SDK's single-entrypoint design (prerelease rename). If you were on an old name, update call sites to decryptValues.

Decrypt one or more FHE encrypted values. Returns cached values when available, only calling the relayer for uncached inputs. Results are written through the SDK's internal CachingService so subsequent calls for the same inputs return instantly.

Inputs from different contracts can be mixed — they are grouped by contractAddress, and each group is sent to the relayer as one or more requests (up to 5 concurrently): a group is automatically split into multiple chunked requests when its cumulative cleartext-bit cost would exceed the KMS gateway's per-request budget, so an oversized batch for one contract still succeeds instead of being rejected. Zero encrypted values (32 zero bytes) resolve to 0n without hitting the relayer.

When the relayer is actually called, permits are resolved from the contract addresses of the full input set (including cached and zero entries), ensuring a stable permit scope regardless of which entries happen to be cached. If every entry is zero or already cached, no permits are needed and no wallet prompt is shown.

To observe decryption lifecycle, subscribe to SDK events (DecryptStart, DecryptEnd, DecryptError) via the onEvent config. Events fire only when the relayer is actually called — the all-zero and fully-cached paths return silently.

The onEvent callback is a single function, so for multi-listener observability you can bridge it into a standard event bus. Pick whichever matches your runtime:

This is the SDK-level entry point for user decryption — a single method that takes a list of value/contract pairs and decrypts them with the connected wallet's credentials (the Zama glossary splits this into decryptValue/decryptValues/decryptValuesFromPairs; the SDK intentionally exposes just one). It is distinct from decryptPublicValues (gateway-level decryption that happens on-chain without user authentication). In React, use useDecryptValues which wraps sdk.decryption.decryptValues with TanStack Query semantics.

onWalletAccountChange

(listener: (change: WalletAccountChange) => void) => () => void

Subscribe to wallet account transitions (connect, disconnect, account change, chain change). Returns an unsubscribe function. Each transition carries previous and next wallet account objects ({ address, chainId }).

permits.revokePermits

(contracts?: Address[]) => Promise<void>

Remove signed permits for the current signer. With a contract list, removes permits on the current chain whose payload touches any listed address. Without arguments, removes all permits across all chains and delegators. The transport key pair is not affected.

permits.clear

() => Promise<void>

Wipe the transport key pair and cascade-delete every permit for the current signer. Use for "log out" flows.

permits.warmTransportKeyPair

() => Promise<void>

Best-effort transport key pair prefetch for the connected signer — an optional latency optimization. Decrypt and permit flows remain correct without it, since they lazily create the transport key pair when needed. Silently no-ops when no signer is configured or no wallet account is connected yet.

Not for pre-warming a shared transportKeyPairScope — this method's wallet-account precondition doesn't apply to a scope-wide key, and would silently no-op exactly when an operator is most likely calling it (no end-user connected yet). Use permits.warmTransportKeyPairScope instead.

permits.warmTransportKeyPairScope

(scopeId: string) => Promise<void>

Pre-warm the shared transport key pair for a transportKeyPairScope. Storage-only, operator-level action — no wallet account or signer needs to be connected, unlike permits.warmTransportKeyPair().

scopeId must match the configured transportKeyPairScope, guarding against warming the wrong scope by mistake; throws ConfigurationError otherwise.

permits.revokeTransportKeyPair

(scopeId: string) => Promise<void>

Revoke the shared transport key pair for a transportKeyPairScope — the operator-level counterpart to permits.warmTransportKeyPairScope, for use on suspected key compromise. Deletes the shared key pair; every permit in the scope embeds its public key, so they're all treated as stale on next access.

This does not revoke any permit already issued under the key — a permit is a self-contained, bearer-style EIP-712 signature the relayer accepts independently of this call, and one exfiltrated alongside the key remains usable until its own permitTTL expiry regardless of this call. scopeId must match the configured scope; throws ConfigurationError otherwise. Signer-level permits.clear never touches the shared key pair — it only ever wipes the calling signer's own permits.

delegations

sdk.delegations manages on-chain decryption delegation through the ACL contract:

  • delegateDecryption({ contractAddress, delegateAddress, expirationDate? })

  • revokeDelegation({ contractAddress, delegateAddress })

  • isActive({ contractAddress, delegatorAddress, delegateAddress })

  • getExpiry({ contractAddress, delegatorAddress, delegateAddress })

See the Delegations reference for the full API and propagation notes.

offline.prepare

sdk.offline.prepare(request, options?)

Builds an unsigned transaction that the caller signs and broadcasts out-of-process (institutional custody, HSMs). Works without a configured signer.

See the Offline reference for the request kinds and options, and the Offline signing guide for the workflow.

offline.preparePermit

sdk.offline.preparePermit(request)

Builds the unsigned EIP-712 typed data for a decryption permit, without signing it — the offline counterpart to permits.grantPermit. Hand the result to an out-of-process signer, then pass the returned signature to permits.registerPermit. Works without a configured signer.

See the Offline reference for the request/response shape and typed errors, and the Offline signing guide for the workflow.

offline.batchPreparePermits

sdk.offline.batchPreparePermits(request)

preparePermit for any number of contracts: returns one PreparedPermit per 10 contracts, each needing its own signature. Pass the signed pairs to permits.batchRegisterPermits. See the Offline reference.

dispose

() => void

Releases the SDK-owned resources: unsubscribes from signer lifecycle events (disconnect, account change, chain change) and releases the relayer backends' resources (an encrypt worker, if one is running). Work already in flight finishes, and the instance remains usable: a later operation re-acquires what it needs, respawning the encrypt worker on the next encryption.

terminate

() => void

Full cleanup: calls dispose(), then also disposes the signer adapter's own event subscriptions. Call when the SDK is no longer needed. Like dispose(), it leaves the instance usable: a later operation re-acquires what it needs.

Last updated