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

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Run it from your machine

> Create the restricted asset from your terminal on Surfpool or devnet, approve holders, and test the blocked transfer, pause, and recovery yourself.

<div className="sol-stepper not-prose" data-path="issue-asset">
<div className="sol-stepper-nav" role="navigation" aria-label="Issue an asset · ~45 min">
<ol>
<li data-state="done"><a href="/developers/docs/assets/issue-asset/try-it"><span className="sol-stepper-n">Step 1<span className="sol-vh">, </span><span className="sol-stepper-done">Done</span><span className="sol-vh">: </span></span><span className="sol-stepper-t">Hold a restricted asset</span></a></li>
<li data-state="done"><a href="/developers/docs/assets/issue-asset/browser"><span className="sol-stepper-n">Step 2<span className="sol-vh">, </span><span className="sol-stepper-done">Done</span><span className="sol-vh">: </span></span><span className="sol-stepper-t">Read the code</span></a></li>
<li data-state="current"><a href="/developers/docs/assets/issue-asset/local" aria-current="step"><span className="sol-stepper-n">Step 3<span className="sol-vh">: </span></span><span className="sol-stepper-t">Run it from your machine</span></a></li>
<li data-state="todo"><a href="/developers/docs/assets/issue-asset/go-live"><span className="sol-stepper-n">Step 4<span className="sol-vh">: </span></span><span className="sol-stepper-t">Go live</span></a></li>
</ol>
</div>
</div>

This step puts the code from the first two steps into a project of your own,
in five files: a connection helper, the asset, holder approval, the transfers
that test the rules, and a script that runs them in order. An optional
confidential variant at the end adds two more. The output under each block is
from a local Surfpool network.

## 1. Create the project and install the packages

You need Node.js 20.18 or later. The scripts use top-level `await` and
`import.meta.url`, so `package.json` needs `"type": "module"`, which the second
command sets. The examples are tested with `@solana/kit` 8.4,
`@solana-program/token-2022` 0.19, and `@solana-program/system` 0.15.

```bash Terminal
mkdir issue-asset && cd issue-asset
npm init -y && npm pkg set type=module
npm install @solana/kit @solana-program/token-2022 @solana-program/system
npm install --save-dev tsx
```

## 2. Pick a network

The code reads the network from two environment variables and uses devnet when
they are unset.

- **Local:** install the [Surfpool CLI](/developers/docs/tools/surfpool/toolchain/getting-started)
  and run `surfpool start`. Then set `RPC_URL=http://127.0.0.1:8899` and
  `RPC_SUBSCRIPTIONS_URL=ws://127.0.0.1:8900`. This is where the output on these
  pages comes from.
- **Devnet:** leave both unset. Fund your issuer wallet (step 7 creates its key
  file) with free devnet SOL from the [Solana Faucet](https://faucet.solana.com/)
  to pay fees and account deposits.

<div className="sol-concept not-prose">
[<span className="sol-concept-name">RPC</span> <span className="sol-concept-def">RPC is the HTTP/JSON API your code uses to read from and send to the network.</span>](/developers/docs/rpc)
</div>

## 3. Add the connection helper

`send` builds a transaction from a list of instructions, signs it, sends it, and
waits until it's confirmed. On failure it keeps the signature and message on
the error, so you can look up the transaction and decode its program error.

```ts config.ts
import {
  appendTransactionMessageInstructions,
  assertIsTransactionWithBlockhashLifetime,
  createSolanaRpc,
  createSolanaRpcSubscriptions,
  createTransactionMessage,
  getSignatureFromTransaction,
  pipe,
  sendAndConfirmTransactionFactory,
  setTransactionMessageFeePayerSigner,
  setTransactionMessageLifetimeUsingBlockhash,
  signTransactionMessageWithSigners,
  type Instruction,
  type Signature,
  type TransactionSigner,
} from "@solana/kit";

export const RPC_URL = process.env.RPC_URL ?? "https://api.devnet.solana.com";
export const RPC_SUBSCRIPTIONS_URL =
  process.env.RPC_SUBSCRIPTIONS_URL ?? "wss://api.devnet.solana.com";

export const rpc = createSolanaRpc(RPC_URL);
const rpcSubscriptions = createSolanaRpcSubscriptions(RPC_SUBSCRIPTIONS_URL);
const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({
  rpc,
  rpcSubscriptions,
});

/** Build, sign, send and confirm one transaction; returns its signature. */
export async function send(
  feePayer: TransactionSigner,
  instructions: Instruction[],
  options: { skipPreflight?: boolean } = {},
) {
  const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
  const message = pipe(
    createTransactionMessage({ version: 0 }),
    (m) => setTransactionMessageFeePayerSigner(feePayer, m),
    (m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
    (m) => appendTransactionMessageInstructions(instructions, m),
  );
  const transaction = await signTransactionMessageWithSigners(message);
  assertIsTransactionWithBlockhashLifetime(transaction);
  const signature = getSignatureFromTransaction(transaction);
  try {
    await sendAndConfirmTransaction(transaction, {
      commitment: "confirmed",
      skipPreflight: options.skipPreflight,
    });
  } catch (error) {
    // Keep the signature (a skipPreflight failure still landed onchain) and
    // the message (to decode program errors) on the error.
    throw Object.assign(error as object, {
      signature,
      transactionMessage: message,
    });
  }
  return signature;
}

/** The network fee a confirmed transaction paid, in lamports. */
export async function fee(signature: Signature) {
  const tx = await rpc
    .getTransaction(signature, {
      commitment: "confirmed",
      encoding: "json",
      maxSupportedTransactionVersion: 0,
    })
    .send();
  return tx?.meta?.fee ?? 0n;
}
```

## 4. Create the asset

Save this as `create-asset.ts`. It's the code from the previous step.

```ts create-asset.ts
import {
  generateKeyPairSigner,
  type Address,
  type Signature,
  type TransactionSigner,
} from "@solana/kit";
import { getCreateAccountInstruction } from "@solana-program/system";
import {
  AccountState,
  extension,
  fetchMint,
  getInitializeMintInstruction,
  getMintSize,
  getPostInitializeInstructionsForMintExtensions,
  getPreInitializeInstructionsForMintExtensions,
  TOKEN_2022_PROGRAM_ADDRESS,
} from "@solana-program/token-2022";
import { fee, rpc, send } from "./config";

/**
 * A restricted asset: onchain metadata, transfers the issuer can pause, a
 * permanent delegate (the issuer can move or burn any balance, e.g. to
 * enforce a court order) and token accounts that start FROZEN, so only
 * holders the issuer approves (thaws) can receive it.
 */
export async function createAsset(
  issuer: TransactionSigner,
): Promise<{ mint: Address; signature: Signature; extensions: string[] }> {
  const mint = await generateKeyPairSigner();
  const extensions = [
    extension("MetadataPointer", {
      authority: issuer.address,
      metadataAddress: mint.address,
    }),
    extension("TokenMetadata", {
      updateAuthority: issuer.address,
      mint: mint.address,
      name: "Lisbon Solar Fund",
      symbol: "LSF",
      uri: "https://example.com/lsf.json",
      additionalMetadata: new Map([["isin", "PTLSF0000001"]]),
    }),
    extension("PausableConfig", { authority: issuer.address, paused: false }),
    extension("PermanentDelegate", { delegate: issuer.address }),
    extension("DefaultAccountState", { state: AccountState.Frozen }),
  ];

  // Metadata is written after the mint is initialized: allocate without it,
  // but fund rent for the final size.
  const space = getMintSize(
    extensions.filter((e) => e.__kind !== "TokenMetadata"),
  );
  const rent = await rpc
    .getMinimumBalanceForRentExemption(BigInt(getMintSize(extensions)))
    .send();

  const signature = await send(issuer, [
    getCreateAccountInstruction({
      payer: issuer,
      newAccount: mint,
      lamports: rent,
      space,
      programAddress: TOKEN_2022_PROGRAM_ADDRESS,
    }),
    ...getPreInitializeInstructionsForMintExtensions(mint.address, extensions),
    getInitializeMintInstruction({
      mint: mint.address,
      decimals: 6,
      mintAuthority: issuer.address,
      freezeAuthority: issuer.address,
    }),
    ...getPostInitializeInstructionsForMintExtensions(
      mint.address,
      issuer,
      extensions,
    ),
  ]);

  const account = await fetchMint(rpc, mint.address);
  const enabled =
    account.data.extensions.__option === "Some"
      ? account.data.extensions.value.map((e) => e.__kind)
      : [];
  console.log("Mint:", mint.address);
  console.log("Extensions:", enabled.join(", "));
  console.log("Signature:", signature);
  console.log("Fee:", String(await fee(signature)), "lamports");
  return { mint: mint.address, signature, extensions: enabled };
}
```

<div className="sol-term not-prose" data-term="paths/assets/issue-asset/create" data-tab="create-asset.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Output of createAsset(issuer)</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Output of createAsset(issuer): Output">
<div className="sol-term-step" data-step="1" data-pending="tx">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await createAsset(issuer)</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Mint\:</span> <span className="sol-h" title="HZum3YzcFTMWDGAQWBYMLDUACtLcxc1pF67doKooqYzY"><span className="sol-h-f">HZum3YzcFTMWDGAQWBYMLDUACtLcxc1pF67doKooqYzY</span><span className="sol-h-s" aria-hidden="true">HZum…qYzY</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Extensions\:</span> MetadataPointer, PausableConfig, PermanentDelegate, DefaultAccountState, TokenMetadata</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="5AJfoLZSwWu7J568eoPPj9NFoGAzYDAS6uBD7zb4bb6E7dNbDRPYdxX6s8hZEo9qqeTpihA9zg6P9sGneEXURiL4"><span className="sol-h-f">5AJfoLZSwWu7J568eoPPj9NFoGAzYDAS6uBD7zb4bb6E7dNbDRPYdxX6s8hZEo9qqeTpihA9zg6P9sGneEXURiL4</span><span className="sol-h-s" aria-hidden="true">5AJf…RiL4</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Fee\:</span> 10000 lamports</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="ok">Confirmed</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

Creating the mint costs the network fee plus a refundable deposit for the mint
account's storage. The fee was 10,000 lamports, for two signatures: the issuer
and the new mint account.

<div className="sol-concept not-prose">
[<span className="sol-concept-name">Rent (storage deposit)</span> <span className="sol-concept-def">Every account holds a small refundable deposit for the space it takes up.</span>](/developers/docs/core/rent)
</div>

## 5. Approve holders

Save this as `approve-holder.ts`. `openAccount` creates a holder's token
account, which starts frozen. `approveHolder` thaws it with the freeze authority
and, when you pass an amount, mints LSF to it in the same transaction. Amounts
are in base units: with 6 decimals, `1_000_000_000n` is 1000 LSF.

```ts approve-holder.ts
import type { Address, TransactionSigner } from "@solana/kit";
import {
  AccountState,
  fetchToken,
  findAssociatedTokenPda,
  getCreateAssociatedTokenIdempotentInstruction,
  getMintToCheckedInstruction,
  getThawAccountInstruction,
  TOKEN_2022_PROGRAM_ADDRESS,
} from "@solana-program/token-2022";
import { rpc, send } from "./config";

/** Base units as LSF (6 decimals), for printing. */
export const lsf = (amount: bigint) => `${Number(amount) / 1e6} LSF`;

export async function tokenAccountOf(owner: Address, mint: Address) {
  const [ata] = await findAssociatedTokenPda({
    owner,
    mint,
    tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
  });
  return ata;
}

/** Open a holder's token account. With DefaultAccountState it starts frozen. */
export async function openAccount(
  issuer: TransactionSigner,
  mint: Address,
  owner: Address,
) {
  const account = await tokenAccountOf(owner, mint);
  await send(issuer, [
    getCreateAssociatedTokenIdempotentInstruction({
      payer: issuer,
      ata: account,
      owner,
      mint,
      tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
    }),
  ]);
  const { data } = await fetchToken(rpc, account);
  const state = AccountState[data.state];
  console.log("Opened", account, "state:", state);
  return { account, state };
}

/**
 * Approve a holder (after your KYC check): thaw their account with the
 * freeze authority, then optionally issue them `amount` base units.
 */
export async function approveHolder(
  issuer: TransactionSigner,
  mint: Address,
  owner: Address,
  amount = 0n,
) {
  const account = await tokenAccountOf(owner, mint);
  const signature = await send(issuer, [
    getThawAccountInstruction({ account, mint, owner: issuer }),
    ...(amount > 0n
      ? [
          getMintToCheckedInstruction({
            mint,
            token: account,
            mintAuthority: issuer,
            amount,
            decimals: 6,
          }),
        ]
      : []),
  ]);
  const { data } = await fetchToken(rpc, account);
  const state = AccountState[data.state];
  console.log(
    "Approved",
    account,
    "state:",
    state,
    "balance:",
    lsf(data.amount),
  );
  console.log("Signature:", signature);
  return { account, signature, state, balance: data.amount };
}
```

<div className="sol-term not-prose" data-term="paths/assets/issue-asset/approve" data-tab="approve-holder.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Approving a holder with 1,000 LSF and a second holder with none</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Approving a holder with 1,000 LSF and a second holder with none: Output">
<div className="sol-term-step" data-step="1" data-pending="tx">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await openAccount(issuer, mint, holder.address)</div>
<div className="sol-term-row sol-term-ln">Opened <span className="sol-h" title="JAg5yGYw5Be2J54jk9s7ZUxhtU2FXN8txfpjxPctaeqx"><span className="sol-h-f">JAg5yGYw5Be2J54jk9s7ZUxhtU2FXN8txfpjxPctaeqx</span><span className="sol-h-s" aria-hidden="true">JAg5…aeqx</span></span> <span className="sol-term-k">state\:</span> Frozen</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await approveHolder(issuer, mint, holder.address, 1\_000\_000\_000n)</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Approved <span className="sol-h" title="JAg5yGYw5Be2J54jk9s7ZUxhtU2FXN8txfpjxPctaeqx"><span className="sol-h-f">JAg5yGYw5Be2J54jk9s7ZUxhtU2FXN8txfpjxPctaeqx</span><span className="sol-h-s" aria-hidden="true">JAg5…aeqx</span></span> <span className="sol-term-k">state\:</span> Initialized <span className="sol-term-k">balance\:</span> 1000 LSF</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="2cTiGJS6oWQFZ8XG4gTXqHz6RiywDvCYRzbprNrPfop8AacwZQCWC4ExL4UNQxK3XYF3LfakaqHPWN9RJQUiQexW"><span className="sol-h-f">2cTiGJS6oWQFZ8XG4gTXqHz6RiywDvCYRzbprNrPfop8AacwZQCWC4ExL4UNQxK3XYF3LfakaqHPWN9RJQUiQexW</span><span className="sol-h-s" aria-hidden="true">2cTi…QexW</span></span></div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await openAccount(issuer, mint, approved.address)</div>
<div className="sol-term-row sol-term-ln">Opened <span className="sol-h" title="CpvfwkairbnMrGqdW9wxMSiFgsHxi7666Gu4j7vCdjDv"><span className="sol-h-f">CpvfwkairbnMrGqdW9wxMSiFgsHxi7666Gu4j7vCdjDv</span><span className="sol-h-s" aria-hidden="true">Cpvf…djDv</span></span> <span className="sol-term-k">state\:</span> Frozen</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await approveHolder(issuer, mint, approved.address, 0n)</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Approved <span className="sol-h" title="CpvfwkairbnMrGqdW9wxMSiFgsHxi7666Gu4j7vCdjDv"><span className="sol-h-f">CpvfwkairbnMrGqdW9wxMSiFgsHxi7666Gu4j7vCdjDv</span><span className="sol-h-s" aria-hidden="true">Cpvf…djDv</span></span> <span className="sol-term-k">state\:</span> Initialized <span className="sol-term-k">balance\:</span> 0 LSF</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="5bjv6TA5KoJ8v61sPZ4Vuf3U8qRoryzTcEGqDShtfGLjxq7zaMn3vxf69QJwbPAxrEFu1tyzPNjw5RLf9ebzRcFa"><span className="sol-h-f">5bjv6TA5KoJ8v61sPZ4Vuf3U8qRoryzTcEGqDShtfGLjxq7zaMn3vxf69QJwbPAxrEFu1tyzPNjw5RLf9ebzRcFa</span><span className="sol-h-s" aria-hidden="true">5bjv…RcFa</span></span></div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="ok">Opened and approved · 4 transactions</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

Call `approveHolder` only after your KYC check passes. To approve addresses from
an allowlist automatically, use [Token ACL](/developers/docs/tokenization/token-acl). To
withdraw an approval, freeze the account again with the freeze authority.

## 6. Test the rules

Save this as `blocked-transfer.ts`. It holds the transfers and controls from
step 1:

- `transfer` sends LSF between holders with `TransferChecked`.
- `sendToUnapproved` sends to a frozen account with `skipPreflight`, so the
  failed transaction lands and you can read its error, log, and fee with
  `failure`. The error holds `bigint` values, which `JSON.stringify` can't
  print as they are, so it converts them first.
- `sendToUnapprovedWithPreflight` sends the same transfer normally and decodes
  the rejection with `isToken2022Error(…, TOKEN_2022_ERROR__ACCOUNT_FROZEN)`.
- `pause` and `resume` switch every transfer of the asset off and on.
- `clawBack` uses the permanent delegate to move tokens out of a holder's account
  into the issuer's.

```ts blocked-transfer.ts
import {
  isSolanaError,
  type Address,
  type Signature,
  type TransactionSigner,
} from "@solana/kit";
import {
  getPauseInstruction,
  getResumeInstruction,
  getTransferCheckedInstruction,
  isToken2022Error,
  TOKEN_2022_ERROR__ACCOUNT_FROZEN,
} from "@solana-program/token-2022";
import { rpc, send } from "./config";
import { lsf, tokenAccountOf } from "./approve-holder";

export async function transfer(
  from: TransactionSigner,
  mint: Address,
  to: Address,
  amount: bigint,
  options: { skipPreflight?: boolean; feePayer?: TransactionSigner } = {},
) {
  try {
    const signature = await send(
      options.feePayer ?? from,
      [
        getTransferCheckedInstruction({
          source: await tokenAccountOf(from.address, mint),
          mint,
          destination: await tokenAccountOf(to, mint),
          authority: from,
          amount,
          decimals: 6,
        }),
      ],
      options,
    );
    console.log(`Transfer ${lsf(amount)}: confirmed`);
    console.log("Signature:", signature);
    return signature;
  } catch (error) {
    // With preflight, the RPC node simulates the transfer and rejects it with
    // the program's error. With skipPreflight, it lands and fails onchain.
    const cause = isSolanaError(error) ? error.cause : undefined;
    console.log(
      `Transfer ${lsf(amount)}:`,
      options.skipPreflight
        ? "failed onchain"
        : `rejected: ${((cause ?? error) as Error).message}`,
    );
    throw error;
  }
}

/** What a failed transaction did onchain: its error, the program log and the fee. */
export async function failure(signature: Signature) {
  const tx = await rpc
    .getTransaction(signature, {
      commitment: "confirmed",
      encoding: "json",
      maxSupportedTransactionVersion: 0,
    })
    .send();
  return {
    err: tx?.meta?.err,
    log: tx?.meta?.logMessages?.find((l) => l.includes("Error")),
    fee: tx?.meta?.fee,
  };
}

/**
 * A transfer to an account the issuer has not approved fails with Token-2022
 * `AccountFrozen` (custom error 17). Sent with `skipPreflight`, it still lands
 * as a failed transaction and the sender still pays the fee.
 */
export async function sendToUnapproved(
  holder: TransactionSigner,
  mint: Address,
  unapproved: Address,
) {
  try {
    await transfer(holder, mint, unapproved, 1_000_000n, {
      skipPreflight: true,
    });
    throw new Error("expected the transfer to fail");
  } catch (error) {
    const signature = (error as { signature?: Signature }).signature;
    if (!signature) throw error;
    const failed = { signature, ...(await failure(signature)) };
    // `err` holds bigints, which JSON.stringify can't print as they are.
    const json = JSON.stringify(failed.err, (_k, v) =>
      typeof v === "bigint" ? Number(v) : v,
    );
    console.log("Failed signature:", signature);
    console.log("  err:", json);
    console.log("  log:", failed.log);
    console.log("  fee paid anyway:", String(failed.fee), "lamports");
    return failed;
  }
}

/** With preflight (the default) the RPC rejects it before it lands: no fee. */
export async function sendToUnapprovedWithPreflight(
  holder: TransactionSigner,
  mint: Address,
  unapproved: Address,
) {
  try {
    await transfer(holder, mint, unapproved, 1_000_000n);
    throw new Error("expected the transfer to fail");
  } catch (error) {
    const { transactionMessage } = error as {
      transactionMessage: Parameters<typeof isToken2022Error>[1];
    };
    const cause = isSolanaError(error) ? error.cause : undefined;
    const accountFrozen = isToken2022Error(
      cause,
      transactionMessage,
      TOKEN_2022_ERROR__ACCOUNT_FROZEN,
    );
    console.log("  accountFrozen:", accountFrozen, "(no fee: it never landed)");
    return {
      code: isSolanaError(error) ? error.context.__code : undefined,
      accountFrozen,
      message:
        (cause as Error | undefined)?.message ?? (error as Error).message,
    };
  }
}

/**
 * The permanent delegate (the issuer) moves tokens out of any account
 * without the holder's signature, e.g. to recover them after a court order.
 */
export async function clawBack(
  issuer: TransactionSigner,
  mint: Address,
  holder: Address,
  amount: bigint,
) {
  const source = await tokenAccountOf(holder, mint);
  const signature = await send(issuer, [
    getTransferCheckedInstruction({
      source,
      mint,
      destination: await tokenAccountOf(issuer.address, mint),
      authority: issuer,
      amount,
      decimals: 6,
    }),
  ]);
  console.log(
    `Permanent delegate moved ${lsf(amount)} from ${source} to the issuer`,
  );
  console.log("Signature:", signature);
  return signature;
}

/** Pause every transfer of the asset, then resume. */
export async function pause(issuer: TransactionSigner, mint: Address) {
  const signature = await send(issuer, [
    getPauseInstruction({ mint, authority: issuer }),
  ]);
  console.log("Paused the asset. Signature:", signature);
  return signature;
}
export async function resume(issuer: TransactionSigner, mint: Address) {
  const signature = await send(issuer, [
    getResumeInstruction({ mint, authority: issuer }),
  ]);
  console.log("Resumed the asset. Signature:", signature);
  return signature;
}
```

<div className="sol-term not-prose" data-term="paths/assets/issue-asset/blocked" data-tab="blocked-transfer.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">A permitted transfer, a blocked one, a pause and a permanent-delegate transfer</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="A permitted transfer, a blocked one, a pause and a permanent-delegate transfer: Output">
<div className="sol-term-step" data-step="1" data-pending="tx">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await transfer(holder, mint, approved.address, 100\_000\_000n)</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Transfer 100 LSF\: confirmed</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="3m3VeXJvsqmPunuwHRyf3qrXXYApTCv2WABEib1U9M7qrXSXgwJxDopg1L6cfvUQ9NL6aG8bJDj6csHVxDm69oTM"><span className="sol-h-f">3m3VeXJvsqmPunuwHRyf3qrXXYApTCv2WABEib1U9M7qrXSXgwJxDopg1L6cfvUQ9NL6aG8bJDj6csHVxDm69oTM</span><span className="sol-h-s" aria-hidden="true">3m3V…9oTM</span></span></div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await openAccount(issuer, mint, unapproved.address)</div>
<div className="sol-term-row sol-term-ln">Opened <span className="sol-h" title="FecRDHyzRTLH3dfdz6ni5pnGq5j883zcSBToSe3PPdbP"><span className="sol-h-f">FecRDHyzRTLH3dfdz6ni5pnGq5j883zcSBToSe3PPdbP</span><span className="sol-h-s" aria-hidden="true">FecR…PdbP</span></span> <span className="sol-term-k">state\:</span> Frozen</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await sendToUnapproved(holder, mint, unapproved.address)</div>
<div className="sol-term-row sol-term-ln" data-tone="error">Transfer 1 LSF\: failed onchain</div>
<div className="sol-term-row sol-term-ln" data-tone="error">Failed <span className="sol-term-k">signature\:</span> <span className="sol-h" title="57czSUTPw8a1c8yN7n4TMV3CsRGEQSqaa3s7Tuvv4sV3jN5HQaurXZZnCtkFnv4DumVSi7WFMpHVhDYcKdtaxseW"><span className="sol-h-f">57czSUTPw8a1c8yN7n4TMV3CsRGEQSqaa3s7Tuvv4sV3jN5HQaurXZZnCtkFnv4DumVSi7WFMpHVhDYcKdtaxseW</span><span className="sol-h-s" aria-hidden="true">57cz…xseW</span></span></div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2"><span className="sol-term-k">err\:</span> `{"InstructionError":[0,{"Custom":17}]}`</div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2"><span className="sol-term-k">log\:</span> Program log\: Error\: Account is frozen</div>
<div className="sol-term-row sol-term-ln" data-indent="2">fee paid anyway\: 5000 lamports</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await sendToUnapprovedWithPreflight(holder, mint, unapproved.address)</div>
<div className="sol-term-row sol-term-ln" data-tone="error">Transfer 1 LSF\: rejected\: Custom program error\: \#17 (instruction \#1)</div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">accountFrozen\:</span> true (no <span className="sol-term-k">fee\:</span> it never landed)</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await pause(issuer, mint)</div>
<div className="sol-term-row sol-term-ln">Paused the asset. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="34UgQ3NwajBVsXCGihEi9pTCpFc8CCkWDfgRzQD2KLyfGGwTpAux7hf7e8RTQfFBChZDsdxQwa4Ef5AVSCgWWy67"><span className="sol-h-f">34UgQ3NwajBVsXCGihEi9pTCpFc8CCkWDfgRzQD2KLyfGGwTpAux7hf7e8RTQfFBChZDsdxQwa4Ef5AVSCgWWy67</span><span className="sol-h-s" aria-hidden="true">34Ug…Wy67</span></span></div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await transfer(holder, mint, approved.address, 1\_000\_000n)</div>
<div className="sol-term-row sol-term-ln" data-tone="error">Transfer 1 LSF\: rejected\: Custom program error\: \#67 (instruction \#1)</div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await resume(issuer, mint)</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Resumed the asset. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="2k8BNXskFbwdVxvxihzs72mDDkGkm6GBmgtVXwJAD8X8QXCUcSSXYSENSWbi85uKmUSNEUBwNv63sem2f7vb9weA"><span className="sol-h-f">2k8BNXskFbwdVxvxihzs72mDDkGkm6GBmgtVXwJAD8X8QXCUcSSXYSENSWbi85uKmUSNEUBwNv63sem2f7vb9weA</span><span className="sol-h-s" aria-hidden="true">2k8B…9weA</span></span></div>
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\></span> await clawBack(issuer, mint, approved.address, 50\_000\_000n)</div>
<div className="sol-term-row sol-term-ln">Permanent delegate moved 50 LSF from <span className="sol-h" title="CpvfwkairbnMrGqdW9wxMSiFgsHxi7666Gu4j7vCdjDv"><span className="sol-h-f">CpvfwkairbnMrGqdW9wxMSiFgsHxi7666Gu4j7vCdjDv</span><span className="sol-h-s" aria-hidden="true">Cpvf…djDv</span></span> to the issuer</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="3ZXvUsuYkbBJMyCr4y1g8iKt8wmsJtt5xhybWW34W6vYShELvj2MMhwZ7UqeAxXVuAFK3Hs76Xb1QBhDJuNXwkmE"><span className="sol-h-f">3ZXvUsuYkbBJMyCr4y1g8iKt8wmsJtt5xhybWW34W6vYShELvj2MMhwZ7UqeAxXVuAFK3Hs76Xb1QBhDJuNXwkmE</span><span className="sol-h-s" aria-hidden="true">3ZXv…wkmE</span></span></div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="ok">100 LSF transfer confirmed</span><span className="sol-term-badge" data-tone="error">Failed\: Account is frozen (Custom\: 17)</span><span className="sol-term-badge" data-tone="error">Failed\: Mint is paused (Custom\: 67)</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

## 7. Run it

Save this as `run.ts`. It calls the functions above in order: create the asset,
give a new holder a little SOL for fees, approve two investors and the issuer's
own account (so `clawBack` has somewhere to send tokens), then send to an
approved and an unapproved account (with and without preflight), pause, try a
transfer, resume, claw back 50 LSF, and print every balance.

```ts run.ts
// run.ts: create the asset, approve holders and test every rule, in order.
//   npx tsx run.ts
// The issuer key is read from ISSUER_KEYPAIR, or from the Solana CLI default
// ~/.config/solana/id.json. On devnet, fund that wallet first.
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import {
  createKeyPairSignerFromBytes,
  generateKeyPairSigner,
  lamports,
  type Address,
  type TransactionSigner,
} from "@solana/kit";
import { getTransferSolInstruction } from "@solana-program/system";
import { fetchToken } from "@solana-program/token-2022";
import {
  approveHolder,
  lsf,
  openAccount,
  tokenAccountOf,
} from "./approve-holder";
import {
  clawBack,
  pause,
  resume,
  sendToUnapproved,
  sendToUnapprovedWithPreflight,
  transfer,
} from "./blocked-transfer";
import { rpc, send } from "./config";
import { createAsset } from "./create-asset";

export async function run(issuer: TransactionSigner) {
  const { mint } = await createAsset(issuer);

  const holder = await generateKeyPairSigner();
  const approved = await generateKeyPairSigner();
  const unapproved = await generateKeyPairSigner();
  // The holder signs its own transfers, so it needs a little SOL for fees.
  await send(issuer, [
    getTransferSolInstruction({
      source: issuer,
      destination: holder.address,
      amount: lamports(10_000_000n), // 0.01 SOL
    }),
  ]);

  // Approve two investors (after your KYC check) and the issuer's own
  // account, which clawBack sends tokens to. The first investor gets 1000 LSF.
  for (const [owner, amount] of [
    [holder.address, 1_000_000_000n],
    [approved.address, 0n],
    [issuer.address, 0n],
  ] as const) {
    await openAccount(issuer, mint, owner);
    await approveHolder(issuer, mint, owner, amount);
  }

  const sent = await transfer(holder, mint, approved.address, 100_000_000n);

  // The unapproved account exists but stays frozen.
  await openAccount(issuer, mint, unapproved.address);
  const blocked = await sendToUnapproved(holder, mint, unapproved.address);
  const rejected = await sendToUnapprovedWithPreflight(
    holder,
    mint,
    unapproved.address,
  );

  await pause(issuer, mint);
  let pausedTransferFailed = false;
  try {
    await transfer(holder, mint, approved.address, 1_000_000n);
  } catch {
    pausedTransferFailed = true; // transfer() printed why
  }
  await resume(issuer, mint);

  const recovered = await clawBack(issuer, mint, approved.address, 50_000_000n);

  const balance = async (owner: Address) =>
    lsf((await fetchToken(rpc, await tokenAccountOf(owner, mint))).data.amount);
  console.log(
    "Balances: holder",
    await balance(holder.address),
    "| approved",
    await balance(approved.address),
    "| unapproved",
    await balance(unapproved.address),
    "| issuer",
    await balance(issuer.address),
  );

  return { mint, sent, blocked, rejected, pausedTransferFailed, recovered };
}

// Run when started directly (not when imported by the tests).
if (
  process.argv[1] &&
  import.meta.url === pathToFileURL(process.argv[1]).href
) {
  const keyPath =
    process.env.ISSUER_KEYPAIR ??
    join(homedir(), ".config", "solana", "id.json");
  const bytes = new Uint8Array(JSON.parse(await readFile(keyPath, "utf8")));
  await run(await createKeyPairSignerFromBytes(bytes));
}
```

<div className="sol-term not-prose" data-term="paths/assets/issue-asset/run" data-tab="run.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Output of npx tsx run.ts</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Output of npx tsx run.ts: Output">
<div className="sol-term-step" data-step="1" data-pending="tx">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\$</span> npx tsx run.ts</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Mint\:</span> <span className="sol-h" title="Fser2BLgZx7Ed27Dyb6UiKQvecHWAEThXqVZzFT31hu8"><span className="sol-h-f">Fser2BLgZx7Ed27Dyb6UiKQvecHWAEThXqVZzFT31hu8</span><span className="sol-h-s" aria-hidden="true">Fser…1hu8</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Extensions\:</span> MetadataPointer, PausableConfig, PermanentDelegate, DefaultAccountState, TokenMetadata</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="25C6zgPeq6PunC6pcnCWPpZBu7gGkg62Esnpw2TqC4r9meGwXhHaziTjkQDsk5zkMwDXLW5fjqL8GWJJpvp6MZXn"><span className="sol-h-f">25C6zgPeq6PunC6pcnCWPpZBu7gGkg62Esnpw2TqC4r9meGwXhHaziTjkQDsk5zkMwDXLW5fjqL8GWJJpvp6MZXn</span><span className="sol-h-s" aria-hidden="true">25C6…MZXn</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Fee\:</span> 10000 lamports</div>
<div className="sol-term-row sol-term-ln">Opened <span className="sol-h" title="BuJ4KXhmUbw4yi2fd2K3jTE7Smp4f15w7Ezv4Wpkpbwq"><span className="sol-h-f">BuJ4KXhmUbw4yi2fd2K3jTE7Smp4f15w7Ezv4Wpkpbwq</span><span className="sol-h-s" aria-hidden="true">BuJ4…pbwq</span></span> <span className="sol-term-k">state\:</span> Frozen</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Approved <span className="sol-h" title="BuJ4KXhmUbw4yi2fd2K3jTE7Smp4f15w7Ezv4Wpkpbwq"><span className="sol-h-f">BuJ4KXhmUbw4yi2fd2K3jTE7Smp4f15w7Ezv4Wpkpbwq</span><span className="sol-h-s" aria-hidden="true">BuJ4…pbwq</span></span> <span className="sol-term-k">state\:</span> Initialized <span className="sol-term-k">balance\:</span> 1000 LSF</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="57hTnE611zzHEXh5t2Dz3iwz7BMNCs3txhkjk6GcNSQwY42DAKzLNb8TMYNwGcraTwaoswwPPXE4CzFx4z3drF6C"><span className="sol-h-f">57hTnE611zzHEXh5t2Dz3iwz7BMNCs3txhkjk6GcNSQwY42DAKzLNb8TMYNwGcraTwaoswwPPXE4CzFx4z3drF6C</span><span className="sol-h-s" aria-hidden="true">57hT…rF6C</span></span></div>
<div className="sol-term-row sol-term-ln">Opened <span className="sol-h" title="BbUYndSSGyYT5gR9LoLjWboZhL63GoyTJm5tDoho7qSS"><span className="sol-h-f">BbUYndSSGyYT5gR9LoLjWboZhL63GoyTJm5tDoho7qSS</span><span className="sol-h-s" aria-hidden="true">BbUY…7qSS</span></span> <span className="sol-term-k">state\:</span> Frozen</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Approved <span className="sol-h" title="BbUYndSSGyYT5gR9LoLjWboZhL63GoyTJm5tDoho7qSS"><span className="sol-h-f">BbUYndSSGyYT5gR9LoLjWboZhL63GoyTJm5tDoho7qSS</span><span className="sol-h-s" aria-hidden="true">BbUY…7qSS</span></span> <span className="sol-term-k">state\:</span> Initialized <span className="sol-term-k">balance\:</span> 0 LSF</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="5EfHpvbBGZkLx4z3YioPEiu3AHR6pacLt7mzct1TFDN9rwrBUynWNyJbznSeyV8ZNKeW1uSXKR3eEetnF98FmRiz"><span className="sol-h-f">5EfHpvbBGZkLx4z3YioPEiu3AHR6pacLt7mzct1TFDN9rwrBUynWNyJbznSeyV8ZNKeW1uSXKR3eEetnF98FmRiz</span><span className="sol-h-s" aria-hidden="true">5EfH…mRiz</span></span></div>
<div className="sol-term-row sol-term-ln">Opened <span className="sol-h" title="BuY7wikCSJsP4mDYtCa14b3nXU4NHkPnUdxDn4SGfsUT"><span className="sol-h-f">BuY7wikCSJsP4mDYtCa14b3nXU4NHkPnUdxDn4SGfsUT</span><span className="sol-h-s" aria-hidden="true">BuY7…fsUT</span></span> <span className="sol-term-k">state\:</span> Frozen</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Approved <span className="sol-h" title="BuY7wikCSJsP4mDYtCa14b3nXU4NHkPnUdxDn4SGfsUT"><span className="sol-h-f">BuY7wikCSJsP4mDYtCa14b3nXU4NHkPnUdxDn4SGfsUT</span><span className="sol-h-s" aria-hidden="true">BuY7…fsUT</span></span> <span className="sol-term-k">state\:</span> Initialized <span className="sol-term-k">balance\:</span> 0 LSF</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="2PyJ79R1DvAMPnqkUQKwTYgcVkMaSSbkC1LkD9r9EpYYNMsyjHTiwJo9MQToM8Gv5gQEFnHpwR19Tq7g3e4HoAse"><span className="sol-h-f">2PyJ79R1DvAMPnqkUQKwTYgcVkMaSSbkC1LkD9r9EpYYNMsyjHTiwJo9MQToM8Gv5gQEFnHpwR19Tq7g3e4HoAse</span><span className="sol-h-s" aria-hidden="true">2PyJ…oAse</span></span></div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Transfer 100 LSF\: confirmed</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="4Sxyq5BBcaNPLBRTJPnGcVXxWQshiJcdkx2UVEop2KoMD8Bd91Vvx111ndbU65Eo7bn3iGPrsERVEqXwjBcCGnFS"><span className="sol-h-f">4Sxyq5BBcaNPLBRTJPnGcVXxWQshiJcdkx2UVEop2KoMD8Bd91Vvx111ndbU65Eo7bn3iGPrsERVEqXwjBcCGnFS</span><span className="sol-h-s" aria-hidden="true">4Sxy…GnFS</span></span></div>
<div className="sol-term-row sol-term-ln">Opened <span className="sol-h" title="JBFb61VX7yHRp3SNR3g2zSFvo4pAKHG6F57qgXZ7dfBz"><span className="sol-h-f">JBFb61VX7yHRp3SNR3g2zSFvo4pAKHG6F57qgXZ7dfBz</span><span className="sol-h-s" aria-hidden="true">JBFb…dfBz</span></span> <span className="sol-term-k">state\:</span> Frozen</div>
<div className="sol-term-row sol-term-ln" data-tone="error">Transfer 1 LSF\: failed onchain</div>
<div className="sol-term-row sol-term-ln" data-tone="error">Failed <span className="sol-term-k">signature\:</span> <span className="sol-h" title="2uJ6CJ5PsyxZD8cvmgC6YS5KXeS94LPTQUHozG6MhiTVK6VVEqUXS92dRRDjdVYmQ3cX6CJKAXDKfSRZfxU6Qpbi"><span className="sol-h-f">2uJ6CJ5PsyxZD8cvmgC6YS5KXeS94LPTQUHozG6MhiTVK6VVEqUXS92dRRDjdVYmQ3cX6CJKAXDKfSRZfxU6Qpbi</span><span className="sol-h-s" aria-hidden="true">2uJ6…Qpbi</span></span></div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2"><span className="sol-term-k">err\:</span> `{"InstructionError":[0,{"Custom":17}]}`</div>
<div className="sol-term-row sol-term-ln" data-tone="error" data-indent="2"><span className="sol-term-k">log\:</span> Program log\: Error\: Account is frozen</div>
<div className="sol-term-row sol-term-ln" data-indent="2">fee paid anyway\: 5000 lamports</div>
<div className="sol-term-row sol-term-ln" data-tone="error">Transfer 1 LSF\: rejected\: Custom program error\: \#17 (instruction \#1)</div>
<div className="sol-term-row sol-term-ln" data-indent="2"><span className="sol-term-k">accountFrozen\:</span> true (no <span className="sol-term-k">fee\:</span> it never landed)</div>
<div className="sol-term-row sol-term-ln">Paused the asset. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="Ph8YZfLuwKUxocyPst5fEyziUCtwha3eAAzLggxDsb3Nq8icnX1hAXPmtfkJy2XgcXvW45DfLaZLVvJ8ssz6g9Z"><span className="sol-h-f">Ph8YZfLuwKUxocyPst5fEyziUCtwha3eAAzLggxDsb3Nq8icnX1hAXPmtfkJy2XgcXvW45DfLaZLVvJ8ssz6g9Z</span><span className="sol-h-s" aria-hidden="true">Ph8Y…6g9Z</span></span></div>
<div className="sol-term-row sol-term-ln" data-tone="error">Transfer 1 LSF\: rejected\: Custom program error\: \#67 (instruction \#1)</div>
<div className="sol-term-row sol-term-ln" data-tone="ok">Resumed the asset. <span className="sol-term-k">Signature\:</span> <span className="sol-h" title="2jv5ueFkaG3LkR1qLJbPLHG9dm9yCSCxRzuD4JRNpTovjFkrvemkUMHa8hFxrBngFAhyJQMpHbk3wsFazj4D9cAq"><span className="sol-h-f">2jv5ueFkaG3LkR1qLJbPLHG9dm9yCSCxRzuD4JRNpTovjFkrvemkUMHa8hFxrBngFAhyJQMpHbk3wsFazj4D9cAq</span><span className="sol-h-s" aria-hidden="true">2jv5…9cAq</span></span></div>
<div className="sol-term-row sol-term-ln">Permanent delegate moved 50 LSF from <span className="sol-h" title="BbUYndSSGyYT5gR9LoLjWboZhL63GoyTJm5tDoho7qSS"><span className="sol-h-f">BbUYndSSGyYT5gR9LoLjWboZhL63GoyTJm5tDoho7qSS</span><span className="sol-h-s" aria-hidden="true">BbUY…7qSS</span></span> to the issuer</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="3sR7wqUAWtJuiS5bRmDrBYFv8pph6RnHsD8a2XBUrZiF7Mzc66rpoXKDKjnhN1qGARQn9rWqBsR18tNmvUpCs9Ha"><span className="sol-h-f">3sR7wqUAWtJuiS5bRmDrBYFv8pph6RnHsD8a2XBUrZiF7Mzc66rpoXKDKjnhN1qGARQn9rWqBsR18tNmvUpCs9Ha</span><span className="sol-h-s" aria-hidden="true">3sR7…s9Ha</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Balances\:</span> holder 900 LSF \| approved 50 LSF \| unapproved 0 LSF \| issuer 50 LSF</div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="ok">100 LSF transfer confirmed</span><span className="sol-term-badge" data-tone="error">Failed\: Account is frozen (Custom\: 17)</span><span className="sol-term-badge" data-tone="error">Failed\: Mint is paused (Custom\: 67)</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

`run.ts` signs as the issuer with a key file: the one named in `ISSUER_KEYPAIR`,
or the Solana CLI default `~/.config/solana/id.json`. If you don't have one
yet, save this as `keygen.ts`. It writes a new key file in the same format and
prints the issuer's address:

```ts keygen.ts
import { generateKeyPairSync } from "node:crypto";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { createKeyPairSignerFromBytes } from "@solana/kit";

// Writes a new key file in the Solana CLI format (64 bytes as a JSON array).
const keyPath =
  process.env.ISSUER_KEYPAIR ?? join(homedir(), ".config", "solana", "id.json");
if (existsSync(keyPath)) throw new Error(`${keyPath} exists; not overwriting it`);
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
const bytes = new Uint8Array([
  ...privateKey.export({ format: "der", type: "pkcs8" }).subarray(-32),
  ...publicKey.export({ format: "der", type: "spki" }).subarray(-32),
]);
mkdirSync(dirname(keyPath), { recursive: true });
writeFileSync(keyPath, JSON.stringify([...bytes]), { mode: 0o600 });
console.log(`Issuer address: ${(await createKeyPairSignerFromBytes(bytes)).address}`);
```

```bash Terminal
npx tsx keygen.ts
```

The key file is the issuer's private key: anyone who has it controls the
asset. Keep it out of version control. On devnet, fund the printed address from
the Solana Faucet. On Surfpool, `surfpool start` airdrops SOL to
`~/.config/solana/id.json` at startup. If you created the key file later, or
keep it elsewhere, restart with `surfpool start --airdrop <issuer address>`.

Then run the script:

```bash Terminal
npx tsx run.ts
```

Expect the states, errors, and balances shown under the script, with your own
addresses and signatures. The examples package runs the same script in its
tests.

<Note>
  The full example is in
  [`packages/docs-examples/paths/assets/issue-asset`](https://github.com/solana-foundation/solana-com/tree/main/packages/docs-examples/paths/assets/issue-asset).
</Note>

## Enable confidentiality (optional)

Use this variant only if balances must be hidden from the public. It doesn't
change the steps above.

Confidential Balances hides token balances and transfer amounts. Addresses stay public, so anyone can still
see which accounts hold the asset and which accounts trade with each other. If
you set an auditor key, whoever holds it (you, or a regulator you give it to)
can decrypt every confidential transfer amount.

You turn it on with the `ConfidentialTransferMint` extension when you create
the mint. You can't add it to an existing mint, so decide before you issue. Set
`autoApproveNewAccounts: false`, so you approve each holder for confidential
use after your KYC check, as you approve them to hold the asset. Set the
auditor's ElGamal public key too; the auditor derives it from their own wallet
and sends you only the public key.

The confidential helpers need the ZK SDK, which derives the encryption keys and
generates the proofs (the example is tested with `@solana/zk-sdk` 0.5):

```bash Terminal
npm install @solana/zk-sdk
```

Save this as `create-confidential-asset.ts`:

- `createConfidentialAsset` is `createAsset` with one more extension.
- `enableConfidentialAccount` is the holder's side. It derives the holder's
  encryption keys from one wallet signature and sends a proof, generated on the
  holder's machine, that the key is valid.
- `approveConfidentialHolder` is your approval. It thaws the account and
  approves it for confidential use in one transaction.

```ts create-confidential-asset.ts
import {
  flattenInstructionPlan,
  generateKeyPairSigner,
  some,
  type Address,
  type Instruction,
  type InstructionPlan,
  type KeyPairSigner,
  type Signature,
  type TransactionSigner,
} from "@solana/kit";
import { getCreateAccountInstruction } from "@solana-program/system";
import {
  AccountState,
  extension,
  fetchMint,
  fetchToken,
  getApproveConfidentialTransferAccountInstruction,
  getInitializeMintInstruction,
  getMintSize,
  getPostInitializeInstructionsForMintExtensions,
  getPreInitializeInstructionsForMintExtensions,
  getThawAccountInstruction,
  TOKEN_2022_PROGRAM_ADDRESS,
  type Token,
} from "@solana-program/token-2022";
import {
  deriveConfidentialKeys,
  getCreateConfidentialTransferAccountInstructionPlan,
} from "@solana-program/token-2022/confidential";
import {
  AeKey,
  ElGamalKeypair,
  ElGamalSecretKey,
} from "@solana/zk-sdk/bundler";
import { tokenAccountOf } from "./approve-holder";
import { rpc, send } from "./config";

/**
 * The same asset as createAsset, plus Confidential Balances. The extension
 * can only be added when the mint is created. With autoApproveNewAccounts
 * false the issuer approves each holder for confidential use, and the
 * auditor's ElGamal public key can decrypt every confidential transfer amount.
 */
export async function createConfidentialAsset(
  issuer: TransactionSigner,
  auditorElgamalPubkey: Address,
): Promise<{ mint: Address; signature: Signature; extensions: string[] }> {
  const mint = await generateKeyPairSigner();
  const extensions = [
    extension("MetadataPointer", {
      authority: issuer.address,
      metadataAddress: mint.address,
    }),
    extension("TokenMetadata", {
      updateAuthority: issuer.address,
      mint: mint.address,
      name: "Lisbon Solar Fund",
      symbol: "LSF",
      uri: "https://example.com/lsf.json",
      additionalMetadata: new Map([["isin", "PTLSF0000001"]]),
    }),
    extension("PausableConfig", { authority: issuer.address, paused: false }),
    extension("PermanentDelegate", { delegate: issuer.address }),
    extension("DefaultAccountState", { state: AccountState.Frozen }),
    extension("ConfidentialTransferMint", {
      authority: some(issuer.address),
      autoApproveNewAccounts: false,
      auditorElgamalPubkey: some(auditorElgamalPubkey),
    }),
  ];

  const space = getMintSize(
    extensions.filter((e) => e.__kind !== "TokenMetadata"),
  );
  const rent = await rpc
    .getMinimumBalanceForRentExemption(BigInt(getMintSize(extensions)))
    .send();

  const signature = await send(issuer, [
    getCreateAccountInstruction({
      payer: issuer,
      newAccount: mint,
      lamports: rent,
      space,
      programAddress: TOKEN_2022_PROGRAM_ADDRESS,
    }),
    ...getPreInitializeInstructionsForMintExtensions(mint.address, extensions),
    getInitializeMintInstruction({
      mint: mint.address,
      decimals: 6,
      mintAuthority: issuer.address,
      freezeAuthority: issuer.address,
    }),
    ...getPostInitializeInstructionsForMintExtensions(
      mint.address,
      issuer,
      extensions,
    ),
  ]);

  const account = await fetchMint(rpc, mint.address);
  const enabled =
    account.data.extensions.__option === "Some"
      ? account.data.extensions.value.map((e) => e.__kind)
      : [];
  return { mint: mint.address, signature, extensions: enabled };
}

/** The auditor's ElGamal public key, derived from the auditor's wallet. */
export async function auditorKey(auditor: KeyPairSigner) {
  const { elgamalKeypair } = await deriveConfidentialKeys({ signer: auditor });
  return elgamalKeypair.elgamalPubkey;
}

/**
 * Holder side: open the token account and set it up for confidential
 * balances. The holder's keys come from one wallet signature, and the
 * proof that the ElGamal key is valid is generated here, on the client.
 */
export async function enableConfidentialAccount(
  holder: KeyPairSigner,
  mint: Address,
) {
  const keys = await deriveConfidentialKeys({ signer: holder });
  const plan = await getCreateConfidentialTransferAccountInstructionPlan({
    rpc,
    payer: holder,
    owner: holder,
    mint,
    elgamalKeypair: ElGamalKeypair.fromSecretKey(
      ElGamalSecretKey.fromBytes(keys.elgamalKeypair.secretKey),
    ),
    aesKey: AeKey.fromBytes(keys.aeKey),
  });
  const signature = await send(holder, instructionsOf(plan));
  return { signature, ...(await stateOf(holder.address, mint)) };
}

/**
 * Issuer side, after your KYC check: thaw the account (freeze authority) and
 * approve it for confidential use (confidential transfer authority).
 */
export async function approveConfidentialHolder(
  issuer: TransactionSigner,
  mint: Address,
  owner: Address,
) {
  const account = await tokenAccountOf(owner, mint);
  const signature = await send(issuer, [
    getThawAccountInstruction({ account, mint, owner: issuer }),
    getApproveConfidentialTransferAccountInstruction({
      token: account,
      mint,
      authority: issuer,
    }),
  ]);
  return { signature, ...(await stateOf(owner, mint)) };
}

/** Whether the account is frozen, and whether it's approved for confidential use. */
async function stateOf(owner: Address, mint: Address) {
  const account = await tokenAccountOf(owner, mint);
  const { data } = await fetchToken(rpc, account);
  const confidential = confidentialExtension(data);
  return {
    account,
    state: AccountState[data.state],
    confidentialApproved: confidential?.approved ?? false,
  };
}

function confidentialExtension(data: Token) {
  if (data.extensions.__option !== "Some") return undefined;
  for (const e of data.extensions.value)
    if (e.__kind === "ConfidentialTransferAccount") return e;
  return undefined;
}

/** The helper returns an instruction plan; here it fits in one transaction. */
function instructionsOf(plan: InstructionPlan): Instruction[] {
  return flattenInstructionPlan(plan).map((p) => {
    if (p.kind !== "single") throw new Error("unexpected plan step");
    return p.instruction;
  });
}
```

Save this as `confidential.ts`. Like `run.ts`, it signs as the issuer with your
key file. It creates a throwaway auditor key and a new holder, gives the holder
a little SOL for fees, creates the asset, then enables and approves the
holder's account.

```ts confidential.ts
// confidential.ts: create the confidential asset, then enable and approve
// one holder.
//   npx tsx confidential.ts
// The issuer key is read from ISSUER_KEYPAIR, or from the Solana CLI default
// ~/.config/solana/id.json. On devnet, fund that wallet first.
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import {
  createKeyPairSignerFromBytes,
  generateKeyPairSigner,
  lamports,
  type TransactionSigner,
} from "@solana/kit";
import { getTransferSolInstruction } from "@solana-program/system";
import { fetchMint } from "@solana-program/token-2022";
import { rpc, send } from "./config";
import {
  approveConfidentialHolder,
  auditorKey,
  createConfidentialAsset,
  enableConfidentialAccount,
} from "./create-confidential-asset";

export async function runConfidential(issuer: TransactionSigner) {
  // In production the auditor derives this key from their own wallet and
  // sends you only the public key.
  const auditor = await generateKeyPairSigner();
  const auditorPubkey = await auditorKey(auditor);
  const asset = await createConfidentialAsset(issuer, auditorPubkey);
  console.log("Mint:", asset.mint);
  console.log("Extensions:", asset.extensions.join(", "));
  const { data } = await fetchMint(rpc, asset.mint);
  const config =
    data.extensions.__option === "Some"
      ? data.extensions.value.find(
          (e) => e.__kind === "ConfidentialTransferMint",
        )
      : undefined;
  if (config?.__kind !== "ConfidentialTransferMint")
    throw new Error("ConfidentialTransferMint missing");
  console.log("Auto-approve new accounts:", config.autoApproveNewAccounts);
  console.log(
    "Auditor ElGamal key:",
    config.auditorElgamalPubkey.__option === "Some"
      ? config.auditorElgamalPubkey.value
      : "none",
  );
  console.log("Signature:", asset.signature);

  // The holder signs and pays for their own account setup.
  const holder = await generateKeyPairSigner();
  await send(issuer, [
    getTransferSolInstruction({
      source: issuer,
      destination: holder.address,
      amount: lamports(10_000_000n), // 0.01 SOL
    }),
  ]);

  const enabled = await enableConfidentialAccount(holder, asset.mint);
  console.log(
    "Holder enabled confidential balances on",
    enabled.account,
    "state:",
    enabled.state,
    "confidential approved:",
    enabled.confidentialApproved,
  );
  console.log("Signature:", enabled.signature);

  // After your KYC check passes.
  const approved = await approveConfidentialHolder(
    issuer,
    asset.mint,
    holder.address,
  );
  console.log(
    "Issuer approved",
    approved.account,
    "state:",
    approved.state,
    "confidential approved:",
    approved.confidentialApproved,
  );
  console.log("Signature:", approved.signature);

  return {
    asset,
    holder,
    autoApprove: config.autoApproveNewAccounts,
    auditor: config.auditorElgamalPubkey,
    auditorPubkey,
    enabled,
    approved,
  };
}

// Run when started directly (not when imported by the tests).
if (
  process.argv[1] &&
  import.meta.url === pathToFileURL(process.argv[1]).href
) {
  const keyPath =
    process.env.ISSUER_KEYPAIR ??
    join(homedir(), ".config", "solana", "id.json");
  const bytes = new Uint8Array(JSON.parse(await readFile(keyPath, "utf8")));
  await runConfidential(await createKeyPairSignerFromBytes(bytes));
}
```

<div className="sol-term not-prose" data-term="paths/assets/issue-asset/confidential-run" data-tab="confidential.ts" data-kind="block" data-steps="1" data-l-run="Run" data-l-run-step="Run step" data-l-next="Next step" data-l-all="Run all" data-l-again="Run again" data-l-running="Running…" data-l-tx="Sending transaction…" data-l-http="Requesting…" data-l-call="Running…" data-l-confirming="Confirming…" data-l-done="Done" data-l-copied="Copied" data-l-step="Step">
<div className="sol-term-head"><span className="sol-term-title">Creating the asset with Confidential Balances, then enabling and approving one holder</span><span className="sol-term-env">Local test network (Surfpool)</span><button type="button" className="sol-term-copy" data-act="copy">Copy</button></div>
<div className="sol-term-screen" role="region" tabIndex="0" aria-label="Creating the asset with Confidential Balances, then enabling and approving one holder: Output">
<div className="sol-term-step" data-step="1" data-pending="tx">
<div className="sol-term-row sol-term-cmd"><span className="sol-term-ps" aria-hidden="true">\$</span> npx tsx confidential.ts</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Mint\:</span> <span className="sol-h" title="BGNsTFxmE969yPfGMS6GriTFgVYPcDZXqHbuRcLibfJH"><span className="sol-h-f">BGNsTFxmE969yPfGMS6GriTFgVYPcDZXqHbuRcLibfJH</span><span className="sol-h-s" aria-hidden="true">BGNs…bfJH</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Extensions\:</span> MetadataPointer, PausableConfig, PermanentDelegate, DefaultAccountState, ConfidentialTransferMint, TokenMetadata</div>
<div className="sol-term-row sol-term-ln">Auto-approve new accounts\: false</div>
<div className="sol-term-row sol-term-ln">Auditor ElGamal key\: <span className="sol-h" title="BGAZF9CWgvrByfhk3EE9tgVAyViHqd53NEP1g4sWkMac"><span className="sol-h-f">BGAZF9CWgvrByfhk3EE9tgVAyViHqd53NEP1g4sWkMac</span><span className="sol-h-s" aria-hidden="true">BGAZ…kMac</span></span></div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="37wcDe44ozgju3EJWw7mwnPcRmpMN3xgYWmd4WUa1sENqFfRiFmGmpsijNSf7c9rHeaPL7F6jRJNYwG5wHeYcSTX"><span className="sol-h-f">37wcDe44ozgju3EJWw7mwnPcRmpMN3xgYWmd4WUa1sENqFfRiFmGmpsijNSf7c9rHeaPL7F6jRJNYwG5wHeYcSTX</span><span className="sol-h-s" aria-hidden="true">37wc…cSTX</span></span></div>
<div className="sol-term-row sol-term-ln">Holder enabled confidential balances on <span className="sol-h" title="9f4CRR8qhtrJqCrwoLSpTBkqfmxA6cBcrevXYy7TLDiU"><span className="sol-h-f">9f4CRR8qhtrJqCrwoLSpTBkqfmxA6cBcrevXYy7TLDiU</span><span className="sol-h-s" aria-hidden="true">9f4C…LDiU</span></span> <span className="sol-term-k">state\:</span> Frozen confidential approved\: false</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="3CLJNdq8zb9CPLyNM3SzNWRwRAeDYCykPYH4zHB3QWoECvueGGcNyhsGUPhMnjwGKjsEYAkHe1xbXG2bU46zCguT"><span className="sol-h-f">3CLJNdq8zb9CPLyNM3SzNWRwRAeDYCykPYH4zHB3QWoECvueGGcNyhsGUPhMnjwGKjsEYAkHe1xbXG2bU46zCguT</span><span className="sol-h-s" aria-hidden="true">3CLJ…CguT</span></span></div>
<div className="sol-term-row sol-term-ln">Issuer approved <span className="sol-h" title="9f4CRR8qhtrJqCrwoLSpTBkqfmxA6cBcrevXYy7TLDiU"><span className="sol-h-f">9f4CRR8qhtrJqCrwoLSpTBkqfmxA6cBcrevXYy7TLDiU</span><span className="sol-h-s" aria-hidden="true">9f4C…LDiU</span></span> <span className="sol-term-k">state\:</span> Initialized confidential approved\: true</div>
<div className="sol-term-row sol-term-ln"><span className="sol-term-k">Signature\:</span> <span className="sol-h" title="2mtEayHEcyJhdtb6zGCNqd8cXMa6DyEq7viJ5A36uAqw5W8aFUuThLZa3MzjiakXrP5efChXXJ4q429Fv2jde6Um"><span className="sol-h-f">2mtEayHEcyJhdtb6zGCNqd8cXMa6DyEq7viJ5A36uAqw5W8aFUuThLZa3MzjiakXrP5efChXXJ4q429Fv2jde6Um</span><span className="sol-h-s" aria-hidden="true">2mtE…e6Um</span></span></div>
<div className="sol-term-result"><span className="sol-term-badge" data-tone="ok">All transactions confirmed</span></div>
</div>
</div>
<div className="sol-term-foot"><button type="button" className="sol-term-btn" data-act="run">Run</button><span className="sol-term-status"></span><span className="sol-term-sr" role="status"></span></div>
</div>

```bash Terminal
npx tsx confidential.ts
```

The holder can set up the account while it is still frozen, but can't use it
until you approve it.

How confidentiality works with the asset's other controls:

- **Approval.** A holder needs both approvals: a thaw from the freeze authority
  and a confidential approval from the confidential transfer authority. There
  is no instruction to withdraw a confidential approval. To stop a holder,
  freeze the account. A frozen account can't deposit, withdraw, or send or
  receive a confidential transfer.
- **Pause.** Pausing also stops confidential deposits, transfers, and
  withdrawals.
- **Permanent delegate.** It can still move or burn any account's public
  balance, but not the encrypted balance: confidential transfers, withdrawals,
  and `ConfidentialMintBurn` burns all need the holder's signature. To recover
  tokens from an encrypted balance, the holder has to withdraw them first;
  freezing the account keeps them where they are. Plan your recovery runbook
  around this.
- **Auditor.** The confidential transfer authority can change the auditor key
  later. Transfers made after the change are encrypted to the new key.

Holders also need software, in their wallet or your app, that generates
zero-knowledge proofs with their keys: setting up the account, transferring,
and withdrawing need proofs. Depositing needs none, and applying incoming
amounts needs the holder's keys but no proof. The
[Confidential Balances guides](/developers/docs/tokens/extensions/confidential-transfer)
show each step in Rust and TypeScript, and the
[issuer guide](/developers/docs/tokens/extensions/confidential-transfer/issuer-guide)
covers the issuer's side.
