> ## Documentation Index
> Fetch the complete documentation index at: https://www.dynamic.xyz/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Zama Confidential Tokens

> Shield ERC-20 tokens into Zama confidential wrappers, send confidential transfers, and read encrypted balances from an EVM wallet with the JavaScript SDK.

## Overview

[Zama](https://www.zama.ai/) confidential tokens keep balances and transfer amounts encrypted on chain while wallet addresses stay public. A confidential wrapper token wraps an ordinary ERC-20: you shield tokens into the wrapper, transfer them without revealing the amount, and decrypt balances only for the wallet's owner.

The `@dynamic-labs-sdk/zama` package runs each operation for a connected EVM wallet. Every helper creates a fresh Zama runtime bound to the wallet's active network, verifies the chain and RPC endpoint, stores decryption credentials in memory only, and clears them before it returns. You do not configure the Zama SDK or manage decryption permits yourself.

## Prerequisites

* A connected EVM wallet account, embedded or external. Embedded wallets are [MPC-backed](https://www.dynamic.xyz/docs/embedded-wallets/mpc/overview.md).
* A network with a Zama deployment, selected as the wallet's active network. The deployments ship with `@zama-fhe/sdk`, so the supported list depends on the installed version; an unsupported chain throws `ZamaUnsupportedChainError`.
* An HTTPS RPC endpoint on the active network. The package reads the endpoint from Dynamic's network configuration, and an insecure or missing endpoint throws `ZamaInsecureRpcError`.
* The confidential wrapper token's contract address, and a public balance of its underlying ERC-20 before you shield.
* `viem` for the `Address` type.

```bash theme={"system"}
npm install @dynamic-labs-sdk/zama viem
```

## Step 1: Get the wallet account

Each helper takes the connected EVM `walletAccount`. The example below finds it from the Dynamic client.

```typescript theme={"system"}
import { getWalletAccounts } from '@dynamic-labs-sdk/client';
import { isEvmWalletAccount } from '@dynamic-labs-sdk/evm';

const walletAccount = getWalletAccounts().find((account) => isEvmWalletAccount(account));

if (!walletAccount || !isEvmWalletAccount(walletAccount)) {
  throw new Error('No EVM wallet found');
}

const tokenAddress = '0xYourConfidentialWrapperTokenAddress';
```

## Step 2: Shield tokens

`shieldConfidentialToken` moves an underlying ERC-20 balance into its confidential wrapper. Pass a human-readable amount such as `'1.5'`; the helper converts it using the underlying token's decimals, which it reads from the ERC-20 contract unless you pass `decimals`. A `bigint` amount is treated as base units and used unchanged.

The helper submits an exact approval when the wrapper needs one, submits the shield transaction, waits for confirmation, and returns the transaction hashes.

```typescript theme={"system"}
import { shieldConfidentialToken } from '@dynamic-labs-sdk/zama';

const result = await shieldConfidentialToken({
  amount: '1.5',
  tokenAddress,
  walletAccount,
});

console.log('shielded in', result.transactionHash);
if (result.approvalTransactionHash) {
  console.log('approved in', result.approvalTransactionHash);
}
```

`result.amount` is the shielded amount in base units. An amount that is not positive, is not a decimal string, or carries nonzero fractional digits beyond the token's decimals throws `ZamaInvalidAmountError` before anything is sent.

## Step 3: Transfer confidential tokens

`transferConfidentialToken` sends wrapper tokens to another address. The amount is encrypted before submission, so neither the amount nor either balance is revealed on chain.

```typescript theme={"system"}
import { transferConfidentialToken } from '@dynamic-labs-sdk/zama';

const result = await transferConfidentialToken({
  amount: '0.25',
  recipient: '0xRecipientAddress',
  tokenAddress,
  walletAccount,
});

console.log('transferred in', result.transactionHash);
```

The amount follows the same rules as shielding, with decimals read from the confidential token contract unless you pass `decimals`. An invalid or zero recipient address throws `ZamaInvalidRecipientError`.

## Step 4: Read the balance

`getConfidentialBalance` reads the wallet's encrypted balance without asking for a decryption permit. It returns `{ status: 'empty' }` when there is nothing to decrypt, or `{ status: 'encrypted', encryptedValue }` with the onchain ciphertext handle.

```typescript theme={"system"}
import { getConfidentialBalance } from '@dynamic-labs-sdk/zama';

const balance = await getConfidentialBalance({ tokenAddress, walletAccount });

if (balance.status === 'encrypted') {
  console.log('encrypted balance handle', balance.encryptedValue);
}
```

`revealConfidentialBalance` goes further: it grants a scoped decryption permit, decrypts the balance, and clears the credentials before returning. A `revealed` result carries the balance in token base units.

```typescript theme={"system"}
import { revealConfidentialBalance } from '@dynamic-labs-sdk/zama';

const balance = await revealConfidentialBalance({ tokenAddress, walletAccount });

if (balance.status === 'revealed') {
  console.log('balance', balance.value);
}
```

Decrypted values are returned to your application and are never stored by the package. Display them only while the wallet context is valid, and hide them when the wallet changes or disconnects.

## Cancellation

Every helper accepts an optional `signal` of type `AbortSignal`. Aborting it stops the operation and rethrows the signal's abort reason.

```typescript theme={"system"}
const controller = new AbortController();
const pending = transferConfidentialToken({
  amount: '0.25',
  recipient: '0xRecipientAddress',
  signal: controller.signal,
  tokenAddress,
  walletAccount,
});

controller.abort();
await pending; // throws the abort reason
```

## Error handling

Each failure the package detects throws its own error class, so you can handle cases with `instanceof`. Errors raised by the wallet, the network, or the Zama SDK, such as a rejected signature, propagate unchanged.

```typescript theme={"system"}
import {
  ZamaContextChangedError,
  ZamaUnsupportedChainError,
} from '@dynamic-labs-sdk/zama';

try {
  await revealConfidentialBalance({ tokenAddress, walletAccount });
} catch (error) {
  if (error instanceof ZamaContextChangedError) {
    // The wallet or network changed mid-operation; discard the result.
  } else if (error instanceof ZamaUnsupportedChainError) {
    // Ask the user to switch to a network Zama supports.
  }
}
```

| Error | Cause |
| - | - |
| `ZamaUnsupportedChainError` | The wallet's chain has no Zama deployment. Switch to a supported network. |
| `ZamaNetworkMismatchError` | The wallet's active Dynamic network does not match the wallet client's chain. |
| `ZamaInsecureRpcError` | The active network's RPC endpoint is missing or is not HTTPS. |
| `ZamaRpcMismatchError` | The configured RPC endpoint reports a different chain ID than the wallet. |
| `ZamaInvalidAmountError` | The amount is not a positive decimal string or has too many fractional digits. |
| `ZamaInvalidRecipientError` | The recipient is not a valid, non-zero EVM address. |
| `ZamaInvalidDecryptionError` | The relayer returned a balance that could not be decrypted. |
| `ZamaContextChangedError` | The wallet or network changed mid-operation. A submitted shield or transfer can still confirm, so check the onchain state before retrying. |
| `ZamaTransactionReplacedError` | The transaction was replaced or cancelled before it confirmed. |
| `ZamaTransactionRevertedError` | The transaction reverted on chain. |

## Direct Zama SDK access

`createZamaWalletClient` and `onZamaWalletContextInvalidated` stay available for integrations that call the official Zama SDK directly. Most applications should use the managed helpers above.

`createZamaWalletClient` returns a viem `WalletClient` for the wallet account that normalizes typed-data domain chain IDs before signing, which Zama's viem adapter requires. Recreate it when the wallet or network changes.

`onZamaWalletContextInvalidated` calls `onInvalidated` once when the wallet context goes stale: logout, wallet removal, provider replacement, or a network change, including switches made through Dynamic. The callback must make the confidential session unusable, hide decrypted data, and arrange permit cleanup. The returned function removes the listeners without triggering the callback.

```typescript theme={"system"}
import {
  createZamaWalletClient,
  onZamaWalletContextInvalidated,
} from '@dynamic-labs-sdk/zama';

const walletClient = await createZamaWalletClient({ walletAccount });
let sessionActive = true;

const removeListeners = await onZamaWalletContextInvalidated({
  networkId: String(walletClient.chain.id),
  onInvalidated: () => {
    sessionActive = false;
    hideDecryptedBalance();
  },
  walletAccount,
});

// Pass walletClient to createConfig from '@zama-fhe/sdk/viem'.
// Discard results from Zama calls that settle after sessionActive flips to false.
// Call removeListeners() when the session ends normally.
```

## Next steps

* [Sign an EVM transaction](https://www.dynamic.xyz/docs/javascript/reference/evm/sign-transaction.md)
* [Getting the viem wallet client](https://www.dynamic.xyz/docs/javascript/reference/evm/getting-viem-wallet-client.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.