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

# Non-Transferable Tokens

> Create a mint whose tokens can be minted, burned, and closed out, but cannot be transferred between token accounts.

## What Are Non-Transferable Tokens?

The Token Extension Program's `NonTransferable` mint extension makes every
token account for that mint non-transferable. After tokens are minted, token
holders cannot move them to another token account with `Transfer` or
`TransferChecked`.

This pattern is useful for assets that should stay attached to one wallet.

Non-transferable tokens can still be:

- Minted by the mint authority
- Burned by the token account owner or an authorized delegate
- Token accounts can be closed after the balance reaches zero

<Info>
  **Token Account Extensions**

  When a token account is initialized for a mint with `NonTransferable`, the
  token account is initialized with `NonTransferableAccount` and
`ImmutableOwner`. When the token account is created through the
  [Associated Token
  Program](/developers/docs/tokens/basics/create-token-account#how-to-create-an-associated-token-account),
  the required account size is calculated and the token account is created with
  the required size and rent-exempt lamports.
</Info>

## Before you start

The examples on this page run against a local validator at
`http://localhost:8899` (WebSocket `ws://localhost:8900`) and fund their
accounts with airdrops from it. Start one in a separate terminal with
[Surfpool](https://surfpool.run) (`surfpool start`) or
`solana-test-validator`.

Each code section below lists the packages or crates it needs. The TypeScript
examples use top-level `await`, so run them as ES modules, for example with
`npx tsx index.ts` in a project whose `package.json` sets `"type": "module"`.

## How to Create a Non-Transferable Mint

To create a non-transferable mint:

1. Calculate the mint account size and rent needed for the mint and the
   `NonTransferable` extension.
2. Create the mint account with `CreateAccount`, initialize
   `NonTransferable`, and initialize the mint with `InitializeMint`.
3. Create token accounts for the mint. `NonTransferableAccount` and
   `ImmutableOwner` are automatically enabled for token accounts.
4. `Transfer` and `TransferChecked` fail with
   `TokenError::NonTransferable`.

<Steps>
  <Step title="Calculate account size">
    Calculate the mint account size for the base mint plus the `NonTransferable`
    extension. This is the size used in `CreateAccount`.

    ```ts Example focus={15,17}
    const client = await createClient()
      .use(generatedPayer())
      .use(
        solanaRpc({
          rpcUrl: "http://localhost:8899",
          rpcSubscriptionsUrl: "ws://localhost:8900"
        })
      )
      .use(rpcAirdrop())
      .use(airdropPayer(lamports(1_000_000_000n)));

    const mint = await generateKeyPairSigner();
    const recipient = await generateKeyPairSigner();

    const nonTransferableExtension = extension("NonTransferable", {});

    const mintSpace = BigInt(getMintSize([nonTransferableExtension]));
    ```
  </Step>

  <Step title="Calculate rent">
    Calculate rent using the size needed for the mint plus the `NonTransferable`
    extension.

    ```ts Example focus={19-21}
    const client = await createClient()
      .use(generatedPayer())
      .use(
        solanaRpc({
          rpcUrl: "http://localhost:8899",
          rpcSubscriptionsUrl: "ws://localhost:8900"
        })
      )
      .use(rpcAirdrop())
      .use(airdropPayer(lamports(1_000_000_000n)));

    const mint = await generateKeyPairSigner();
    const recipient = await generateKeyPairSigner();

    const nonTransferableExtension = extension("NonTransferable", {});

    const mintSpace = BigInt(getMintSize([nonTransferableExtension]));

    const mintRent = await client.rpc
      .getMinimumBalanceForRentExemption(mintSpace)
      .send();
    ```
  </Step>

  <Step title="Create the mint account">
    Create the mint account with the calculated space and lamports.

    ```ts Example focus={23-31}
    const client = await createClient()
      .use(generatedPayer())
      .use(
        solanaRpc({
          rpcUrl: "http://localhost:8899",
          rpcSubscriptionsUrl: "ws://localhost:8900"
        })
      )
      .use(rpcAirdrop())
      .use(airdropPayer(lamports(1_000_000_000n)));

    const mint = await generateKeyPairSigner();
    const recipient = await generateKeyPairSigner();

    const nonTransferableExtension = extension("NonTransferable", {});

    const mintSpace = BigInt(getMintSize([nonTransferableExtension]));

    const mintRent = await client.rpc
      .getMinimumBalanceForRentExemption(mintSpace)
      .send();

    await client.sendTransaction([
      getCreateAccountInstruction({
        payer: client.payer,
        newAccount: mint,
        lamports: mintRent,
        space: mintSpace,
        programAddress: TOKEN_2022_PROGRAM_ADDRESS
      })
    ]);
    ```
  </Step>

  <Step title="Initialize NonTransferable">
    Initialize the `NonTransferable` extension on the mint.

    ```ts Example focus={31-33}
    const client = await createClient()
      .use(generatedPayer())
      .use(
        solanaRpc({
          rpcUrl: "http://localhost:8899",
          rpcSubscriptionsUrl: "ws://localhost:8900"
        })
      )
      .use(rpcAirdrop())
      .use(airdropPayer(lamports(1_000_000_000n)));

    const mint = await generateKeyPairSigner();
    const recipient = await generateKeyPairSigner();

    const nonTransferableExtension = extension("NonTransferable", {});

    const mintSpace = BigInt(getMintSize([nonTransferableExtension]));

    const mintRent = await client.rpc
      .getMinimumBalanceForRentExemption(mintSpace)
      .send();

    await client.sendTransaction([
      getCreateAccountInstruction({
        payer: client.payer,
        newAccount: mint,
        lamports: mintRent,
        space: mintSpace,
        programAddress: TOKEN_2022_PROGRAM_ADDRESS
      }),
      getInitializeNonTransferableMintInstruction({
        mint: mint.address
      })
    ]);
    ```
  </Step>

  <Step title="Initialize the mint">
    Initialize the mint with `InitializeMint` in the same transaction.

    ```ts Example focus={34-39}
    const client = await createClient()
      .use(generatedPayer())
      .use(
        solanaRpc({
          rpcUrl: "http://localhost:8899",
          rpcSubscriptionsUrl: "ws://localhost:8900"
        })
      )
      .use(rpcAirdrop())
      .use(airdropPayer(lamports(1_000_000_000n)));

    const mint = await generateKeyPairSigner();
    const recipient = await generateKeyPairSigner();

    const nonTransferableExtension = extension("NonTransferable", {});

    const mintSpace = BigInt(getMintSize([nonTransferableExtension]));

    const mintRent = await client.rpc
      .getMinimumBalanceForRentExemption(mintSpace)
      .send();

    await client.sendTransaction([
      getCreateAccountInstruction({
        payer: client.payer,
        newAccount: mint,
        lamports: mintRent,
        space: mintSpace,
        programAddress: TOKEN_2022_PROGRAM_ADDRESS
      }),
      getInitializeNonTransferableMintInstruction({
        mint: mint.address
      }),
      getInitializeMintInstruction({
        mint: mint.address,
        decimals: 0,
        mintAuthority: client.payer.address,
        freezeAuthority: client.payer.address
      })
    ]);
    ```
  </Step>
</Steps>

<Info>
  **Instruction Order**

  `InitializeNonTransferableMint` must come before `InitializeMint`.
`CreateAccount`, `InitializeNonTransferableMint`, and
`InitializeMint` must be included in the same transaction.
</Info>

### Source Reference

| Item                                       | Description                                                                                                                                                                                                         | Source                                                                                                                            |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `NonTransferable`                          | Mint extension that marks tokens from the mint as non-transferable.                                                                                                                                                 | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/interface/src/extension/non_transferable.rs#L8-L13)  |
| `NonTransferableAccount`                   | Token account extension added to token accounts for non-transferable mints.                                                                                                                                         | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/interface/src/extension/non_transferable.rs#L15-L21) |
| `ImmutableOwner`                           | Token account extension that prevents ownership changes and is required for non-transferable token accounts.                                                                                                        | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/interface/src/extension/immutable_owner.rs#L8-L17)   |
| `InitializeNonTransferableMint`            | Instruction that initializes the mint-level non-transferable extension before `InitializeMint`.                                                                                                                     | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/interface/src/instruction.rs#L636-L647)              |
| `process_initialize_non_transferable_mint` | Processor logic that initializes the `NonTransferable` mint extension on an uninitialized mint.                                                                                                                     | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/program/src/processor.rs#L1528-L1540)                |
| `get_required_init_account_extensions`     | Used to automatically add token account extensions when token accounts are initialized based on extensions enabled on the mint. For `NonTransferable` mints, it adds `NonTransferableAccount` and `ImmutableOwner`. | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/interface/src/extension/mod.rs#L1292-L1319)          |

### Kit

These examples use the generated Token-2022 instructions directly.

```bash Terminal
npm install @solana/kit @solana/kit-plugin-rpc @solana/kit-plugin-signer @solana-program/system @solana-program/token-2022
```

```ts Instructions highlight={47-49,93-100}
import { lamports, createClient, generateKeyPairSigner } from "@solana/kit";
import { solanaRpc, rpcAirdrop } from "@solana/kit-plugin-rpc";
import { generatedPayer, airdropPayer } from "@solana/kit-plugin-signer";
import { getCreateAccountInstruction } from "@solana-program/system";
import {
  extension,
  fetchMint,
  fetchToken,
  findAssociatedTokenPda,
  getCreateAssociatedTokenInstructionAsync,
  getInitializeMintInstruction,
  getInitializeNonTransferableMintInstruction,
  getMintSize,
  getMintToCheckedInstruction,
  getTransferCheckedInstruction,
  TOKEN_2022_PROGRAM_ADDRESS
} from "@solana-program/token-2022";

const client = await createClient()
  .use(generatedPayer())
  .use(
    solanaRpc({
      rpcUrl: "http://localhost:8899",
      rpcSubscriptionsUrl: "ws://localhost:8900"
    })
  )
  .use(rpcAirdrop())
  .use(airdropPayer(lamports(1_000_000_000n)));

const mint = await generateKeyPairSigner();
const recipient = await generateKeyPairSigner();

const nonTransferableExtension = extension("NonTransferable", {});
const mintSpace = BigInt(getMintSize([nonTransferableExtension]));
const mintRent = await client.rpc
  .getMinimumBalanceForRentExemption(mintSpace)
  .send();

await client.sendTransaction([
  getCreateAccountInstruction({
    payer: client.payer,
    newAccount: mint,
    lamports: mintRent,
    space: mintSpace,
    programAddress: TOKEN_2022_PROGRAM_ADDRESS
  }),
  getInitializeNonTransferableMintInstruction({
    mint: mint.address // Mint account that stores the NonTransferable extension.
  }),
  getInitializeMintInstruction({
    mint: mint.address,
    decimals: 0,
    mintAuthority: client.payer.address,
    freezeAuthority: client.payer.address
  })
]);

const [sourceToken] = await findAssociatedTokenPda({
  mint: mint.address,
  owner: client.payer.address,
  tokenProgram: TOKEN_2022_PROGRAM_ADDRESS
});

const [destinationToken] = await findAssociatedTokenPda({
  mint: mint.address,
  owner: recipient.address,
  tokenProgram: TOKEN_2022_PROGRAM_ADDRESS
});

await client.sendTransaction([
  await getCreateAssociatedTokenInstructionAsync({
    payer: client.payer,
    mint: mint.address,
    owner: client.payer.address
  }),
  await getCreateAssociatedTokenInstructionAsync({
    payer: client.payer,
    mint: mint.address,
    owner: recipient.address
  }),
  getMintToCheckedInstruction({
    mint: mint.address,
    token: sourceToken,
    mintAuthority: client.payer,
    amount: 1n,
    decimals: 0
  })
]);

let transferFailure: string | undefined;
try {
  await client.sendTransaction([
    getTransferCheckedInstruction({
      source: sourceToken, // Token account sending the transfer.
      mint: mint.address, // Mint with the non-transferable configuration.
      destination: destinationToken, // Token account receiving the transfer.
      authority: client.payer, // Signer approving the transfer.
      amount: 1n, // Token amount in base units.
      decimals: 0 // Decimals defined on the mint.
    })
  ]);
} catch (error) {
  transferFailure = error instanceof Error ? error.message : String(error);
}
if (!transferFailure) {
  throw new Error("Expected the non-transferable transfer to fail");
}
console.log("Transfer failed as expected:", transferFailure);

const mintAccount = await fetchMint(client.rpc, mint.address);
const sourceTokenAccount = await fetchToken(client.rpc, sourceToken);

console.log("Mint Address:", mint.address);
console.log("Mint Extensions:", mintAccount.data.extensions);
console.log("\nSource ATA:", sourceToken);
console.log("Source Token Extensions:", sourceTokenAccount.data.extensions);
console.log("Destination ATA:", destinationToken);
```

### Web3.js v3

These examples use the class-based `@solana/web3.js` v3 API with
`@solana-program` instruction builders.

```bash Terminal
npm install @solana/web3.js@3 @solana/kit @solana-program/token-2022
```

```ts Instructions highlight={70-72,116-123}
import {
  Connection,
  Keypair,
  LAMPORTS_PER_SOL,
  PublicKey,
  sendAndConfirmTransaction,
  SystemProgram,
  Transaction
} from "@solana/web3.js";
import { unwrapOption } from "@solana/kit";
import {
  findAssociatedTokenPda,
  getCreateAssociatedTokenIdempotentInstruction,
  getInitializeMint2Instruction,
  getInitializeNonTransferableMintInstruction,
  getMintDecoder,
  getMintSize,
  getMintToCheckedInstruction,
  getTokenDecoder,
  getTransferCheckedInstruction,
  TOKEN_2022_PROGRAM_ADDRESS
} from "@solana-program/token-2022";

const connection = new Connection("http://localhost:8899", "confirmed");
const latestBlockhash = await connection.getLatestBlockhash();

const feePayer = await Keypair.generate();
const recipient = await Keypair.generate();

const airdropSignature = await connection.requestAirdrop(
  feePayer.publicKey,
  LAMPORTS_PER_SOL
);
await connection.confirmTransaction({
  blockhash: latestBlockhash.blockhash,
  lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
  signature: airdropSignature
});

const mint = await Keypair.generate();
const mintSpace = getMintSize([{ __kind: "NonTransferable" }]);
const mintRent = await connection.getMinimumBalanceForRentExemption(mintSpace);

const [sourceToken] = await findAssociatedTokenPda({
  mint: mint.publicKey.toBase58(),
  owner: feePayer.publicKey.toBase58(),
  tokenProgram: TOKEN_2022_PROGRAM_ADDRESS
});

const [destinationToken] = await findAssociatedTokenPda({
  mint: mint.publicKey.toBase58(),
  owner: recipient.publicKey.toBase58(),
  tokenProgram: TOKEN_2022_PROGRAM_ADDRESS
});

await sendAndConfirmTransaction(
  connection,
  new Transaction({
    feePayer: feePayer.publicKey,
    blockhash: latestBlockhash.blockhash,
    lastValidBlockHeight: latestBlockhash.lastValidBlockHeight
  }).add(
    SystemProgram.createAccount({
      fromPubkey: feePayer.publicKey,
      newAccountPubkey: mint.publicKey,
      lamports: mintRent,
      space: mintSpace,
      programId: new PublicKey(TOKEN_2022_PROGRAM_ADDRESS)
    }),
    getInitializeNonTransferableMintInstruction({
      mint: mint.publicKey // Mint account that stores the NonTransferable extension.
    }),
    getInitializeMint2Instruction({
      mint: mint.publicKey,
      decimals: 0,
      mintAuthority: feePayer.publicKey.toBase58(),
      freezeAuthority: feePayer.publicKey.toBase58()
    })
  ),
  [feePayer, mint],
  { commitment: "confirmed" }
);

await sendAndConfirmTransaction(
  connection,
  new Transaction().add(
    getCreateAssociatedTokenIdempotentInstruction({
      payer: feePayer,
      ata: sourceToken,
      owner: feePayer.publicKey,
      mint: mint.publicKey
    }),
    getCreateAssociatedTokenIdempotentInstruction({
      payer: feePayer,
      ata: destinationToken,
      owner: recipient.publicKey,
      mint: mint.publicKey
    }),
    getMintToCheckedInstruction({
      mint: mint.publicKey,
      token: sourceToken,
      mintAuthority: feePayer,
      amount: 1,
      decimals: 0
    })
  ),
  [feePayer],
  { commitment: "confirmed" }
);

let transferFailure: string | undefined;
try {
  await sendAndConfirmTransaction(
    connection,
    new Transaction().add(
      getTransferCheckedInstruction({
        source: sourceToken, // Token account sending the transfer.
        mint: mint.publicKey, // Mint with the non-transferable configuration.
        destination: destinationToken, // Token account receiving the transfer.
        authority: feePayer, // Signer approving the transfer.
        amount: 1, // Token amount in base units.
        decimals: 0 // Decimals defined on the mint.
      })
    ),
    [feePayer],
    { commitment: "confirmed" }
  );
} catch (error) {
  transferFailure = error instanceof Error ? error.message : String(error);
}
if (!transferFailure) {
  throw new Error("Expected the non-transferable transfer to fail");
}
console.log("Transfer failed as expected:", transferFailure);

const mintAccountInfo = await connection.getAccountInfo(mint.publicKey);
const mintAccount = getMintDecoder().decode(mintAccountInfo!.data);
const sourceAccountInfo = await connection.getAccountInfo(
  new PublicKey(sourceToken)
);
const sourceTokenAccount = getTokenDecoder().decode(sourceAccountInfo!.data);

const extensions = unwrapOption(mintAccount.extensions) ?? [];

console.log("Mint Address:", mint.publicKey.toBase58());
console.log(
  "Has NonTransferable:",
  extensions.some((extension) => extension.__kind === "NonTransferable")
);
console.log("\nSource ATA:", sourceToken);
console.log("Source Token Account:", sourceTokenAccount);
console.log("Destination ATA:", destinationToken);
```

### Rust

Add these dependencies to `Cargo.toml` (tested with Rust 1.89, 1.98, and 1.99):

```toml Cargo.toml
[dependencies]
anyhow = "1"
tokio = { version = "1", features = ["full"] }
solana-client = "2"
solana-commitment-config = "2"
solana-sdk = "2"
solana-system-interface = "1"
spl-token-2022-interface = "1"
spl-associated-token-account-interface = "1"
```

```rust Rust highlight={122-131}
use anyhow::Result;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_commitment_config::CommitmentConfig;
use solana_sdk::{
    signature::{Keypair, Signer},
    transaction::Transaction,
};
use solana_system_interface::instruction::create_account;
use spl_associated_token_account_interface::{
    address::get_associated_token_address_with_program_id,
    instruction::create_associated_token_account,
};
use spl_token_2022_interface::{
    extension::{
        non_transferable::{NonTransferable, NonTransferableAccount},
        BaseStateWithExtensions, ExtensionType, StateWithExtensions,
    },
    instruction::{
        initialize_mint, initialize_non_transferable_mint, mint_to_checked, transfer_checked,
    },
    state::{Account, Mint},
    ID as TOKEN_2022_PROGRAM_ID,
};

#[tokio::main]
async fn main() -> Result<()> {
    let client = RpcClient::new_with_commitment(
        String::from("http://localhost:8899"),
        CommitmentConfig::confirmed(),
    );
    let recipient = Keypair::new();
    let fee_payer = Keypair::new();
    let decimals = 0;

    let airdrop_signature = client
        .request_airdrop(&fee_payer.pubkey(), 1_000_000_000)
        .await?;
    loop {
        let confirmed = client.confirm_transaction(&airdrop_signature).await?;
        if confirmed {
            break;
        }
    }

    let mint = Keypair::new();
    let mint_space =
        ExtensionType::try_calculate_account_len::<Mint>(&[ExtensionType::NonTransferable])?;
    let mint_rent = client
        .get_minimum_balance_for_rent_exemption(mint_space)
        .await?;

    let mint_blockhash = client.get_latest_blockhash().await?;
    let mint_transaction = Transaction::new_signed_with_payer(
        &[
            create_account(
                &fee_payer.pubkey(),
                &mint.pubkey(),
                mint_rent,
                mint_space as u64,
                &TOKEN_2022_PROGRAM_ID,
            ),
            initialize_non_transferable_mint(&TOKEN_2022_PROGRAM_ID, &mint.pubkey())?,
            initialize_mint(
                &TOKEN_2022_PROGRAM_ID,
                &mint.pubkey(),
                &fee_payer.pubkey(),
                Some(&fee_payer.pubkey()),
                decimals,
            )?,
        ],
        Some(&fee_payer.pubkey()),
        &[&fee_payer, &mint],
        mint_blockhash,
    );
    client.send_and_confirm_transaction(&mint_transaction).await?;

    let source_token_address = get_associated_token_address_with_program_id(
        &fee_payer.pubkey(),
        &mint.pubkey(),
        &TOKEN_2022_PROGRAM_ID,
    );
    let destination_token_address = get_associated_token_address_with_program_id(
        &recipient.pubkey(),
        &mint.pubkey(),
        &TOKEN_2022_PROGRAM_ID,
    );

    let setup_blockhash = client.get_latest_blockhash().await?;
    let setup_transaction = Transaction::new_signed_with_payer(
        &[
            create_associated_token_account(
                &fee_payer.pubkey(),
                &fee_payer.pubkey(),
                &mint.pubkey(),
                &TOKEN_2022_PROGRAM_ID,
            ),
            create_associated_token_account(
                &fee_payer.pubkey(),
                &recipient.pubkey(),
                &mint.pubkey(),
                &TOKEN_2022_PROGRAM_ID,
            ),
            mint_to_checked(
                &TOKEN_2022_PROGRAM_ID,
                &mint.pubkey(),
                &source_token_address,
                &fee_payer.pubkey(),
                &[],
                1,
                decimals,
            )?,
        ],
        Some(&fee_payer.pubkey()),
        &[&fee_payer],
        setup_blockhash,
    );
    client.send_and_confirm_transaction(&setup_transaction).await?;

    let transfer_blockhash = client.get_latest_blockhash().await?;
    let transfer_transaction = Transaction::new_signed_with_payer(
        &[
            transfer_checked(
                &TOKEN_2022_PROGRAM_ID, // Token program to invoke.
                &source_token_address, // Token account sending the tokens.
                &mint.pubkey(), // Mint for the token being transferred.
                &destination_token_address, // Token account receiving the tokens.
                &fee_payer.pubkey(), // Owner or delegate approving the transfer.
                &[], // Additional multisig signers.
                1, // Token amount in base units.
                decimals, // Decimals defined on the mint account.
            )?,
        ],
        Some(&fee_payer.pubkey()),
        &[&fee_payer],
        transfer_blockhash,
    );

    match client.send_and_confirm_transaction(&transfer_transaction).await {
        Ok(signature) => anyhow::bail!(
            "Expected the non-transferable transfer to fail, but it succeeded: {signature}"
        ),
        Err(error) => println!("Transfer failed as expected: {error:#?}"),
    }

    let mint_account = client.get_account(&mint.pubkey()).await?;
    let mint_state = StateWithExtensions::<Mint>::unpack(&mint_account.data)?;
    let source_token_account = client.get_account(&source_token_address).await?;
    let source_token_state = StateWithExtensions::<Account>::unpack(&source_token_account.data)?;

    println!("Mint Address: {}", mint.pubkey());
    println!("Mint Extensions: {:?}", mint_state.get_extension_types()?);
    println!(
        "Has NonTransferable: {}",
        mint_state.get_extension::<NonTransferable>().is_ok()
    );
    println!("\nSource ATA: {}", source_token_address);
    println!(
        "Source Token Extensions: {:?}",
        source_token_state.get_extension_types()?
    );
    println!(
        "Has NonTransferableAccount: {}",
        source_token_state
            .get_extension::<NonTransferableAccount>()
            .is_ok()
    );
    println!("Destination ATA: {}", destination_token_address);

    Ok(())
}
```

### Web3.js (legacy)

These examples use legacy `@solana/web3.js` with `@solana/spl-token`.

<Warning>
  **`@solana/web3.js` 1.x is no longer actively maintained**

  It receives critical fixes only. Use [Kit](/developers/docs/clients/official/javascript#solana-kit) for new code. To migrate existing code, follow the [Kit upgrade guide](https://www.solanakit.com/docs/upgrade-guide), or the [web3.js v3 migration guide](https://github.com/solana-foundation/solana-web3.js/blob/main/docs/web3js-v1-to-v3-migration.md) to keep the class-based API.

  To run this code, install 1.x with `npm install @solana/web3.js@1`. A plain `npm install @solana/web3.js` installs v3, which this code doesn't run on.
</Warning>

```bash Terminal
npm install @solana/web3.js@1 @solana/spl-token
```

```ts Instructions highlight={75-78,129-138}
import {
  Connection,
  Keypair,
  LAMPORTS_PER_SOL,
  sendAndConfirmTransaction,
  SystemProgram,
  Transaction
} from "@solana/web3.js";
import {
  ASSOCIATED_TOKEN_PROGRAM_ID,
  createAssociatedTokenAccountInstruction,
  createInitializeMintInstruction,
  createInitializeNonTransferableMintInstruction,
  createMintToCheckedInstruction,
  createTransferCheckedInstruction,
  ExtensionType,
  getAccount,
  getAssociatedTokenAddressSync,
  getMint,
  getMintLen,
  getNonTransferable,
  TOKEN_2022_PROGRAM_ID
} from "@solana/spl-token";

const connection = new Connection("http://localhost:8899", "confirmed");
const latestBlockhash = await connection.getLatestBlockhash();

const feePayer = Keypair.generate();
const recipient = Keypair.generate();

const airdropSignature = await connection.requestAirdrop(
  feePayer.publicKey,
  LAMPORTS_PER_SOL
);
await connection.confirmTransaction({
  blockhash: latestBlockhash.blockhash,
  lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
  signature: airdropSignature
});

const mint = Keypair.generate();
const mintSpace = getMintLen([ExtensionType.NonTransferable]);
const mintRent = await connection.getMinimumBalanceForRentExemption(mintSpace);

const sourceToken = getAssociatedTokenAddressSync(
  mint.publicKey,
  feePayer.publicKey,
  false,
  TOKEN_2022_PROGRAM_ID,
  ASSOCIATED_TOKEN_PROGRAM_ID
);

const destinationToken = getAssociatedTokenAddressSync(
  mint.publicKey,
  recipient.publicKey,
  false,
  TOKEN_2022_PROGRAM_ID,
  ASSOCIATED_TOKEN_PROGRAM_ID
);

await sendAndConfirmTransaction(
  connection,
  new Transaction({
    feePayer: feePayer.publicKey,
    blockhash: latestBlockhash.blockhash,
    lastValidBlockHeight: latestBlockhash.lastValidBlockHeight
  }).add(
    SystemProgram.createAccount({
      fromPubkey: feePayer.publicKey,
      newAccountPubkey: mint.publicKey,
      lamports: mintRent,
      space: mintSpace,
      programId: TOKEN_2022_PROGRAM_ID
    }),
    createInitializeNonTransferableMintInstruction(
      mint.publicKey, // Mint account that stores the NonTransferable extension.
      TOKEN_2022_PROGRAM_ID // Token program that owns the mint.
    ),
    createInitializeMintInstruction(
      mint.publicKey,
      0,
      feePayer.publicKey,
      feePayer.publicKey,
      TOKEN_2022_PROGRAM_ID
    )
  ),
  [feePayer, mint],
  { commitment: "confirmed" }
);

await sendAndConfirmTransaction(
  connection,
  new Transaction().add(
    createAssociatedTokenAccountInstruction(
      feePayer.publicKey,
      sourceToken,
      feePayer.publicKey,
      mint.publicKey,
      TOKEN_2022_PROGRAM_ID,
      ASSOCIATED_TOKEN_PROGRAM_ID
    ),
    createAssociatedTokenAccountInstruction(
      feePayer.publicKey,
      destinationToken,
      recipient.publicKey,
      mint.publicKey,
      TOKEN_2022_PROGRAM_ID,
      ASSOCIATED_TOKEN_PROGRAM_ID
    ),
    createMintToCheckedInstruction(
      mint.publicKey,
      sourceToken,
      feePayer.publicKey,
      1,
      0,
      [],
      TOKEN_2022_PROGRAM_ID
    )
  ),
  [feePayer],
  { commitment: "confirmed" }
);

let transferFailure: string | undefined;
try {
  await sendAndConfirmTransaction(
    connection,
    new Transaction().add(
      createTransferCheckedInstruction(
        sourceToken, // Token account sending the transfer.
        mint.publicKey, // Mint with the non-transferable configuration.
        destinationToken, // Token account receiving the transfer.
        feePayer.publicKey, // Signer approving the transfer.
        1, // Token amount in base units.
        0, // Decimals defined on the mint.
        [], // Additional multisig signers.
        TOKEN_2022_PROGRAM_ID // Token program that processes the transfer.
      )
    ),
    [feePayer],
    { commitment: "confirmed" }
  );
} catch (error) {
  transferFailure = error instanceof Error ? error.message : String(error);
}
if (!transferFailure) {
  throw new Error("Expected the non-transferable transfer to fail");
}
console.log("Transfer failed as expected:", transferFailure);

const mintAccount = await getMint(
  connection,
  mint.publicKey,
  "confirmed",
  TOKEN_2022_PROGRAM_ID
);
const sourceTokenAccount = await getAccount(
  connection,
  sourceToken,
  "confirmed",
  TOKEN_2022_PROGRAM_ID
);

console.log("Mint Address:", mint.publicKey.toBase58());
console.log("Has NonTransferable:", getNonTransferable(mintAccount) !== null);
console.log("\nSource ATA:", sourceToken.toBase58());
console.log("Source Token Account:", sourceTokenAccount);
console.log("Destination ATA:", destinationToken.toBase58());
```
