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

# Immutable Owner

> Initialize a Token Extension Program token account with immutable ownership so its owner can never be reassigned.

## What Is Immutable Owner?

The Token Extension Program's `ImmutableOwner` account extension makes a
token account's owner permanent.

Once a token account is initialized with `ImmutableOwner`, later
`SetAuthority` instructions cannot change its `AccountOwner` authority.

<Info>
  **Associated Token Accounts**

  Associated token accounts created through the Associated Token Program for the
  Token Extension Program automatically initialize `ImmutableOwner` on the
  token account.
</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 Initialize an Immutable Owner Account

To initialize an immutable owner account:

1. Create and initialize a mint.
2. Create a token account with enough space for `ImmutableOwner`.
3. Initialize `ImmutableOwner` on the token account before
   `InitializeAccount`.
4. Attempting to change the account owner later with `SetAuthority` fails
   with `TokenError::ImmutableOwner`.

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

    ```ts Example focus={36,38}
    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 tokenAccount = await generateKeyPairSigner();

    const mintSpace = BigInt(getMintSize());
    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
      }),
      getInitializeMintInstruction({
        mint: mint.address,
        decimals: 0,
        mintAuthority: client.payer.address,
        freezeAuthority: client.payer.address
      })
    ]);

    const immutableOwnerExtension = extension("ImmutableOwner", {});

    const tokenSpace = BigInt(getTokenSize([immutableOwnerExtension]));
    ```
  </Step>

  <Step title="Calculate rent">
    Calculate rent using the token account size needed for the `ImmutableOwner`
    extension.

    ```ts Example focus={40-42} expandable
    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 tokenAccount = await generateKeyPairSigner();

    const mintSpace = BigInt(getMintSize());
    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
      }),
      getInitializeMintInstruction({
        mint: mint.address,
        decimals: 0,
        mintAuthority: client.payer.address,
        freezeAuthority: client.payer.address
      })
    ]);

    const immutableOwnerExtension = extension("ImmutableOwner", {});

    const tokenSpace = BigInt(getTokenSize([immutableOwnerExtension]));

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

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

    ```ts Example focus={44-52} expandable
    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 tokenAccount = await generateKeyPairSigner();

    const mintSpace = BigInt(getMintSize());
    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
      }),
      getInitializeMintInstruction({
        mint: mint.address,
        decimals: 0,
        mintAuthority: client.payer.address,
        freezeAuthority: client.payer.address
      })
    ]);

    const immutableOwnerExtension = extension("ImmutableOwner", {});

    const tokenSpace = BigInt(getTokenSize([immutableOwnerExtension]));

    const tokenRent = await client.rpc
      .getMinimumBalanceForRentExemption(tokenSpace)
      .send();

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

  <Step title="Initialize ImmutableOwner">
    Initialize the `ImmutableOwner` extension on the token account.

    ```ts Example focus={52-54} expandable
    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 tokenAccount = await generateKeyPairSigner();

    const mintSpace = BigInt(getMintSize());
    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
      }),
      getInitializeMintInstruction({
        mint: mint.address,
        decimals: 0,
        mintAuthority: client.payer.address,
        freezeAuthority: client.payer.address
      })
    ]);

    const immutableOwnerExtension = extension("ImmutableOwner", {});

    const tokenSpace = BigInt(getTokenSize([immutableOwnerExtension]));

    const tokenRent = await client.rpc
      .getMinimumBalanceForRentExemption(tokenSpace)
      .send();

    await client.sendTransaction([
      getCreateAccountInstruction({
        payer: client.payer,
        newAccount: tokenAccount,
        lamports: tokenRent,
        space: tokenSpace,
        programAddress: TOKEN_2022_PROGRAM_ADDRESS
      }),
      getInitializeImmutableOwnerInstruction({
        account: tokenAccount.address
      })
    ]);
    ```
  </Step>

  <Step title="Initialize the token account">
    Initialize the token account with `InitializeAccount` in the same
    transaction.

    ```ts Example focus={55-59} expandable
    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 tokenAccount = await generateKeyPairSigner();

    const mintSpace = BigInt(getMintSize());
    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
      }),
      getInitializeMintInstruction({
        mint: mint.address,
        decimals: 0,
        mintAuthority: client.payer.address,
        freezeAuthority: client.payer.address
      })
    ]);

    const immutableOwnerExtension = extension("ImmutableOwner", {});

    const tokenSpace = BigInt(getTokenSize([immutableOwnerExtension]));

    const tokenRent = await client.rpc
      .getMinimumBalanceForRentExemption(tokenSpace)
      .send();

    await client.sendTransaction([
      getCreateAccountInstruction({
        payer: client.payer,
        newAccount: tokenAccount,
        lamports: tokenRent,
        space: tokenSpace,
        programAddress: TOKEN_2022_PROGRAM_ADDRESS
      }),
      getInitializeImmutableOwnerInstruction({
        account: tokenAccount.address
      }),
      getInitializeAccountInstruction({
        account: tokenAccount.address,
        mint: mint.address,
        owner: client.payer.address
      })
    ]);
    ```
  </Step>
</Steps>

<Info>
  **Instruction Order**

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

### Source Reference

| Item                                 | Description                                                                                     | Source                                                                                                                           |
| ------------------------------------ | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `ImmutableOwner`                     | Account extension that marks a token account owner as immutable.                                | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/interface/src/extension/immutable_owner.rs#L13-L17) |
| `InitializeImmutableOwner`           | Instruction that initializes the immutable-owner extension on an uninitialized token account.   | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/interface/src/instruction.rs#L1845-L1856)           |
| `process_initialize_immutable_owner` | Processor logic that allocates and initializes `ImmutableOwner` on the account.                 | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/program/src/processor.rs#L1418-L1429)               |
| `SetAuthority`                       | Base token instruction used to change authorities, including a token account owner.             | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/interface/src/instruction.rs#L1488-L1520)           |
| `process_set_authority`              | Processor logic that rejects owner changes when the token account has `ImmutableOwner` enabled. | [Source](https://github.com/solana-program/token-2022/blob/program%40v10.0.0/program/src/processor.rs#L676-L978)                 |

### 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={76-78,93-98}
import {
  lamports,
  createClient,
  generateKeyPairSigner,
  isSolanaError,
  SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,
  unwrapOption
} 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 {
  AuthorityType,
  extension,
  fetchToken,
  getInitializeAccountInstruction,
  getInitializeImmutableOwnerInstruction,
  getInitializeMintInstruction,
  getMintSize,
  getSetAuthorityInstruction,
  getTokenSize,
  isExtension,
  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 tokenAccount = await generateKeyPairSigner();
const newOwner = await generateKeyPairSigner();

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

await client.sendTransaction([
  getCreateAccountInstruction({
    payer: client.payer, // Account funding the new mint account.
    newAccount: mint, // New mint account to create.
    lamports: mintRent, // Lamports funding the mint account rent.
    space: mintSpace, // Account size in bytes for the mint.
    programAddress: TOKEN_2022_PROGRAM_ADDRESS // Program that owns the mint account.
  }),
  getInitializeMintInstruction({
    mint: mint.address, // Mint account to initialize.
    decimals: 0, // Number of decimals for the token.
    mintAuthority: client.payer.address, // Authority allowed to mint new tokens.
    freezeAuthority: client.payer.address // Authority allowed to freeze token accounts.
  })
]);

const immutableOwnerExtension = extension("ImmutableOwner", {});
const tokenSpace = BigInt(getTokenSize([immutableOwnerExtension]));
const tokenRent = await client.rpc
  .getMinimumBalanceForRentExemption(tokenSpace)
  .send();

await client.sendTransaction([
  getCreateAccountInstruction({
    payer: client.payer, // Account funding the new token account.
    newAccount: tokenAccount, // New token account to create.
    lamports: tokenRent, // Lamports funding the token account rent.
    space: tokenSpace, // Account size in bytes for the token account plus ImmutableOwner.
    programAddress: TOKEN_2022_PROGRAM_ADDRESS // Program that owns the token account.
  }),
  getInitializeImmutableOwnerInstruction({
    account: tokenAccount.address // Token account that stores the ImmutableOwner extension.
  }),
  getInitializeAccountInstruction({
    account: tokenAccount.address, // Token account to initialize.
    mint: mint.address, // Mint for the token account.
    owner: client.payer.address // Owner of the token account.
  })
]);

// TokenError::ImmutableOwner. @solana-program/token-2022 only exports
// constants for the base token errors (0-19).
const TOKEN_ERROR_IMMUTABLE_OWNER = 0x22;

let failure: string | undefined;
try {
  await client.sendTransaction([
    getSetAuthorityInstruction({
      owned: tokenAccount.address, // Token account whose authority is being updated.
      owner: client.payer, // Current token account owner signing the instruction.
      authorityType: AuthorityType.AccountOwner, // Account authority field to change.
      newAuthority: newOwner.address // New token account owner to set.
    })
  ]);
} catch (error) {
  // Walk the error's causes to the custom program error from the instruction.
  let cause: unknown = error;
  while (
    cause instanceof Error &&
    !isSolanaError(cause, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM)
  ) {
    cause = cause.cause;
  }
  if (
    !isSolanaError(cause, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) ||
    cause.context.code !== TOKEN_ERROR_IMMUTABLE_OWNER
  ) {
    throw error;
  }
  failure = `custom program error: 0x${cause.context.code.toString(16)} (TokenError::ImmutableOwner)`;
}
if (!failure) {
  throw new Error("Expected the owner change to fail");
}

const token = await fetchToken(client.rpc, tokenAccount.address);
const immutableOwnerExtensionState = (
  unwrapOption(token.data.extensions) ?? []
).find((item) => isExtension("ImmutableOwner", item));

console.log("Mint Address:", mint.address);
console.log("Token Account:", tokenAccount.address);
console.log("ImmutableOwner Extension:", immutableOwnerExtensionState);
console.log("SetAuthority Failure:", failure);
```

### 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={72-75,107-112}
import {
  Connection,
  Keypair,
  PublicKey,
  sendAndConfirmTransaction,
  SystemProgram,
  Transaction,
  LAMPORTS_PER_SOL
} from "@solana/web3.js";
import { unwrapOption } from "@solana/kit";
import {
  AuthorityType,
  getInitializeAccountInstruction,
  getInitializeImmutableOwnerInstruction,
  getInitializeMint2Instruction,
  getMintSize,
  getSetAuthorityInstruction,
  getTokenDecoder,
  getTokenSize,
  TOKEN_2022_PROGRAM_ADDRESS
} from "@solana-program/token-2022";

const connection = new Connection("http://localhost:8899", "confirmed");
const feePayer = await Keypair.generate();
const newOwner = await Keypair.generate();

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

const mint = await Keypair.generate();

const mintLength = getMintSize();

const mintRent = await connection.getMinimumBalanceForRentExemption(mintLength);

const tokenAccount = await Keypair.generate();
const tokenAccountLen = getTokenSize([{ __kind: "ImmutableOwner" }]);
const tokenAccountRent =
  await connection.getMinimumBalanceForRentExemption(tokenAccountLen);

const createMintAccountInstruction = SystemProgram.createAccount({
  fromPubkey: feePayer.publicKey, // Account funding the new mint account.
  newAccountPubkey: mint.publicKey, // New mint account to create.
  space: mintLength, // Account size in bytes for the mint.
  lamports: mintRent, // Lamports funding the mint account rent.
  programId: new PublicKey(TOKEN_2022_PROGRAM_ADDRESS) // Program that owns the mint account.
});

const initializeMintInstruction = getInitializeMint2Instruction({
  mint: mint.publicKey, // Mint account to initialize.
  decimals: 0, // Number of decimals for the token.
  mintAuthority: feePayer.publicKey.toBase58(), // Authority allowed to mint new tokens.
  freezeAuthority: feePayer.publicKey.toBase58() // Authority allowed to freeze token accounts.
});

const createTokenAccountInstruction = SystemProgram.createAccount({
  fromPubkey: feePayer.publicKey, // Account funding the new token account.
  newAccountPubkey: tokenAccount.publicKey, // New token account to create.
  space: tokenAccountLen, // Account size in bytes for the token account plus ImmutableOwner.
  lamports: tokenAccountRent, // Lamports funding the token account rent.
  programId: new PublicKey(TOKEN_2022_PROGRAM_ADDRESS) // Program that owns the token account.
});

const initializeImmutableOwnerInstruction =
  getInitializeImmutableOwnerInstruction({
    account: tokenAccount.publicKey // Token account that stores the ImmutableOwner extension.
  });

const initializeTokenAccountInstruction = getInitializeAccountInstruction({
  account: tokenAccount.publicKey, // Token account to initialize.
  mint: mint.publicKey, // Mint for the token account.
  owner: feePayer.publicKey // Owner of the token account.
});

await sendAndConfirmTransaction(
  connection,
  new Transaction().add(
    createMintAccountInstruction,
    initializeMintInstruction
  ),
  [feePayer, mint]
);

await sendAndConfirmTransaction(
  connection,
  new Transaction().add(
    createTokenAccountInstruction,
    initializeImmutableOwnerInstruction,
    initializeTokenAccountInstruction
  ),
  [feePayer, tokenAccount]
);

let failure: string | undefined;
try {
  await sendAndConfirmTransaction(
    connection,
    new Transaction().add(
      getSetAuthorityInstruction({
        owned: tokenAccount.publicKey, // Token account whose authority is being updated.
        owner: feePayer, // Current token account owner signing the instruction.
        authorityType: AuthorityType.AccountOwner, // Account authority field to change.
        newAuthority: newOwner.publicKey.toBase58() // New token account owner to set.
      })
    ),
    [feePayer]
  );
} catch (error) {
  failure = String(error);
}
if (!failure) {
  throw new Error("Expected the owner change to fail");
}

const tokenAccountInfo = await connection.getAccountInfo(
  tokenAccount.publicKey,
  "confirmed"
);
const tokenAccountData = getTokenDecoder().decode(tokenAccountInfo!.data);
const immutableOwnerExtension = (
  unwrapOption(tokenAccountData.extensions) ?? []
).find((extension) => extension.__kind === "ImmutableOwner");

console.log("Mint Address:", mint.publicKey.toBase58());
console.log("Token Account:", tokenAccount.publicKey.toBase58());
console.log("ImmutableOwner Extension:", immutableOwnerExtension);
console.log("SetAuthority Failure:", failure);
```

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

```rust Rust highlight={89-92,114-121}
use anyhow::{anyhow, Result};
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_commitment_config::CommitmentConfig;
use solana_sdk::{
    program_pack::Pack,
    signature::{Keypair, Signer},
    transaction::Transaction,
};
use solana_system_interface::instruction::create_account;
use spl_token_2022_interface::{
    extension::{
        immutable_owner::ImmutableOwner, BaseStateWithExtensions, ExtensionType,
        StateWithExtensions,
    },
    instruction::{
        initialize_account, initialize_immutable_owner, initialize_mint, set_authority,
        AuthorityType,
    },
    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 fee_payer = Keypair::new();

    let airdrop_signature = client
        .request_airdrop(&fee_payer.pubkey(), 5_000_000_000)
        .await?;

    loop {
        let confirmed = client.confirm_transaction(&airdrop_signature).await?;
        if confirmed {
            break;
        }
    }

    let mint = Keypair::new();

    let mint_space = Mint::LEN;
    let mint_rent = client
        .get_minimum_balance_for_rent_exemption(mint_space)
        .await?;

    let create_mint_account_instruction = create_account(
        &fee_payer.pubkey(),    // Account funding the new mint account.
        &mint.pubkey(),         // New mint account to create.
        mint_rent,              // Lamports funding the mint account rent.
        mint_space as u64,      // Account size in bytes for the mint.
        &TOKEN_2022_PROGRAM_ID, // Program that owns the mint account.
    );

    let initialize_mint_instruction = initialize_mint(
        &TOKEN_2022_PROGRAM_ID,    // Program that owns the mint account.
        &mint.pubkey(),            // Mint account to initialize.
        &fee_payer.pubkey(),       // Authority allowed to mint new tokens.
        Some(&fee_payer.pubkey()), // Authority allowed to freeze token accounts.
        0,                         // Number of decimals for the token.
    )?;

    let token_account = Keypair::new();

    let token_account_space =
        ExtensionType::try_calculate_account_len::<Account>(&[ExtensionType::ImmutableOwner])?;

    let token_account_rent = client
        .get_minimum_balance_for_rent_exemption(token_account_space)
        .await?;

    let create_token_account_instruction = create_account(
        &fee_payer.pubkey(),        // Account funding the new token account.
        &token_account.pubkey(),    // New token account to create.
        token_account_rent,         // Lamports funding the token account rent.
        token_account_space as u64, // Account size in bytes for the token account plus ImmutableOwner.
        &TOKEN_2022_PROGRAM_ID,     // Program that owns the token account.
    );

    let initialize_token_account = initialize_account(
        &TOKEN_2022_PROGRAM_ID,  // Token program that owns the token account.
        &token_account.pubkey(), // Token account to initialize.
        &mint.pubkey(),          // Mint for the token account.
        &fee_payer.pubkey(),     // Owner of the token account.
    )?;

    let init_immutable_owner_instruction =
        initialize_immutable_owner(
            &TOKEN_2022_PROGRAM_ID, // Token program that owns the token account.
            &token_account.pubkey(), // Token account that stores the ImmutableOwner extension.
        )?;

    let transaction = Transaction::new_signed_with_payer(
        &[
            create_mint_account_instruction,
            initialize_mint_instruction,
            create_token_account_instruction,
            init_immutable_owner_instruction,
            initialize_token_account,
        ],
        Some(&fee_payer.pubkey()),
        &[&fee_payer, &mint, &token_account],
        client.get_latest_blockhash().await?,
    );

    client.send_and_confirm_transaction(&transaction).await?;

    let token_account_data = client.get_account(&token_account.pubkey()).await?;
    let token_account_state = StateWithExtensions::<Account>::unpack(&token_account_data.data)?;

    let new_owner = Keypair::new();
    let set_authority_instruction = set_authority(
        &TOKEN_2022_PROGRAM_ID, // Token program that owns the token account.
        &token_account.pubkey(), // Token account whose authority is being updated.
        Some(&new_owner.pubkey()), // New token account owner to set.
        AuthorityType::AccountOwner, // Account authority field to change.
        &fee_payer.pubkey(), // Current token account owner signing the instruction.
        &[], // Additional multisig signers.
    )?;

    let set_authority_transaction = Transaction::new_signed_with_payer(
        &[set_authority_instruction],
        Some(&fee_payer.pubkey()),
        &[&fee_payer],
        client.get_latest_blockhash().await?,
    );

    let failure = match client
        .send_and_confirm_transaction(&set_authority_transaction)
        .await
    {
        Ok(sig) => return Err(anyhow!("Expected the owner change to fail: {}", sig)),
        Err(e) => format!("{:#?}", e),
    };

    let immutable_owner_extension = token_account_state.get_extension::<ImmutableOwner>()?;

    println!("Mint Address: {}", mint.pubkey());
    println!("Token Account: {}", token_account.pubkey());
    println!("ImmutableOwner Extension: {:#?}", immutable_owner_extension);
    println!("SetAuthority Failure: {}", failure);

    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={74-78,111-118}
import {
  Connection,
  Keypair,
  sendAndConfirmTransaction,
  SystemProgram,
  Transaction,
  LAMPORTS_PER_SOL
} from "@solana/web3.js";
import {
  AuthorityType,
  createInitializeMintInstruction,
  createInitializeAccountInstruction,
  createInitializeImmutableOwnerInstruction,
  createSetAuthorityInstruction,
  ExtensionType,
  getAccount,
  getAccountLen,
  getImmutableOwner,
  getMintLen,
  TOKEN_2022_PROGRAM_ID
} from "@solana/spl-token";

const connection = new Connection("http://localhost:8899", "confirmed");
const feePayer = Keypair.generate();
const newOwner = Keypair.generate();

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

const mint = Keypair.generate();

const mintLength = getMintLen([]);

const mintRent = await connection.getMinimumBalanceForRentExemption(mintLength);

const extensions = [ExtensionType.ImmutableOwner];
const tokenAccount = new Keypair();
const tokenAccountLen = getAccountLen(extensions);
const tokenAccountRent =
  await connection.getMinimumBalanceForRentExemption(tokenAccountLen);

const createMintAccountInstruction = SystemProgram.createAccount({
  fromPubkey: feePayer.publicKey, // Account funding the new mint account.
  newAccountPubkey: mint.publicKey, // New mint account to create.
  space: mintLength, // Account size in bytes for the mint.
  lamports: mintRent, // Lamports funding the mint account rent.
  programId: TOKEN_2022_PROGRAM_ID // Program that owns the mint account.
});

const initializeMintInstruction = createInitializeMintInstruction(
  mint.publicKey, // Mint account to initialize.
  0, // Number of decimals for the token.
  feePayer.publicKey, // Authority allowed to mint new tokens.
  feePayer.publicKey, // Authority allowed to freeze token accounts.
  TOKEN_2022_PROGRAM_ID // Program that owns the mint account.
);

const createTokenAccountInstruction = SystemProgram.createAccount({
  fromPubkey: feePayer.publicKey, // Account funding the new token account.
  newAccountPubkey: tokenAccount.publicKey, // New token account to create.
  space: tokenAccountLen, // Account size in bytes for the token account plus ImmutableOwner.
  lamports: tokenAccountRent, // Lamports funding the token account rent.
  programId: TOKEN_2022_PROGRAM_ID // Program that owns the token account.
});

const initializeImmutableOwnerInstruction =
  createInitializeImmutableOwnerInstruction(
    tokenAccount.publicKey, // Token account that stores the ImmutableOwner extension.
    TOKEN_2022_PROGRAM_ID // Token program that owns the token account.
  );

const initializeTokenAccountInstruction = createInitializeAccountInstruction(
  tokenAccount.publicKey, // Token account to initialize.
  mint.publicKey, // Mint for the token account.
  feePayer.publicKey, // Owner of the token account.
  TOKEN_2022_PROGRAM_ID // Token program that owns the token account.
);

await sendAndConfirmTransaction(
  connection,
  new Transaction().add(
    createMintAccountInstruction,
    initializeMintInstruction
  ),
  [feePayer, mint]
);

await sendAndConfirmTransaction(
  connection,
  new Transaction().add(
    createTokenAccountInstruction,
    initializeImmutableOwnerInstruction,
    initializeTokenAccountInstruction
  ),
  [feePayer, tokenAccount]
);

let failure: string | undefined;
try {
  await sendAndConfirmTransaction(
    connection,
    new Transaction().add(
      createSetAuthorityInstruction(
        tokenAccount.publicKey, // Token account whose authority is being updated.
        feePayer.publicKey, // Current token account owner signing the instruction.
        AuthorityType.AccountOwner, // Account authority field to change.
        newOwner.publicKey, // New token account owner to set.
        [], // Additional multisig signers.
        TOKEN_2022_PROGRAM_ID // Token program that owns the token account.
      )
    ),
    [feePayer]
  );
} catch (error) {
  failure = String(error);
}
if (!failure) {
  throw new Error("Expected the owner change to fail");
}

const tokenAccountData = await getAccount(
  connection,
  tokenAccount.publicKey,
  "confirmed",
  TOKEN_2022_PROGRAM_ID
);
const immutableOwnerExtension = getImmutableOwner(tokenAccountData);

console.log("Mint Address:", mint.publicKey.toBase58());
console.log("Token Account:", tokenAccount.publicKey.toBase58());
console.log("ImmutableOwner Extension:", immutableOwnerExtension);
console.log("SetAuthority Failure:", failure);
```
