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

> Create a confidential seed, configure a Token-2022 token account, send confidential transfers, and read decrypted balances from an embedded Solana wallet with the JavaScript SDK.

## Overview

The Token-2022 [confidential transfer extension](https://solana.com/docs/tokens/extensions/confidential-transfer) keeps token balances and transfer amounts encrypted on chain while wallet and token account addresses stay public. A confidential token account holds three balances:

| Balance | On chain | What it holds |
| - | - | - |
| Public balance | Visible | The token's ordinary balance. |
| Pending balance | Encrypted | Funds you deposited or received that you cannot spend yet. |
| Available balance | Encrypted | Funds you can spend confidentially. |

Incoming funds always land in the pending balance. Before you can spend them, you apply the pending balance, which moves it into the available balance.

The `@dynamic-labs-sdk/solana/waas` package builds, signs, and optionally broadcasts each operation for an embedded Solana wallet, and it can decrypt the encrypted balances so your application can display them. Confidential transfers work only with embedded wallets that use V3 MPC. They are not available for external wallets such as Phantom.

## Prerequisites

* An embedded Solana wallet account, and a project environment whose default embedded wallet version is V3.
* SOL in the wallet. The wallet pays the transaction fee, and `configureAccount` also pays the rent to create and grow the token account.
* A Token-2022 mint with the confidential transfer extension enabled. If the mint does not auto-approve new accounts, its confidential transfer authority must approve each token account after `configureAccount`. The SDK does not send that instruction.
* A public balance of the token in the wallet's associated token account before you `deposit`.
* `@solana/web3.js` to derive token account addresses.

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

## Step 1: Get the wallet account and token account

The functions on this page take the embedded Solana `walletAccount`. The example below finds it and derives the wallet's associated token account for your mint.

```typescript theme={"system"}
import { getWalletAccounts } from '@dynamic-labs-sdk/client';
import { isWaasWalletAccount } from '@dynamic-labs-sdk/client/waas';
import { isSolanaWalletAccount } from '@dynamic-labs-sdk/solana';
import { PublicKey } from '@solana/web3.js';

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

const mint = 'YourConfidentialMintAddress';
const decimals = 6;

const walletAccount = getWalletAccounts().find(
  (account) => isSolanaWalletAccount(account) && isWaasWalletAccount({ walletAccount: account })
);

if (!walletAccount || !isSolanaWalletAccount(walletAccount)) {
  throw new Error('No embedded Solana wallet found');
}

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

const tokenAccount = tokenAccountFor(walletAccount.address);
```

By default the SDK uses the RPC endpoint and the chain of the wallet's active network, so you do not pass either. To use a different endpoint, pass `rpcUrl` to the functions that accept it. The cluster behind `rpcUrl` must match the network you intend to use.

## Step 2: Create the confidential seed

Create the confidential seed once for each wallet, before its first confidential operation. The seed is generated inside a secure enclave and stored encrypted, and it never leaves the enclave in plaintext. The function returns the wallet's ElGamal public key and the derivation version.

```typescript theme={"system"}
import { createConfidentialSeed } from '@dynamic-labs-sdk/solana/waas';

const { elgamalPubkey, derivationVersion } = await createConfidentialSeed({ walletAccount });
```

You can create the seed at any time after the wallet exists. Calling it again for a wallet that already has a seed is rejected by the API with a `409` response and the code `confidential_seed_exists`, and the existing seed is left unchanged.

## Step 3: Configure the token account

`configureAccount` enables confidential transfers on the wallet's token account, and it creates the associated token account if it does not exist. Every token account that will send or receive confidential funds must be configured, and only the account's owner can do it: the owner's wallet signs the transaction, and the enclave uses that wallet's own ElGamal key. A sender cannot configure a recipient's account, so each recipient runs `configureAccount` from their own wallet before they can receive a confidential transfer.

The SDK does not check whether the token account is already configured before it builds the transaction. Running `configureAccount` on an account that is already configured is not skipped. Token-2022 rejects it with the error `ExtensionAlreadyInitialized`, the transaction fails, and the account is unchanged. Run `configureAccount` once for each token account, and skip it for an account you have already configured.

```typescript theme={"system"}
import { signConfidentialTransfer } from '@dynamic-labs-sdk/solana/waas';

const { transactionIds } = await signConfidentialTransfer({
  broadcast: true,
  mint,
  operation: 'configureAccount',
  tokenAccount,
  walletAccount,
});
```

## Operations

There are five operations, and each one is a single Solana transaction. Every operation uses the same function with a different `operation`.

| Operation | What it does | Extra parameters |
| - | - | - |
| `configureAccount` | Enables confidential transfers on a token account. Only the account's owner can run it. | 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` |

`amount` is a string in the token's base units, so `'1000000'` is one token when the mint has 6 decimals, and `decimals` must match the mint. `transfer` also accepts an optional `auditorElgamalPubkey` for mints that configure an auditor.

```typescript theme={"system"}
import { signConfidentialTransfer } from '@dynamic-labs-sdk/solana/waas';

const common = { broadcast: true, mint, tokenAccount, walletAccount };

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

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

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

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

Each operation reads the current token account state, so confirm one operation on chain before you start the next. The recipient receives a transfer as a pending balance, so the recipient's wallet must run `applyPendingBalance` before it can transfer or withdraw those funds.

## 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, 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 signs the transaction with the wallet's key share in a single signing session.
4. If you set `broadcast: true`, the SDK submits the transaction.

The result contains `serializedTransactions` with the signed transaction, `signatures`, and `transactionIds` when you broadcast. Broadcasting returns the transaction id without waiting for confirmation, so check that the transaction confirmed before you start the next operation.

Each operation requires one signing approval, so the user may be asked for multi-factor authentication or a step-up before it proceeds, the same as for any other wallet signing action.

> [!WARNING]
>
> The amount of a `transfer` is encrypted on chain, so wallet policies cannot evaluate it. Rules that depend on the transfer amount do not apply to confidential transfers.

## Read decrypted balances

`getConfidentialBalance` decrypts both encrypted balances inside the enclave and returns them as decimal strings in base units.

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

const { availableBalance, pendingBalance } = await getConfidentialBalance({
  mint,
  tokenAccount,
  walletAccount,
});

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

The public balance is not encrypted. Read it from the token account with your Solana connection, for example `connection.getTokenAccountBalance(new PublicKey(tokenAccount))`.

## Sign without broadcasting

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

```typescript theme={"system"}
import { signConfidentialTransfer } from '@dynamic-labs-sdk/solana/waas';

const { serializedTransactions, signatures } = await signConfidentialTransfer({
  mint,
  operation: 'configureAccount',
  tokenAccount,
  walletAccount,
});
```

## Supply account state yourself

By default the SDK fetches the token account state from the RPC endpoint. If you already have it, pass it as `accountState` to `getConfidentialBalance` to skip that request. It has the shape `{ data, lamports, owner }`, where `data` is the base64 account data and `lamports` and `owner` are strings.

## Error handling

```typescript theme={"system"}
import { signConfidentialTransfer } from '@dynamic-labs-sdk/solana/waas';

try {
  await signConfidentialTransfer({ ...common, operation: 'applyPendingBalance' });
} catch (error) {
  console.error(error);
}
```

| Error | Cause and fix |
| - | - |
| `NotWaasWalletAccountError` | The wallet account is not an embedded wallet. Confidential transfers need an embedded Solana wallet. |
| `This embedded wallet is not ready for confidential transfers` | The wallet account has no embedded wallet id yet. Wait until the wallet finishes loading, then retry. |
| `An RPC url is required: pass rpcUrl or switch to a network with an RPC url` | The active network has no RPC endpoint. Pass `rpcUrl`, or switch to a network that has one. |
| `A chain id is required: pass chainId or switch to a network with a genesis hash` | The active network has no genesis hash. Pass `chainId`, or switch to a network that has one. |
| `V3 Embedded Wallets feature is not enabled for this environment` | The environment's default embedded wallet version is not V3. Change it in the developer dashboard. |
| `confidential_seed_exists` | The wallet already has a seed. Skip the seed step and continue with `configureAccount`. |
| `ExtensionAlreadyInitialized` | The token account is already configured. Skip `configureAccount` for it. |

## Next steps

* [Sign and send Solana transactions](https://www.dynamic.xyz/docs/javascript/reference/solana/signing-sending-transactions.md)
* [Solana gas sponsorship](https://www.dynamic.xyz/docs/javascript/reference/solana/svm-gas-sponsorship.md)


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