> ## 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.

# Confidential Transfers

> Configure token accounts, move tokens between public and confidential balances, and send Token-2022 confidential transfers from a Solana wallet using Dynamic's Node SDK

## Overview

The Token-2022 confidential transfer extension keeps token balances and transfer amounts encrypted on chain while addresses stay public. A confidential token account holds a public balance and two encrypted balances: a pending balance that receives incoming funds, and an available balance that you can spend. `DynamicSvmWalletClient` builds, signs, and optionally broadcasts each operation for a Dynamic wallet, and it can decrypt the encrypted balances so your application can display them.

There are five operations, and each one is a single Solana transaction.

| Operation | What it does | Extra parameters |
| - | - | - |
| `configureAccount` | Enables confidential transfers on a token account. | None |
| `deposit` | Moves tokens from the public balance into the pending balance. | `amount`, `decimals` |
| `applyPendingBalance` | Moves the pending balance into the available balance. | None |
| `transfer` | Sends tokens from the available balance to another confidential token account, which receives them as pending. | `amount`, `decimals`, `destinationTokenAccount` |
| `withdraw` | Moves tokens from the available balance back to the public balance. | `amount`, `decimals` |

Amounts are strings in the token's base units, so `'1000000'` is one token when the mint has 6 decimals.

## How signing works

Each call to `signConfidentialTransfer` runs the same sequence:

1. The SDK reads the token account state and the latest blockhash from the RPC endpoint you provide, because the secure enclave that builds the transaction cannot reach the network.
2. The enclave builds one unsigned transaction containing the confidential instruction and its zero-knowledge proofs, using the wallet's confidential seed.
3. The SDK checks the transaction before signing. It refuses to sign unless the transaction is a version 1 transaction, uses only the Token-2022, associated token account, System, ZK ElGamal Proof, and Compute Budget programs, has the wallet as its only signer and fee payer, and contains exactly one confidential instruction that matches the operation, mint, token account, destination, amount, and decimals you passed.
4. The SDK signs the transaction with the wallet's key share in a single signing session.
5. If you set `broadcast: true`, the SDK submits the transaction and waits for the `confirmed` commitment level.

The result contains `serializedTransactions` with the signed transaction as base64, `signatures` with its base58 signature, and `transactionIds` when you broadcast.

## Prerequisites

* [A Solana wallet](https://www.dynamic.xyz/docs/node/svm/create-wallet.md) funded with SOL for network fees.
* A Token-2022 mint with the confidential transfer extension enabled.
* An associated token account for that mint, owned by each wallet that takes part. Your application creates these accounts. The SDK does not.
* `@solana/web3.js` installed to derive token account addresses.

```bash theme={"system"}
npm install @solana/web3.js
```

## Step 1: Set up the client

```typescript theme={"system"}
import { DynamicSvmWalletClient } from '@dynamic-labs-wallet/node-svm';

const client = new DynamicSvmWalletClient({
  environmentId: process.env.DYNAMIC_ENVIRONMENT_ID!,
});
await client.authenticateApiToken(process.env.DYNAMIC_AUTH_TOKEN!);
```

The examples that follow use these values. Replace them with your own.

```typescript theme={"system"}
import { PublicKey } from '@solana/web3.js';

const TOKEN_2022 = new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
const ASSOCIATED_TOKEN = new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');

const rpcUrl = 'https://api.devnet.solana.com';
const chainId = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1'; // devnet
const mint = 'YourConfidentialMintAddress';
const decimals = 6;

// Application-supplied: returns the walletMetadata you persisted when you created the wallet.
const walletMetadata = await loadWalletMetadata();
const { walletId, accountAddress } = walletMetadata;
const recipientAddress = 'RecipientWalletAddress';

const tokenAccountFor = (owner: string) =>
  PublicKey.findProgramAddressSync(
    [new PublicKey(owner).toBuffer(), TOKEN_2022.toBuffer(), new PublicKey(mint).toBuffer()],
    ASSOCIATED_TOKEN
  )[0].toBase58();

const tokenAccount = tokenAccountFor(accountAddress);
```

`walletMetadata` is the value `createWalletAccount` returned when you created the wallet. Load it from the cache where you [stored the wallet information](https://www.dynamic.xyz/docs/node/svm/create-wallet.md#step-4-store-wallet-information-securely). `signConfidentialTransfer` requires it and checks that its `walletId` and `accountAddress` match the `walletId` and `solanaAddress` in the call.

> [!WARNING]
>
> `chainId` defaults to Solana mainnet (`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`). The cluster in `chainId` must match the cluster behind `rpcUrl`. Devnet is `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`.

`rpcUrl` must use `https`. The SDK accepts `http` only for `localhost`, `127.0.0.1`, and `[::1]`.

## Step 2: Create the confidential seed

Create the confidential seed once for each wallet, before its first confidential operation. The enclave generates the seed and stores it encrypted. The method returns the wallet's ElGamal public key and the derivation version.

```typescript theme={"system"}
const { elgamalPubkey, derivationVersion } = await client.createConfidentialSeed({
  walletId,
  solanaAddress: accountAddress,
});
```

## Step 3: Configure the token account

`configureAccount` enables confidential transfers on the wallet's token account. Run it for every token account that will send or receive confidential funds, including the recipient's.

```typescript theme={"system"}
const { transactionIds } = await client.signConfidentialTransfer({
  walletId,
  walletMetadata,
  operation: 'configureAccount',
  solanaAddress: accountAddress,
  mint,
  tokenAccount,
  chainId,
  rpcUrl,
  password: 'your-secure-password',
  broadcast: true,
});
```

Pass the `password` you set when you created the wallet. If you hold the wallet's `externalServerKeyShares` yourself, pass them as `externalServerKeyShares` together with the password instead of letting the SDK recover the shares.

## Step 4: Deposit, apply, transfer, and withdraw

Every operation uses the same call with a different `operation`. The wallet must hold a public balance of the token before it can deposit.

```typescript theme={"system"}
const common = {
  walletId,
  walletMetadata,
  solanaAddress: accountAddress,
  mint,
  tokenAccount,
  chainId,
  rpcUrl,
  password: 'your-secure-password',
  broadcast: true,
};

// Public balance to pending balance
await client.signConfidentialTransfer({
  ...common,
  operation: 'deposit',
  amount: '40000000',
  decimals,
});

// Pending balance to available balance
await client.signConfidentialTransfer({ ...common, operation: 'applyPendingBalance' });

// Available balance to another confidential token account
await client.signConfidentialTransfer({
  ...common,
  operation: 'transfer',
  amount: '10000000',
  decimals,
  destinationTokenAccount: tokenAccountFor(recipientAddress),
});

// Available balance back to the public balance
await client.signConfidentialTransfer({
  ...common,
  operation: 'withdraw',
  amount: '10000000',
  decimals,
});
```

Each operation reads the current token account state, so wait for one operation to confirm before you start the next. With `broadcast: true` the call returns only after the transaction reaches the `confirmed` commitment level.

The recipient receives a transfer as a pending balance. The recipient's wallet must run `applyPendingBalance` before it can transfer or withdraw those funds.

## Read decrypted balances

`getConfidentialBalance` decrypts both encrypted balances inside the enclave and returns them as decimal strings in base units. It reads the token account at the `confirmed` commitment level, so the result includes any operation you have already confirmed.

```typescript theme={"system"}
const { availableBalance, pendingBalance } = await client.getConfidentialBalance({
  walletId,
  solanaAddress: accountAddress,
  mint,
  tokenAccount,
  rpcUrl,
});

console.log(`Available: ${availableBalance}, pending: ${pendingBalance}`);
```

The public balance is not encrypted. Read it with `connection.getTokenAccountBalance(new PublicKey(tokenAccount), 'confirmed')`.

## Sign without broadcasting

Leave out `broadcast` to get the signed transaction back without submitting it. Submit it yourself, and wait for confirmation before the next operation.

```typescript theme={"system"}
const { serializedTransactions, signatures } = await client.signConfidentialTransfer({
  ...common,
  broadcast: false,
  operation: 'configureAccount',
});
```

## Supply account state yourself

By default the SDK fetches account state and the blockhash from `rpcUrl`. If you already have them, pass `accountState`, `destinationAccountState`, `recentBlockhash`, and `lastValidBlockHeight` and omit `rpcUrl`. A call that broadcasts still needs `rpcUrl`. `accountState` has the shape `{ data, lamports, owner }`, where `data` is the base64 account data and `lamports` and `owner` are strings.

## Error handling

```typescript theme={"system"}
try {
  await client.signConfidentialTransfer({ ...common, operation: 'applyPendingBalance' });
} catch (error) {
  console.error(error);
}
```

| Error | Cause and fix |
| - | - |
| `signConfidentialTransfer requires rpcUrl to fetch account state, blockhash, or broadcast` | The call needs data from the network. Pass `rpcUrl`, or pass every value the operation reads. |
| `getConfidentialBalance requires rpcUrl or accountState` | Pass `rpcUrl` or an `accountState`. |
| `Unsupported rpcUrl protocol` | Use an `https` endpoint. |
| `Refusing to sign confidential transaction: ...` | The transaction the enclave built does not match the request. Check `mint`, `tokenAccount`, `amount`, and `decimals`. |
| `walletId and solanaAddress must match walletMetadata` | Pass the `walletMetadata` that belongs to the `walletId` and `solanaAddress` in the call. |

## Next steps

* [Sign SVM transactions](https://www.dynamic.xyz/docs/node/svm/sign-transactions.md)
* [Create a Solana wallet](https://www.dynamic.xyz/docs/node/svm/create-wallet.md)


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